file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./libs/maths/SafeMath.sol";
import "./libs/string.sol";
import "./interfaces/IERC20.sol";
import "./libs/sort.sol";
struct GlqStaker {
address wallet;
uint256 block_number;
uint256 amount;
uint256 index_at;
bool already_withdrawn;
}
struct GraphLinqApyStruct {
uint256 tier1Apy;
uint256 tier2Apy;
uint256 tier3Apy;
}
contract GlqStakingContract {
using SafeMath for uint256;
using strings for *;
using QuickSorter for *;
event NewStakerRegistered (
address staker_address,
uint256 at_block,
uint256 amount_registered
);
/*
** Address of the GLQ token hash: 0x9F9c8ec3534c3cE16F928381372BfbFBFb9F4D24
*/
address private _glqTokenAddress;
/*
** Manager of the contract to add/remove APYs bonuses into the staking contract
*/
address private _glqDeployerManager;
/*
** Current amount of GLQ available in the pool as rewards
*/
uint256 private _totalGlqIncentive;
GlqStaker[] private _stakers;
uint256 private _stakersIndex;
uint256 private _totalStaked;
bool private _emergencyWithdraw;
mapping(address => uint256) private _indexStaker;
uint256 private _blocksPerYear;
GraphLinqApyStruct private _apyStruct;
constructor(address glqAddr, address manager) {
_glqTokenAddress = glqAddr;
_glqDeployerManager = manager;
_totalStaked = 0;
_stakersIndex = 1;
_blocksPerYear = 2250000;
// default t1: 30%, t2: 15%, t3: 7.5%
_apyStruct = GraphLinqApyStruct(50*1e18, 25*1e18, 12500000000000000000);
}
/* Getter ---- Read-Only */
/*
** Return the sender wallet position from the tier system
*/
function getWalletCurrentTier(address wallet) public view returns (uint256) {
uint256 currentTier = 3;
uint256 index = _indexStaker[wallet];
require(
index != 0,
"You dont have any tier rank currently in the Staking contract."
);
uint256 walletAggregatedIndex = (index).mul(1e18);
// Total length of stakers
uint256 totalIndex = _stakers.length.mul(1e18);
// 15% of hodlers in T1
uint256 t1MaxIndex = totalIndex.div(100).mul(15);
// 55% of hodlers in T2
uint256 t2MaxIndex = totalIndex.div(100).mul(55);
if (walletAggregatedIndex <= t1MaxIndex) {
currentTier = 1;
} else if (walletAggregatedIndex > t1MaxIndex && walletAggregatedIndex <= t2MaxIndex) {
currentTier = 2;
}
return currentTier;
}
/*
** Return rank position of a wallet
*/
function getPosition(address wallet) public view returns (uint256) {
uint256 index = _indexStaker[wallet];
return index;
}
/*
** Return the amount of GLQ that a wallet can currently claim from the staking contract
*/
function getGlqToClaim(address wallet) public view returns(uint256) {
uint256 index = _indexStaker[wallet];
require (index > 0, "Invalid staking index");
GlqStaker storage staker = _stakers[index - 1];
uint256 calculatedApr = getWaitingPercentAPR(wallet);
return staker.amount.mul(calculatedApr).div(100).div(1e18);
}
/*
** Return the current percent winnable for a staker wallet
*/
function getWaitingPercentAPR(address wallet) public view returns(uint256) {
uint256 index = _indexStaker[wallet];
require (index > 0, "Invalid staking index");
GlqStaker storage staker = _stakers[index - 1];
uint256 walletTier = getWalletCurrentTier(wallet);
uint256 blocksSpent = block.number.sub(staker.block_number);
if (blocksSpent == 0) { return 0; }
uint256 percentYearSpent = percent(blocksSpent.mul(10000), _blocksPerYear.mul(10000), 20);
uint256 percentAprGlq = _apyStruct.tier3Apy;
if (walletTier == 1) {
percentAprGlq = _apyStruct.tier1Apy;
} else if (walletTier == 2) {
percentAprGlq = _apyStruct.tier2Apy;
}
return percentAprGlq.mul(percentYearSpent).div(100).div(1e18);
}
/*
** Return the total amount of GLQ as incentive rewards in the contract
*/
function getTotalIncentive() public view returns (uint256) {
return _totalGlqIncentive;
}
/*
** Return the total amount in staking for an hodler.
*/
function getDepositedGLQ(address wallet) public view returns (uint256) {
uint256 index = _indexStaker[wallet];
if (index == 0) { return 0; }
return _stakers[index-1].amount;
}
/*
** Count the total numbers of stakers in the contract
*/
function getTotalStakers() public view returns(uint256) {
return _stakers.length;
}
/*
** Return all APY per different Tier
*/
function getTiersAPY() public view returns(uint256, uint256, uint256) {
return (_apyStruct.tier1Apy, _apyStruct.tier2Apy, _apyStruct.tier3Apy);
}
/*
** Return the Total staked amount
*/
function getTotalStaked() public view returns(uint256) {
return _totalStaked;
}
/*
** Return the top 3 of stakers (by age)
*/
function getTopStakers() public view returns(address[] memory, uint256[] memory) {
uint256 len = _stakers.length;
address[] memory addresses = new address[](3);
uint256[] memory amounts = new uint256[](3);
for (uint i = 0; i < len && i <= 2; i++) {
addresses[i] = _stakers[i].wallet;
amounts[i] = _stakers[i].amount;
}
return (addresses, amounts);
}
/*
** Return the total amount deposited on a rank tier
*/
function getTierTotalStaked(uint tier) public view returns (uint256) {
uint256 totalAmount = 0;
// Total length of stakers
uint256 totalIndex = _stakers.length.mul(1e18);
// 15% of hodlers in T1
uint256 t1MaxIndex = totalIndex.div(100).mul(15);
// 55% of hodlers in T2
uint256 t2MaxIndex = totalIndex.div(100).mul(55);
uint startIndex = (tier == 1) ? 0 : t1MaxIndex.div(1e18);
uint endIndex = (tier == 1) ? t1MaxIndex.div(1e18) : t2MaxIndex.div(1e18);
if (tier == 3) {
startIndex = t2MaxIndex.div(1e18);
endIndex = _stakers.length;
}
for (uint i = startIndex; i <= endIndex && i < _stakers.length; i++) {
totalAmount += _stakers[i].amount;
}
return totalAmount;
}
/* Getter ---- Read-Only */
/* Setter - Read & Modifications */
/*
** Enable emergency withdraw by GLQ Deployer
*/
function setEmergencyWithdraw(bool state) public {
require (
msg.sender == _glqDeployerManager,
"Only the Glq Deployer can change the state of the emergency withdraw"
);
_emergencyWithdraw = state;
}
/*
** Set numbers of blocks spent per year to calculate claim rewards
*/
function setBlocksPerYear(uint256 blocks) public {
require(
msg.sender == _glqDeployerManager,
"Only the Glq Deployer can change blocks spent per year");
_blocksPerYear = blocks;
}
/*
** Update the APY rewards for each tier in percent per year
*/
function setApyPercentRewards(uint256 t1, uint256 t2, uint256 t3) public {
require(
msg.sender == _glqDeployerManager,
"Only the Glq Deployer can APY rewards");
GraphLinqApyStruct memory newApy = GraphLinqApyStruct(t1, t2, t3);
_apyStruct = newApy;
}
/*
** Add GLQ liquidity in the staking contract for stakers rewards
*/
function addIncentive(uint256 glqAmount) public {
IERC20 glqToken = IERC20(_glqTokenAddress);
require(
msg.sender == _glqDeployerManager,
"Only the Glq Deployer can add incentive into the smart-contract");
require(
glqToken.balanceOf(msg.sender) >= glqAmount,
"Insufficient funds from the deployer contract");
require(
glqToken.transferFrom(msg.sender, address(this), glqAmount) == true,
"Error transferFrom on the contract"
);
_totalGlqIncentive += glqAmount;
}
/*
** Remove GLQ liquidity from the staking contract for stakers rewards
*/
function removeIncentive(uint256 glqAmount) public {
IERC20 glqToken = IERC20(_glqTokenAddress);
require(
msg.sender == _glqDeployerManager,
"Only the Glq Deployer can remove incentive from the smart-contract");
require(
glqToken.balanceOf(address(this)) >= glqAmount,
"Insufficient funds from the deployer contract");
require(
glqToken.transfer(msg.sender, glqAmount) == true,
"Error transfer on the contract"
);
_totalGlqIncentive -= glqAmount;
}
/*
** Deposit GLQ in the staking contract to stake & earn
*/
function depositGlq(uint256 glqAmount) public {
IERC20 glqToken = IERC20(_glqTokenAddress);
require(
glqToken.balanceOf(msg.sender) >= glqAmount,
"Insufficient funds from the sender");
require(
glqToken.transferFrom(msg.sender, address(this), glqAmount) == true,
"Error transferFrom on the contract"
);
uint256 index = _indexStaker[msg.sender];
_totalStaked += glqAmount;
if (index == 0) {
GlqStaker memory staker = GlqStaker(msg.sender, block.number, glqAmount, _stakersIndex, false);
_stakers.push(staker);
_indexStaker[msg.sender] = _stakersIndex;
// emit event of a new staker registered at current block position
emit NewStakerRegistered(msg.sender, block.number, glqAmount);
_stakersIndex = _stakersIndex.add(1);
}
else {
// claim rewards before adding new staking amount
if (_stakers[index-1].amount > 0) {
claimGlq();
}
_stakers[index-1].amount += glqAmount;
}
}
function removeStaker(GlqStaker storage staker) private {
uint256 currentIndex = _indexStaker[staker.wallet]-1;
_indexStaker[staker.wallet] = 0;
for (uint256 i= currentIndex ; i < _stakers.length-1 ; i++) {
_stakers[i] = _stakers[i+1];
_stakers[i].index_at = _stakers[i].index_at.sub(1);
_indexStaker[_stakers[i].wallet] = _stakers[i].index_at;
}
_stakers.pop();
// Remove the staker and decrease stakers index
_stakersIndex = _stakersIndex.sub(1);
if (_stakersIndex == 0) { _stakersIndex = 1; }
}
/*
** Emergency withdraw enabled by GLQ team in an emergency case
*/
function emergencyWithdraw() public {
require(
_emergencyWithdraw == true,
"The emergency withdraw feature is not enabled"
);
uint256 index = _indexStaker[msg.sender];
require (index > 0, "Invalid staking index");
GlqStaker storage staker = _stakers[index - 1];
IERC20 glqToken = IERC20(_glqTokenAddress);
require(
staker.amount > 0,
"Not funds deposited in the staking contract");
require(
glqToken.transfer(msg.sender, staker.amount) == true,
"Error transfer on the contract"
);
staker.amount = 0;
}
/*
** Withdraw Glq from the staking contract (reduce the tier position)
*/
function withdrawGlq() public {
uint256 index = _indexStaker[msg.sender];
require (index > 0, "Invalid staking index");
GlqStaker storage staker = _stakers[index - 1];
IERC20 glqToken = IERC20(_glqTokenAddress);
require(
staker.amount > 0,
"Not funds deposited in the staking contract");
//auto claim when withdraw
claimGlq();
_totalStaked -= staker.amount;
require(
glqToken.balanceOf(address(this)) >= staker.amount,
"Insufficient funds from the deployer contract");
require(
glqToken.transfer(msg.sender, staker.amount) == true,
"Error transfer on the contract"
);
staker.amount = 0;
if (staker.already_withdrawn) {
removeStaker(staker);
} else {
staker.already_withdrawn = true;
}
}
function percent(uint256 numerator, uint256 denominator, uint256 precision) private pure returns(uint256) {
uint256 _numerator = numerator * 10 ** (precision+1);
// with rounding of last digit
uint256 _quotient = ((_numerator / denominator) + 5) / 10;
return ( _quotient);
}
/*
** Claim waiting rewards from the staking contract
*/
function claimGlq() public returns(uint256) {
uint256 index = _indexStaker[msg.sender];
require (index > 0, "Invalid staking index");
GlqStaker storage staker = _stakers[index - 1];
uint256 glqToClaim = getGlqToClaim(msg.sender);
IERC20 glqToken = IERC20(_glqTokenAddress);
if (glqToClaim == 0) { return 0; }
require(
glqToken.balanceOf(address(this)) >= glqToClaim,
"Not enough funds in the staking program to claim rewards"
);
staker.block_number = block.number;
require(
glqToken.transfer(msg.sender, glqToClaim) == true,
"Error transfer on the contract"
);
return (glqToClaim);
}
/* Setter - Read & Modifications */
}
// 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);
function decimals() external view returns (uint8);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.8.0;
library QuickSorter {
function sort(uint[] storage data) internal {
uint n = data.length;
uint[] memory arr = new uint[](n);
uint i;
for(i=0; i<n; i++) {
arr[i] = data[i];
}
uint[] memory stack = new uint[](n+2);
//Push initial lower and higher bound
uint top = 1;
stack[top] = 0;
top = top + 1;
stack[top] = n-1;
//Keep popping from stack while is not empty
while (top > 0) {
uint h = stack[top];
top = top - 1;
uint l = stack[top];
top = top - 1;
i = l;
uint x = arr[h];
for(uint j=l; j<h; j++){
if (arr[j] <= x) {
//Move smaller element
(arr[i], arr[j]) = (arr[j],arr[i]);
i = i + 1;
}
}
(arr[i], arr[h]) = (arr[h],arr[i]);
uint p = i;
//Push left side to stack
if (p > l + 1) {
top = top + 1;
stack[top] = l;
top = top + 1;
stack[top] = p - 1;
}
//Push right side to stack
if (p+1 < h) {
top = top + 1;
stack[top] = p + 1;
top = top + 1;
stack[top] = h;
}
}
for(i=0; i<n; i++) {
data[i] = arr[i];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library strings {
using strings for *;
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len_cpy) private pure {
// Copy word-length chunks while possible
for(; len_cpy >= 32; len_cpy -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len_cpy) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string memory self) internal pure returns (slice memory) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice memory self) internal pure returns (slice memory) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice memory self) internal pure returns (string memory) {
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice memory self) internal pure returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr = self._ptr - 31;
uint end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice memory self) internal pure returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice memory self, slice memory other) internal pure returns (int) {
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
uint selfptr = self._ptr;
uint otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
uint256 diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice memory self, slice memory other) internal pure returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if(b < 0xE0) {
l = 2;
} else if(b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice memory self) internal pure returns (slice memory ret) {
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice memory self) internal pure returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice memory self) internal pure returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
uint selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
uint selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
event log_bytemask(bytes32 mask);
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr = selfptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice memory self, slice memory needle) internal pure returns (slice memory token) {
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) {
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {
uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice memory self, slice memory needle) internal pure returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice memory self, slice memory other) internal pure returns (string memory) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
length += parts[i]._len;
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(uint i = 0; i < parts.length; i++) {
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint j = _i;
uint lenn;
while (j != 0) {
lenn++;
j /= 10;
}
bytes memory bstr = new bytes(lenn);
uint k = lenn - 1;
while (_i != 0) {
bstr[k--] = bytes1(uint8(48 + _i % 10));
_i /= 10;
}
return string(bstr);
}
function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i = 0; i < bresult.length; i++) {
if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) {
if (decimals) {
if (_b == 0) {
break;
} else {
_b--;
}
}
mint *= 10;
mint += uint(uint8(bresult[i])) - 48;
} else if (uint(uint8(bresult[i])) == 46) {
decimals = true;
}
}
if (_b > 0) {
mint *= 10 ** _b;
}
return mint;
}
function split_string(string memory raw, string memory by) pure internal returns(string[] memory)
{
strings.slice memory s = raw.toSlice();
strings.slice memory delim = by.toSlice();
string[] memory parts = new string[](s.count(delim));
for (uint i = 0; i < parts.length; i++) {
parts[i] = s.split(delim).toString();
}
return parts;
}
} | Copy word-length chunks while possible | function memcpy(uint dest, uint src, uint len_cpy) private pure {
for(; len_cpy >= 32; len_cpy -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
| 1,061,472 |
./full_match/3/0xe3E78C43980456568eE5902C155079e725dcBB99/sources/browser/ERC1400ERC20.sol | Add a certificate signer for the token. operator Address to set as a certificate signer. authorized 'true' if operator shall be accepted as certificate signer, 'false' if not./ | function setCertificateSigner(address operator, bool authorized) external onlyOwner {
_setCertificateSigner(operator, authorized);
}
| 14,141,627 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "../interfaces/IPlus.sol";
import "../interfaces/IGauge.sol";
import "../interfaces/IGaugeController.sol";
/**
* @title Controller for all liquidity gauges.
*
* The Gauge Controller is responsible for the following:
* 1) AC emission rate computation for plus gauges;
* 2) AC reward claiming;
* 3) Liquidity gauge withdraw fee processing.
*
* Liquidity gauges can be divided into two categories:
* 1) Plus gauge: Liquidity gauges for plus tokens, the total rate is dependent on the total staked amount in these gauges;
* 2) Non-plus gage: Liquidity gauges for non-plus token, the rate is set by governance.
*/
contract GaugeController is Initializable, IGaugeController {
using SafeERC20Upgradeable for IERC20Upgradeable;
event GovernanceUpdated(address indexed oldGovernance, address indexed newGovernance);
event ClaimerUpdated(address indexed claimer, bool allowed);
event BasePlusRateUpdated(uint256 oldBaseRate, uint256 newBaseRate);
event TreasuryUpdated(address indexed oldTreasury, address indexed newTreasury);
event GaugeAdded(address indexed gauge, bool plus, uint256 gaugeWeight, uint256 gaugeRate);
event GaugeRemoved(address indexed gauge);
event GaugeUpdated(address indexed gauge, uint256 oldWeight, uint256 newWeight, uint256 oldGaugeRate, uint256 newGaugeRate);
event Checkpointed(uint256 oldRate, uint256 newRate, uint256 totalSupply, uint256 ratePerToken, address[] gauges, uint256[] guageRates);
event RewardClaimed(address indexed gauge, address indexed user, address indexed receiver, uint256 amount);
uint256 constant WAD = 10 ** 18;
uint256 constant LOG_10_2 = 301029995663981195; // log10(2) = 0.301029995663981195
uint256 constant DAY = 86400;
uint256 constant PLUS_BOOST_THRESHOLD = 100 * WAD; // Plus boosting starts at 100 plus staked!
address public override governance;
// AC token
address public override reward;
// Address => Whether this is claimer address.
// A claimer can help claim reward on behalf of the user.
mapping(address => bool) public override claimers;
address public override treasury;
struct Gauge {
// Helps to check whether the gauge is in the gauges list.
bool isSupported;
// Whether this is a plus gauge. The emission rate for the plus gauges depends on
// the total staked value in the plus gauges, while the emission rate for the non-plus
// gauges is set by the governance.
bool isPlus;
// Multiplier applied to the gauge in computing emission rate. Only applied to plus
// gauges as non-plus gauges should have fixed rate set by governance.
uint256 weight;
// Fixed AC emission rate for non-plus gauges.
uint256 rate;
}
// List of supported liquidity gauges
address[] public gauges;
// Liquidity gauge address => Liquidity gauge data
mapping(address => Gauge) public gaugeData;
// Liquidity gauge address => Actual AC emission rate
// For non-plus gauges, it is equal to gaugeData.rate when staked amount is non-zero and zero otherwise.
mapping(address => uint256) public override gaugeRates;
// Base AC emission rate for plus gauges. It's equal to the emission rate when there is no plus boosting,
// i.e. total plus staked <= PLUS_BOOST_THRESHOLD
uint256 public basePlusRate;
// Boost for all plus gauges. 1 when there is no plus boosting, i.e.total plus staked <= PLUS_BOOST_THRESHOLD
uint256 public plusBoost;
// Global AC emission rate, including both plus and non-plus gauge.
uint256 public totalRate;
// Last time the checkpoint is called
uint256 public lastCheckpoint;
// Total amount of AC rewarded until the latest checkpoint
uint256 public lastTotalReward;
// Total amount of AC claimed so far. totalReward - totalClaimed is the minimum AC balance that should be kept.
uint256 public totalClaimed;
// Mapping: Gauge address => Mapping: User address => Total claimed amount for this user in this gauge
mapping(address => mapping(address => uint256)) public override claimed;
// Mapping: User address => Timestamp of the last claim
mapping(address => uint256) public override lastClaim;
/**
* @dev Initializes the gauge controller.
* @param _reward AC token address.
* @param _plusRewardPerDay Amount of AC rewarded per day for plus gauges if there is no plus boost.
*/
function initialize(address _reward, uint256 _plusRewardPerDay) public initializer {
governance = msg.sender;
treasury = msg.sender;
reward = _reward;
// Base rate is in WAD
basePlusRate = _plusRewardPerDay * WAD / DAY;
plusBoost = WAD;
lastCheckpoint = block.timestamp;
}
/**
* @dev Computes log2(num). Result in WAD.
* Credit: https://medium.com/coinmonks/math-in-solidity-part-5-exponent-and-logarithm-9aef8515136e
*/
function _log2(uint256 num) internal pure returns (uint256) {
uint256 msb = 0;
uint256 xc = num;
if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; } // 2**128
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
uint256 lsb = 0;
uint256 ux = num << uint256 (127 - msb);
for (uint256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
lsb += bit * b;
}
return msb * 10**18 + (lsb * 10**18 >> 64);
}
/**
* @dev Computes log10(num). Result in WAD.
* Credit: https://medium.com/coinmonks/math-in-solidity-part-5-exponent-and-logarithm-9aef8515136e
*/
function _log10(uint256 num) internal pure returns (uint256) {
return _log2(num) * LOG_10_2 / WAD;
}
/**
* @dev Most important function of the gauge controller. Recompute total AC emission rate
* as well as AC emission rate per liquidity guage.
* Anyone can call this function so that if the liquidity gauge is exploited by users with short-term
* large amount of minting, others can restore to the correct mining paramters.
*/
function checkpoint() public {
// Loads the gauge list for better performance
address[] memory _gauges = gauges;
// The total amount of plus tokens staked
uint256 _totalPlus = 0;
// The total weighted amount of plus tokens staked
uint256 _totalWeightedPlus = 0;
// Amount of plus token staked in each gauge
uint256[] memory _gaugePlus = new uint256[](_gauges.length);
// Weighted amount of plus token staked in each gauge
uint256[] memory _gaugeWeightedPlus = new uint256[](_gauges.length);
uint256 _plusBoost = WAD;
for (uint256 i = 0; i < _gauges.length; i++) {
// Don't count if it's non-plus gauge
if (!gaugeData[_gauges[i]].isPlus) continue;
// Liquidity gauge token and staked token is 1:1
// Total plus is used to compute boost
address _staked = IGauge(_gauges[i]).token();
// Rebase once to get an accurate result
IPlus(_staked).rebase();
_gaugePlus[i] = IGauge(_gauges[i]).totalStaked();
_totalPlus = _totalPlus + _gaugePlus[i];
// Weighted plus is used to compute rate allocation
_gaugeWeightedPlus[i] = _gaugePlus[i] * gaugeData[_gauges[i]].weight;
_totalWeightedPlus = _totalWeightedPlus + _gaugeWeightedPlus[i];
}
// Computes the AC emission per plus. The AC emission rate is determined by total weighted plus staked.
uint256 _ratePerPlus = 0;
// Total AC emission rate for plus gauges is zero if the weighted total plus staked is zero!
if (_totalWeightedPlus > 0) {
// Plus boost is applied when more than 100 plus are staked
if (_totalPlus > PLUS_BOOST_THRESHOLD) {
// rate = baseRate * (log total - 1)
// Minus 19 since the TVL is in WAD, so -1 - 18 = -19
_plusBoost = _log10(_totalPlus) - 19 * WAD;
}
// Both plus boot and total weighted plus are in WAD so it cancels out
// Therefore, _ratePerPlus is still in WAD
_ratePerPlus = basePlusRate * _plusBoost / _totalWeightedPlus;
}
// Allocates AC emission rates for each liquidity gauge
uint256 _oldTotalRate = totalRate;
uint256 _totalRate;
uint256[] memory _gaugeRates = new uint256[](_gauges.length);
for (uint256 i = 0; i < _gauges.length; i++) {
if (gaugeData[_gauges[i]].isPlus) {
// gauge weighted plus is in WAD
// _ratePerPlus is also in WAD
// so block.timestamp gauge rate is in WAD
_gaugeRates[i] = _gaugeWeightedPlus[i] * _ratePerPlus / WAD;
} else {
// AC emission rate for non-plus gauge is fixed and set by the governance.
// However, if no token is staked, the gauge rate is zero.
_gaugeRates[i] = IERC20Upgradeable(_gauges[i]).totalSupply() == 0 ? 0 : gaugeData[_gauges[i]].rate;
}
gaugeRates[_gauges[i]] = _gaugeRates[i];
_totalRate += _gaugeRates[i];
}
// Checkpoints gauge controller
lastTotalReward += _oldTotalRate * (block.timestamp - lastCheckpoint) / WAD;
lastCheckpoint = block.timestamp;
totalRate = _totalRate;
plusBoost = _plusBoost;
// Checkpoints each gauge to consume the latest rate
// We trigger gauge checkpoint after all parameters are updated
for (uint256 i = 0; i < _gauges.length; i++) {
IGauge(_gauges[i]).checkpoint();
}
emit Checkpointed(_oldTotalRate, _totalRate, _totalPlus, _ratePerPlus, _gauges, _gaugeRates);
}
/**
* @dev Claims rewards for a user. Only the liquidity gauge can call this function.
* @param _account Address of the user to claim reward.
* @param _receiver Address that receives the claimed reward
* @param _amount Amount of AC to claim
*/
function claim(address _account, address _receiver, uint256 _amount) external override {
require(gaugeData[msg.sender].isSupported, "not gauge");
totalClaimed += _amount;
claimed[msg.sender][_account] = claimed[msg.sender][_account] + _amount;
lastClaim[msg.sender] = block.timestamp;
IERC20Upgradeable(reward).safeTransfer(_receiver, _amount);
emit RewardClaimed(msg.sender, _account, _receiver, _amount);
}
/**
* @dev Return the total amount of rewards generated so far.
*/
function totalReward() public view returns (uint256) {
return lastTotalReward + totalRate * (block.timestamp - lastCheckpoint) / WAD;
}
/**
* @dev Returns the total amount of rewards that can be claimed by user until block.timestamp.
* It can be seen as minimum amount of reward tokens should be buffered in the gauge controller.
*/
function claimable() external view returns (uint256) {
return totalReward() - totalClaimed;
}
/**
* @dev Returns the total number of gauges.
*/
function gaugeSize() public view returns (uint256) {
return gauges.length;
}
/**
* @dev Donate the gauge fee. Only liqudity gauge can call this function.
* @param _token Address of the donated token.
*/
function donate(address _token) external override {
require(gaugeData[msg.sender].isSupported, "not gauge");
uint256 _balance = IERC20Upgradeable(_token).balanceOf(address(this));
if (_balance == 0) return;
address _staked = IGauge(msg.sender).token();
if (gaugeData[msg.sender].isPlus && _token == _staked) {
// If this is a plus gauge and the donated token is the gauge staked token,
// then the gauge is donating the plus token!
// For plus token, donate it to all holders
IPlus(_token).donate(_balance);
} else {
// Otherwise, send to treasury for future process
IERC20Upgradeable(_token).safeTransfer(treasury, _balance);
}
}
/*********************************************
*
* Governance methods
*
**********************************************/
function _checkGovernance() internal view {
require(msg.sender == governance, "not governance");
}
modifier onlyGovernance() {
_checkGovernance();
_;
}
/**
* @dev Updates governance. Only governance can update governance.
*/
function setGovernance(address _governance) external onlyGovernance {
address _oldGovernance = governance;
governance = _governance;
emit GovernanceUpdated(_oldGovernance, _governance);
}
/**
* @dev Updates claimer. Only governance can update claimers.
*/
function setClaimer(address _account, bool _allowed) external onlyGovernance {
claimers[_account] = _allowed;
emit ClaimerUpdated(_account, _allowed);
}
/**
* @dev Updates the AC emission base rate for plus gauges. Only governance can update the base rate.
*/
function setPlusReward(uint256 _plusRewardPerDay) external onlyGovernance {
uint256 _oldRate = basePlusRate;
// Base rate is in WAD
basePlusRate = _plusRewardPerDay * WAD / DAY;
// Need to checkpoint with the base rate update!
checkpoint();
emit BasePlusRateUpdated(_oldRate, basePlusRate);
}
/**
* @dev Updates the treasury.
*/
function setTreasury(address _treasury) external onlyGovernance {
require(_treasury != address(0x0), "treasury not set");
address _oldTreasury = treasury;
treasury = _treasury;
emit TreasuryUpdated(_oldTreasury, _treasury);
}
/**
* @dev Adds a new liquidity gauge to the gauge controller. Only governance can add new gauge.
* @param _gauge The new liquidity gauge to add.
* @param _plus Whether it's a plus gauge.
* @param _weight Weight of the liquidity gauge. Useful for plus gauges only.
* @param _rewardPerDay AC reward for the gauge per day. Useful for non-plus gauges only.
*/
function addGauge(address _gauge, bool _plus, uint256 _weight, uint256 _rewardPerDay) external onlyGovernance {
require(_gauge != address(0x0), "gauge not set");
require(!gaugeData[_gauge].isSupported, "gauge exist");
uint256 _rate = _rewardPerDay * WAD / DAY;
gauges.push(_gauge);
gaugeData[_gauge] = Gauge({
isSupported: true,
isPlus: _plus,
weight: _weight,
// Reward rate is in WAD
rate: _rate
});
// Need to checkpoint with the new token!
checkpoint();
emit GaugeAdded(_gauge, _plus, _weight, _rate);
}
/**
* @dev Removes a liquidity gauge from gauge controller. Only governance can remove a plus token.
* @param _gauge The liquidity gauge to remove from gauge controller.
*/
function removeGauge(address _gauge) external onlyGovernance {
require(_gauge != address(0x0), "gauge not set");
require(gaugeData[_gauge].isSupported, "gauge not exist");
uint256 _gaugeSize = gauges.length;
uint256 _gaugeIndex = _gaugeSize;
for (uint256 i = 0; i < _gaugeSize; i++) {
if (gauges[i] == _gauge) {
_gaugeIndex = i;
break;
}
}
// We must have found the gauge!
assert(_gaugeIndex < _gaugeSize);
gauges[_gaugeIndex] = gauges[_gaugeSize - 1];
gauges.pop();
delete gaugeData[_gauge];
// Need to checkpoint with the token removed!
checkpoint();
emit GaugeRemoved(_gauge);
}
/**
* @dev Updates the weight of the liquidity gauge.
* @param _gauge Address of the liquidity gauge to update.
* @param _weight New weight of the liquidity gauge.
* @param _rewardPerDay AC reward for the gauge per day
*/
function updateGauge(address _gauge, uint256 _weight, uint256 _rewardPerDay) external onlyGovernance {
require(gaugeData[_gauge].isSupported, "gauge not exist");
uint256 _oldWeight = gaugeData[_gauge].weight;
uint256 _oldRate = gaugeData[_gauge].rate;
uint256 _rate = _rewardPerDay * WAD / DAY;
gaugeData[_gauge].weight = _weight;
gaugeData[_gauge].rate = _rate;
// Need to checkpoint with the token removed!
checkpoint();
emit GaugeUpdated(_gauge, _oldWeight, _weight, _oldRate, _rate);
}
/**
* @dev Used to salvage any ETH deposited to gauge controller by mistake. Only governance can salvage ETH.
* The salvaged ETH is transferred to treasury for futher operation.
*/
function salvage() external onlyGovernance {
uint256 _amount = address(this).balance;
address payable _target = payable(treasury);
(bool success, ) = _target.call{value: _amount}(new bytes(0));
require(success, 'ETH salvage failed');
}
/**
* @dev Used to salvage any token deposited to gauge controller by mistake. Only governance can salvage token.
* The salvaged token is transferred to treasury for futhuer operation.
* Note: The gauge controller is not expected to hold any token, so any token is salvageable!
* @param _token Address of the token to salvage.
*/
function salvageToken(address _token) external onlyGovernance {
IERC20Upgradeable _target = IERC20Upgradeable(_token);
_target.safeTransfer(treasury, _target.balanceOf(address(this)));
}
} | Returns the total amount of rewards that can be claimed by user until block.timestamp. It can be seen as minimum amount of reward tokens should be buffered in the gauge controller./ | function claimable() external view returns (uint256) {
return totalReward() - totalClaimed;
}
| 958,278 |
./full_match/5/0x631CadF9267a7784D690AFa0Bd9128760CF555Cf/sources/contracts/libraries/Token.sol | Returns readable string./ | function toString(Info memory _info) internal pure returns (string memory) {
return
string(
abi.encodePacked(
"TokenInfo(",
Strings.toHexString(uint160(_info.erc), 1),
",",
Strings.toHexString(_info.id),
",",
Strings.toHexString(_info.quantity),
")"
)
);
}
| 1,908,479 |
pragma solidity ^0.4.0;
// Example Contract that contributors can give birthday gifts to wallet(s)
// Gifter can send money to all pool
// Gifter can send to specifc address
// Birthdayee can see funds
// Birthdayee will not be transfered until birthday
contract BirthdayGift {
uint private giftAllBalance = 0;
uint private numOfWallets = 0;
struct Birthdayee {
// fix int
uint birthDate;
// fix int
uint balance;
// Used to see if address has been initialized
bool isInitialized;
}
// All participants
mapping (address => Birthdayee) private birthdayPool;
// If the wallet hasn't been initialized, then do so and increment counter
modifier walletCheck(address birthdayeeAddress) {
if ( isNewAddress(birthdayeeAddress) ) {
birthdayPool[birthdayeeAddress].isInitialized = true;
numOfWallets++;
}
_;
}
function isItTheirBirthday(address birthdayeeAddress) private pure returns(bool) {
// TODO : for now, return true - need to work on dates
return true;
}
// function to control counts of poolf members
function isNewAddress(address birthdayeeAddress) private view returns(bool) {
// Has the wallet been initialized?
if ( birthdayPool[birthdayeeAddress].isInitialized ) {
return true;
}
return false;
}
function getGiftBalance(address walletAddress) private view returns(uint payout) {
payout = birthdayPool[walletAddress].balance;
payout += this.balance / numOfWallets;
}
// Give to a specific wallet
function giveTo(address birthdayeeAddress) public payable walletCheck(msg.sender) {
birthdayPool[birthdayeeAddress].balance += msg.value;
}
// Give to birthday pool because nice people do exist
function giveAll() public payable {
giftAllBalance += msg.value;
}
// View Birthdayee balance assigned and from pool
function viewMyGift() public view returns (uint balance) {
balance = getGiftBalance(msg.sender);
}
// View Pool balance
function viewPoolBalance() public view returns (uint balance) {
balance = giftAllBalance;
}
// Collect birthday gift if within two weeks of birthday
function collectMyGift() public walletCheck(msg.sender) returns (uint payout) {
payout = getGiftBalance(msg.sender);
require (payout > 0);
if ( isItTheirBirthday(msg.sender) ) {
birthdayPool[msg.sender].balance = 0;
giftAllBalance -= payout;
msg.sender.transfer(payout);
} else {
payout = 0;
}
}
// Anon function for paying to the pool
function () public payable {
giveAll();
}
} | TODO : for now, return true - need to work on dates | function isItTheirBirthday(address birthdayeeAddress) private pure returns(bool) {
return true;
}
| 12,843,550 |
./partial_match/56/0x5AE8e454d3558102305Fa8487D3c6b59305B36b4/sources/project_/contracts/Airdrop.sol | Claims entire user airdrop in one transfer based on parameters. Requirements: - tokens are not claimed yet for `phrAddr` address - `amount` must be bigger than zero. merkleProofs - List of claim proofs for particular PHR addresses. phrAddresses - List of Phore addresses able to receive airdrop. amounts - List of GFN amounts for particular PHR addresses./ | function claimAllGFN(address sender, bytes32[][] memory merkleProofs, string[] memory phrAddresses,
uint256[] memory amounts, bytes[] memory signatures) public {
require(merkleProofs.length == phrAddresses.length, ARRAY_LEN_ERR);
require(merkleProofs.length == amounts.length, ARRAY_LEN_ERR);
require(merkleProofs.length == signatures.length, ARRAY_LEN_ERR);
uint amount = 0;
uint256 phrAddressLen = phrAddresses.length;
for (uint256 i = 0; i < phrAddressLen; i++) {
if(_spent[phrAddresses[i]]) {
continue;
}
bytes32 messageHash = createMessageHash(phrAddresses[i], amounts[i]);
if (!checkProof(merkleProofs[i], messageHash)) {
continue;
}
if (!_phrHolders.isPhoreOwner(sender, phrAddresses[i])) {
if (!_phrHolders.setPhoreOwner(sender, phrAddresses[i], signatures[i])) {
continue;
}
}
_spent[phrAddresses[i]] = true;
amount = amount.add(amounts[i]);
}
require(amount > 0, "Amount CANNOT BE ZERO!");
require(_graphene.transfer(sender, amount), "Transfer failed.");
}
| 11,231,424 |
pragma solidity >=0.4.25 <0.8.0;
import "./interfaces/IERC20.sol";
import "./interfaces/IWETH.sol";
import "./interfaces/IControl.sol";
import "./interfaces/IExchange.sol";
import "./uniswapv2/libraries/TransferHelper.sol";
pragma experimental ABIEncoderV2;
contract CCTPool {
struct Follower {
// address followerAddress; // 地址
uint256 investAmount; // money
uint256 withdrawnAmount;
uint256 atTime;
bool isInvested;
}
struct PoolInfo {
address master; // 基金创始人地址
// string title;
// string tags;
uint256 goal;
uint256 hardTop;
uint256 startTime;
uint256 duration;
address acceptToken;
address[] targetTokens;
uint32 expectedEarningRate; //预期收益率
uint8 managerShareRate; //基金管理员的分成比例。固定比例,有上下限
uint8 maxRetracement; //回撤
// string introduction;
uint256 totalCollectedAmount; // 当前募集金额
uint256 totalBalanceAmount; // 当前结存总额
int64 actualEarningRate;
bool isServiceEnd; //管理员已经结算过
bool isSettled; //平台方已经结算过
uint256 createTime;
}
struct AssetInfo {
address addr;
uint256 balance;
}
uint256 public poolId;
PoolInfo poolInfo;
uint256 public totalFollowers;
uint256 totalWithdrawals; //总共提走币的人
mapping(address => Follower) public followerMap; // 跟随者列表
// address[] invests; // 购买列表
uint256 locked;
//平台抽成比例
uint8 public serviceShareRate = 10;
IControl private control;
string public version = "0.1";
event PoolInvested(uint256 id, address from, uint256 value);
event SwapToken(uint256 id, uint256 amount);
constructor(
uint256 id,
address creator,
address acceptTokenAddress,
address[] memory targetTokensArray,
uint256 goal,
uint256 hardTop,
uint256 startTime,
uint256 duration,
uint32 expectedEarningRate,
uint8 managerShareRate,
uint8 maxRetracement
) public {
require(
acceptTokenAddress != address(0),
"CCTPool: accept token must be not the zero address"
);
require(
targetTokensArray.length != 0,
"CCTPool: target tokens is none"
);
for (uint256 i = 0; i < targetTokensArray.length; i++) {
require(
targetTokensArray[i] != address(0),
"CCTPool: accept token must be not the zero address"
);
}
require(goal >= 1, "At least 1");
require(hardTop >= goal, "HardTop must great than goal");
require(
startTime > block.timestamp,
"StartTime must great current time"
);
require(
expectedEarningRate >= 10,
"Expected earning rate must great than 10%"
);
require(
managerShareRate + serviceShareRate <= 100,
"Total rate must less than 100%"
);
require(maxRetracement >= 30, "Max retracement at least 30%");
require(duration > 0, "At least 1 day");
control = IControl(msg.sender);
poolId = id;
poolInfo = PoolInfo({
master: creator,
goal: goal,
hardTop: hardTop,
startTime: startTime,
duration: duration,
acceptToken: acceptTokenAddress,
targetTokens: targetTokensArray,
expectedEarningRate: expectedEarningRate,
managerShareRate: managerShareRate,
maxRetracement: maxRetracement,
totalCollectedAmount: 0,
totalBalanceAmount: 0,
actualEarningRate: 0,
isServiceEnd: false,
isSettled: false,
createTime: block.timestamp
});
// poolInfo = info;
}
receive() external payable {
require(
msg.sender == address(control.uniswapExchange().weth()),
"CCTPool: must from weth"
);
}
modifier lock() {
require(locked == 0, "Locked, please waiting for a while");
locked = 1;
_;
locked = 0;
}
modifier onlyMaster() {
require(isMaster(), "Only owner");
_;
}
modifier onlyControl() {
require(isControl(), "Only control");
_;
}
modifier inPreparation() {
require(isEarlyTime(), "Expired");
require(
poolInfo.totalCollectedAmount <= poolInfo.hardTop,
"Has reached goal"
);
_;
}
// modifier inRunning(uint256 id) {
// uint256 i1;
// uint256 i2;
// bool b1;
// (i1, i2, b1) = isRunningTime(id);
// uint256 j1;
// uint256 j2;
// bool b2;
// (j1, j2, b2) = isGoalAchieved(id);
// require(b1, "ContractCapital: NOT RIGHT TIME");
// require(b2, "ContractCapital: NOT ENOUGH TOKEN");
// _;
// }
modifier inService() {
require(poolInfo.isServiceEnd, "Service end");
_;
}
// modifier canSettle(uint256 id) {
// require(isEndedTime(id), "ContractCapital: NOT END");
// require(isGoalAchieved(id), "ContractCapital: NOT RUN");
// _;
// }
function isControl() public view returns (bool) {
return msg.sender == control.admin();
}
function isMaster() public view returns (bool) {
return msg.sender == poolInfo.master;
}
function isEarlyTime() public view returns (bool) {
return poolInfo.startTime >= block.timestamp;
}
function getBlockTime() public view returns (uint256) {
return block.timestamp;
}
function isRunningTime() public view returns (bool) {
return (poolInfo.startTime <= block.timestamp &&
block.timestamp <
poolInfo.startTime + poolInfo.duration * 1 minutes);
}
function isEndedTime() public view returns (bool) {
return (poolInfo.startTime + poolInfo.duration * 1 minutes <=
block.timestamp);
}
function isGoalAchieved() public view returns (bool) {
return (poolInfo.goal <= poolInfo.totalCollectedAmount);
}
// function getInvestedAmount() external view returns (uint256) {
// return followerMap[msg.sender].investAmount;
// }
// function getPools() external view returns (PoolInfo[] memory) {
// uint256 total = poolCount;
// PoolInfo[] memory pools;
// for (uint256 index = 0; index < total; index++) {
// pools[index] = poolList[index].poolInfo;
// }
// return pools;
// }
function getPoolState()
external
view
returns (
PoolInfo memory,
Follower memory,
uint256
)
{
return (poolInfo, followerMap[msg.sender], calcBalance());
}
// function getBalance(address addr) private returns (uint256) {
// if (addr == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) {
// return address(this).balance;
// }
// return IERC20(addr).balanceOf(address(this));
// }
// function getAssets() external returns (AssetInfo[] memory) {
// AssetInfo[] memory assets;
// assets[0] = AssetInfo({
// addr: poolInfo.acceptToken,
// balance: getBalance(poolInfo.acceptToken)
// });
// for (uint256 i = 0; i < poolInfo.targetTokens.length; i++) {
// assets[i + 1] = AssetInfo({
// addr: poolInfo.targetTokens[i],
// balance: getBalance(poolInfo.targetTokens[i])
// });
// }
// return assets;
// }
// function getPoolState2() external view returns (follower memory) {
// follower memory f = followerMap[msg.sender];
// return f;
// }
function investToPool(uint256 amountIn)
external
payable
lock()
inPreparation()
{
// require(IERC20(acceptToken).approve(address(this), amountIn), 'approve failed.');
if (
poolInfo.acceptToken ==
address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
) {
amountIn = msg.value;
}
require(amountIn > 0, "No zero");
uint256 totalAmount = poolInfo.totalCollectedAmount + amountIn;
require(totalAmount <= poolInfo.hardTop, "Overflow");
// require(
// IERC20(acceptToken).transferFrom(
// msg.sender,
// address(this),
// amountIn
// ),
// "transferFrom failed."
// );
// require(
// transferFrom(
// msg.sender,
// address(this),
// amountIn
// ),
// "transferFrom failed."
// );
//eth
if (
poolInfo.acceptToken !=
address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
) {
TransferHelper.safeTransferFrom(
poolInfo.acceptToken,
msg.sender,
address(this),
amountIn
);
}
if (!followerMap[msg.sender].isInvested) {
totalFollowers++;
followerMap[msg.sender] = Follower({
investAmount: amountIn,
withdrawnAmount: 0,
atTime: block.timestamp,
isInvested: true
});
} else {
followerMap[msg.sender].investAmount += amountIn;
}
poolInfo.totalCollectedAmount = totalAmount;
emit PoolInvested(poolId, msg.sender, amountIn);
}
function depositEth(address token, uint256 amount) private {
if (token == control.uniswapExchange().weth()) {
IWETH(token).deposit{value: amount}();
}
}
function withdrawEth(address token, uint256 amount) private {
if (token == control.uniswapExchange().weth()) {
IWETH(token).withdraw(amount);
}
}
//check token is in allowable list
function isValidSubject(address token) private view returns (bool) {
for (uint256 i = 0; i < poolInfo.targetTokens.length; i++) {
if (token == poolInfo.targetTokens[i]) {
return true;
}
}
address t = token;
if (
poolInfo.acceptToken ==
address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
) {
t = control.uniswapExchange().weth();
}
return t == token;
}
function getLiquidity(address tokenA, address tokenB)
external
view
returns (uint256)
{
return control.uniswapExchange().getLiquidity(tokenA, tokenB);
}
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountA,
uint256 amountB
)
external
onlyMaster
returns (
uint256,
uint256,
uint256
)
{
require(
isValidSubject(tokenA) && isValidSubject(tokenB),
"CCTPool: invalid subject"
);
depositEth(tokenA, amountA);
depositEth(tokenB, amountB);
TransferHelper.safeTransfer(
tokenA,
address(control.uniswapExchange()),
amountA
);
TransferHelper.safeTransfer(
tokenB,
address(control.uniswapExchange()),
amountB
);
return
control.uniswapExchange().addLiquidity(
tokenA,
tokenB,
amountA,
amountB
);
}
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity
) external onlyMaster returns (uint256, uint256) {
address pair = control.uniswapExchange().getLiquidityAddress(
tokenA,
tokenB
);
TransferHelper.safeTransfer(
pair,
address(control.uniswapExchange()),
liquidity
);
uint256 amountA;
uint256 amountB;
(amountA, amountB) = control.uniswapExchange().removeLiquidity(
tokenA,
tokenB,
liquidity
);
withdrawEth(tokenA, amountA);
withdrawEth(tokenB, amountB);
return (amountA, amountB);
}
function swap(
address srcToken,
address destToken,
uint256 srcAmount,
uint256 minDestAmount
) external onlyMaster returns (uint256) {
require(isValidSubject(destToken), "CCTPool: invalid subject");
depositEth(srcToken, srcAmount);
TransferHelper.safeTransfer(
srcToken,
address(control.uniswapExchange()),
srcAmount
);
uint256 amount = control.uniswapExchange().swap(
srcToken,
destToken,
srcAmount,
minDestAmount
);
withdrawEth(destToken, srcAmount);
SwapToken(poolId, amount);
return amount;
}
//if tokenIn is weth, neet send eth to weth before call this function by:weth.deposit{value: eth value}()
function swapTokensAndAddLiquidity(
address tokenIn,
address pairToken,
uint256 amountIn
)
external
onlyMaster
returns (
uint256,
uint256,
uint256
)
{
require(isValidSubject(pairToken), "CCTPool: invalid subject");
depositEth(tokenIn, amountIn);
TransferHelper.safeTransfer(
tokenIn,
address(control.uniswapExchange()),
amountIn
);
return
control.uniswapExchange().swapTokenAndAddLiquidity(
tokenIn,
pairToken,
amountIn
);
}
function removeLiquidityAndSwapToToken(
address undesiredToken,
address desiredToken,
uint256 liquidity
) external onlyMaster returns (uint256) {
address pair = control.uniswapExchange().getLiquidityAddress(
undesiredToken,
desiredToken
);
TransferHelper.safeTransfer(
pair,
address(control.uniswapExchange()),
liquidity
);
uint256 amountDesiredTokenOut = control
.uniswapExchange()
.removeLiquidityAndSwapToToken(
undesiredToken,
desiredToken,
liquidity
);
withdrawEth(desiredToken, amountDesiredTokenOut);
return amountDesiredTokenOut;
}
/**
*清算
*/
function liquidate() external {}
function setEarningRate(uint256 currentBalance) external {
poolInfo.totalBalanceAmount = currentBalance;
poolInfo.actualEarningRate = int32(
((currentBalance - poolInfo.totalCollectedAmount) * 100) /
poolInfo.totalCollectedAmount
);
}
// function getFollower(address addr) private view returns (uint256, bool) {
// for (uint256 i = 0; i < totalFollowers; i++) {
// if (followerMap[i].followerAddress == addr) {
// // f = followerMap[i];
// // has = true;
// return (i, true);
// }
// }
// return (0, false);
// }
function calcBalance() public view returns (uint256) {
if (isEarlyTime()) {
return 0;
}
if (isRunningTime() && isGoalAchieved()) {
return 0;
}
uint256 investAmount = followerMap[msg.sender].investAmount;
if (isMaster()) {
if (poolInfo.isServiceEnd) {
return 0;
}
} else if (isControl()) {
if (poolInfo.isSettled) {
return 0;
}
} else if (
investAmount == 0 ||
investAmount == followerMap[msg.sender].withdrawnAmount
) {
return 0;
}
uint256 returnMoney;
if (!isGoalAchieved()) {
returnMoney = investAmount;
} else {
uint256 total = poolInfo.totalBalanceAmount;
if (total == 0) {
total = poolInfo.totalCollectedAmount;
}
if (poolInfo.actualEarningRate < poolInfo.expectedEarningRate) {
returnMoney =
(total * investAmount) /
poolInfo.totalCollectedAmount;
} else {
uint256 remained = 100 -
poolInfo.managerShareRate -
serviceShareRate;
uint256 profit = total - poolInfo.totalCollectedAmount;
returnMoney =
investAmount +
(profit * remained * investAmount) /
100 /
poolInfo.totalCollectedAmount;
if (isMaster()) {
returnMoney += (profit * poolInfo.managerShareRate) / 100;
} else if (isControl()) {
returnMoney += (profit * serviceShareRate) / 100;
}
}
}
return returnMoney;
}
/**
* 参与投资的人以及管理员执行资金赎回
*/
function redeem() external {
uint256 returnMoney = calcBalance();
require(returnMoney != 0, "balance 0");
if (isMaster()) {
poolInfo.isServiceEnd = true;
} else if (isControl()) {
poolInfo.isSettled = true;
}
followerMap[msg.sender].withdrawnAmount = followerMap[msg.sender]
.investAmount;
msg.sender.transfer(returnMoney);
}
/**
*平台执行服务结算
*/
// function settleService(uint256 id)
// external
// payable
// onlyControl
// exist(id)
// inService(id)
// canSettle(id)
// {
// Pool memory p = poolList[id];
// PoolInfo memory info = p.poolInfo;
// if (info.actualEarningRate >= info.expectedEarningRate) {
// uint256 profit = p.totalBalanceAmount - info.totalCollectedAmount;
// uint256 returnMoney = profit * serviceShareRate;
// msg.sender.transfer(returnMoney);
// }
// info.isServiceEnd = true;
// }
// function batchTransferToken(
// address _token,
// address[] _receivers,
// uint256[] _tokenAmounts
// ) public checkArrayArgument(_receivers, _tokenAmounts) {}
}
| require(IERC20(acceptToken).approve(address(this), amountIn), 'approve failed.'); | function investToPool(uint256 amountIn)
external
payable
lock()
inPreparation()
{
if (
poolInfo.acceptToken ==
address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
) {
amountIn = msg.value;
}
require(amountIn > 0, "No zero");
uint256 totalAmount = poolInfo.totalCollectedAmount + amountIn;
require(totalAmount <= poolInfo.hardTop, "Overflow");
poolInfo.acceptToken !=
address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
) {
TransferHelper.safeTransferFrom(
poolInfo.acceptToken,
msg.sender,
address(this),
amountIn
);
}
if (!followerMap[msg.sender].isInvested) {
totalFollowers++;
followerMap[msg.sender] = Follower({
investAmount: amountIn,
withdrawnAmount: 0,
atTime: block.timestamp,
isInvested: true
});
followerMap[msg.sender].investAmount += amountIn;
}
poolInfo.totalCollectedAmount = totalAmount;
emit PoolInvested(poolId, msg.sender, amountIn);
}
| 12,666,183 |
// File: @openzeppelin/contracts/utils/Counters.sol
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// 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);
}
}
// File: @openzeppelin/contracts/utils/cryptography/ECDSA.sol
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// 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: @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/utils/Address.sol
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface 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
// 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: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract 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
// OpenZeppelin Contracts v4.4.1 (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
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = 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 Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try 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 {}
}
// File: contracts/NaftyDolls/NaftyDolls.sol
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
contract NaftyDolls is ERC721, Ownable {
using Strings for uint256;
using ECDSA for bytes32;
uint256 public MAX_PRESALE = 1000;
uint256 public MAX_FREE = 1696;
uint256 public maxSupply = 6969;
uint256 public currentSupply = 0;
uint256 public maxPerWallet = 5;
uint256 public salePrice = 0.025 ether;
uint256 public presalePrice = 0.02 ether;
uint256 public presaleCount;
uint256 public freeMinted;
//Placeholders
address private presaleAddress = address(0x0d9555EEa2835eE438219374dd97F0Cbe51bf0bc);
address private freeAddress = address(0x642D7B2F8CaC6b7DA136D1fe8C2C912EEF32564c);
address private wallet = address(0x9C86fC37EB0054f38D29C44Ba374E6e712e40F9f);
string private baseURI;
string private notRevealedUri = "ipfs://QmYSLyMYTPKjgavj4ZkxP8U8epdDP6mwKypg5S5UFi7it7";
bool public revealed = false;
bool public baseLocked = false;
bool public marketOpened = false;
bool public freeMintOpened = false;
enum WorkflowStatus {
Before,
Presale,
Sale,
Paused,
Reveal
}
WorkflowStatus public workflow;
mapping(address => uint256) public freeMintAccess;
mapping(address => uint256) public presaleMintLog;
mapping(address => uint256) public freeMintLog;
constructor()
ERC721("NaftyDolls", "DOLLS")
{
transferOwnership(msg.sender);
workflow = WorkflowStatus.Before;
initFree();
}
function setApprovalForAll(address operator, bool approved) public virtual override {
require(marketOpened, 'The sale of NFTs on the marketplaces has not been opened yet.');
_setApprovalForAll(_msgSender(), operator, approved);
}
function approve(address to, uint256 tokenId) public virtual override {
require(marketOpened, 'The sale of NFTs on the marketplaces has not been opened yet.');
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);
}
function withdraw() public onlyOwner {
uint256 _balance = address( this ).balance;
payable( wallet ).transfer( _balance );
}
//GETTERS
function getSaleStatus() public view returns (WorkflowStatus) {
return workflow;
}
function totalSupply() public view returns (uint256) {
return currentSupply;
}
function getFreeMintAmount( address _acc ) public view returns (uint256) {
return freeMintAccess[ _acc ];
}
function getFreeMintLog( address _acc ) public view returns (uint256) {
return freeMintLog[ _acc ];
}
function validateSignature( address _addr, bytes memory _s ) internal view returns (bool){
bytes32 messageHash = keccak256(
abi.encodePacked( address(this), msg.sender)
);
address signer = messageHash.toEthSignedMessageHash().recover(_s);
if( _addr == signer ) {
return true;
} else {
return false;
}
}
//Batch minting
function mintBatch(
address to,
uint256 baseId,
uint256 number
) internal {
for (uint256 i = 0; i < number; i++) {
_safeMint(to, baseId + i);
}
}
/**
Claims tokens for free paying only gas fees
*/
function freeMint(uint256 _amount, bytes calldata signature) external {
//Free mint check
require(
freeMintOpened,
"Free mint is not opened yet."
);
//Check free mint signature
require(
validateSignature(
freeAddress,
signature
),
"SIGNATURE_VALIDATION_FAILED"
);
uint256 supply = currentSupply;
uint256 allowedAmount = 1;
if( freeMintAccess[ msg.sender ] > 0 ) {
allowedAmount = freeMintAccess[ msg.sender ];
}
require(
freeMintLog[ msg.sender ] + _amount <= allowedAmount,
"You dont have permision to free mint that amount."
);
require(
supply + _amount <= maxSupply,
"NaftyDolls: Mint too large, exceeding the maxSupply"
);
require(
freeMinted + _amount <= MAX_FREE,
"NaftyDolls: Mint too large, exceeding the free mint amount"
);
freeMintLog[ msg.sender ] += _amount;
freeMinted += _amount;
currentSupply += _amount;
mintBatch(msg.sender, supply, _amount);
}
function presaleMint(
uint256 amount,
bytes calldata signature
) external payable {
require(
workflow == WorkflowStatus.Presale,
"NaftyDolls: Presale is not currently active."
);
require(
validateSignature(
presaleAddress,
signature
),
"SIGNATURE_VALIDATION_FAILED"
);
require(amount > 0, "You must mint at least one token");
//Max per wallet check
require(
presaleMintLog[ msg.sender ] + amount <= maxPerWallet,
"NaftyDolls: You have exceeded the max per wallet amount!"
);
//Price check
require(
msg.value >= presalePrice * amount,
"NaftyDolls: Insuficient ETH amount sent."
);
require(
presaleCount + amount <= MAX_PRESALE,
"NaftyDolls: Selected amount exceeds the max presale supply"
);
presaleCount += amount;
currentSupply += amount;
presaleMintLog[ msg.sender ] += amount;
mintBatch(msg.sender, currentSupply - amount, amount);
}
function publicSaleMint(uint256 amount) external payable {
require( amount > 0, "You must mint at least one NFT.");
uint256 supply = currentSupply;
require( supply < maxSupply, "NaftyDolls: Sold out!" );
require( supply + amount <= maxSupply, "NaftyDolls: Selected amount exceeds the max supply.");
require(
workflow == WorkflowStatus.Sale,
"NaftyDolls: Public sale has not active."
);
require(
msg.value >= salePrice * amount,
"NaftyDolls: Insuficient ETH amount sent."
);
currentSupply += amount;
mintBatch(msg.sender, supply, amount);
}
function forceMint(uint256 number, address receiver) external onlyOwner {
uint256 supply = currentSupply;
require(
supply + number <= maxSupply,
"NaftyDolls: You can't mint more than max supply"
);
currentSupply += number;
mintBatch( receiver, supply, number);
}
function ownerMint(uint256 number) external onlyOwner {
uint256 supply = currentSupply;
require(
supply + number <= maxSupply,
"NaftyDolls: You can't mint more than max supply"
);
currentSupply += number;
mintBatch(msg.sender, supply, number);
}
function airdrop(address[] calldata addresses) external onlyOwner {
uint256 supply = currentSupply;
require(
supply + addresses.length <= maxSupply,
"NaftyDolls: You can't mint more than max supply"
);
currentSupply += addresses.length;
for (uint256 i = 0; i < addresses.length; i++) {
_safeMint(addresses[i], supply + i);
}
}
function setUpBefore() external onlyOwner {
workflow = WorkflowStatus.Before;
}
function setUpPresale() external onlyOwner {
workflow = WorkflowStatus.Presale;
}
function setUpSale() external onlyOwner {
workflow = WorkflowStatus.Sale;
}
function pauseSale() external onlyOwner {
workflow = WorkflowStatus.Paused;
}
function setMaxPerWallet( uint256 _amount ) external onlyOwner {
maxPerWallet = _amount;
}
function setMaxPresale( uint256 _amount ) external onlyOwner {
MAX_PRESALE = _amount;
}
function setMaxFree( uint256 _amount ) external onlyOwner {
MAX_FREE = _amount;
}
function openFreeMint() public onlyOwner {
freeMintOpened = true;
}
function stopFreeMint() public onlyOwner {
freeMintOpened = false;
}
function reveal() public onlyOwner {
revealed = true;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
require( baseLocked == false, "Base URI change has been disabled permanently");
baseURI = _newBaseURI;
}
function setPresaleAddress(address _newAddress) public onlyOwner {
require(_newAddress != address(0), "CAN'T PUT 0 ADDRESS");
presaleAddress = _newAddress;
}
function setWallet(address _newWallet) public onlyOwner {
wallet = _newWallet;
}
function setSalePrice(uint256 _newPrice) public onlyOwner {
salePrice = _newPrice;
}
function setPresalePrice(uint256 _newPrice) public onlyOwner {
presalePrice = _newPrice;
}
function setFreeMintAccess(address _acc, uint256 _am ) public onlyOwner {
freeMintAccess[ _acc ] = _am;
}
//Lock base security - your nfts can never be changed.
function lockBase() public onlyOwner {
baseLocked = true;
}
//Once opened, it can not be closed again
function openMarket() public onlyOwner {
marketOpened = true;
}
// FACTORY
function tokenURI(uint256 tokenId)
public
view
override(ERC721)
returns (string memory)
{
if (revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = baseURI;
return
bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(),'.json'))
: "";
}
function initFree() internal {
freeMintAccess[ address(0x9C86fC37EB0054f38D29C44Ba374E6e712e40F9f) ] = 168;
freeMintAccess[ address(0x49c72c829B2aa1Ae2526fAEE29461E6cb7Efe0E6) ] = 102;
freeMintAccess[ address(0x522dC68b2fd2da341d1d25595101E27118B232bD) ] = 73;
freeMintAccess[ address(0xA21f8534E9521C02981a0956106d6074abE9c60f) ] = 61;
freeMintAccess[ address(0xbF1aE3F91EC24B5Da2d85F2bD95a9E2a0F632d47) ] = 48;
freeMintAccess[ address(0x0Cb7Dbc3837Ce16661BeC77e1Db239AAA6d4F0b4) ] = 40;
freeMintAccess[ address(0xa7B463a13EF0657F0ab7b6DD03A923563e503Aea) ] = 39;
freeMintAccess[ address(0x6E84a7EB0c34A757652A2474f4D2c73e288347c3) ] = 35;
freeMintAccess[ address(0x883AB33f8270015102afeCBD03872458b12bf9c5) ] = 29;
freeMintAccess[ address(0xb41e212b047f7A8e3961d52001ADE9413f7D0C70) ] = 24;
freeMintAccess[ address(0x666e1b05Bf965b09B6D598C26Fa2Bdc27C5d3f4f) ] = 21;
freeMintAccess[ address(0x0C319880d4296207b82F463B979b4923E5F9AD07) ] = 20;
freeMintAccess[ address(0x86E453d8c94bc0ADC4f4B05b2b4E451e17Be8abe) ] = 20;
freeMintAccess[ address(0xb0e41D26Cc795Da7220e3FBaaa0c92E6Baf65db2) ] = 20;
freeMintAccess[ address(0xfB72c1a0500E18D757f722d1F71191503e937f1F) ] = 20;
freeMintAccess[ address(0x1A18A57567EB571E29F14F7ae59c6fFEf2398157) ] = 13;
freeMintAccess[ address(0xFaeFb5433b70f5D0857cc7f65b32eeae0316aBcb) ] = 12;
freeMintAccess[ address(0x0Df8bFD2628A4b90cf8967167D0bd0F1E9969D55) ] = 11;
freeMintAccess[ address(0x40E3c1262445fc6A5A8AEF06610dc44F7532c291) ] = 11;
freeMintAccess[ address(0xC23e1145356A9dd3aa6Af8d7766281984ec24B76) ] = 11;
freeMintAccess[ address(0x0e279033eA931f98908cc52E1ABFCa60118CAeBA) ] = 10;
freeMintAccess[ address(0x9E75aa8Da215804fa82c8C6b5F24bBb7fF069541) ] = 10;
freeMintAccess[ address(0x396EB23e3C593F0cD705fBA2Fb6F75c66CaAAd7a) ] = 9;
freeMintAccess[ address(0x06a91aEcF753fF023033FFc6afD79904Dc6Dd22f) ] = 8;
freeMintAccess[ address(0x617011B79F0761DD82Acc026F796650f5e767e84) ] = 8;
freeMintAccess[ address(0x6571cb1fc92d71238aE992271D4Fca16e950a40A) ] = 8;
freeMintAccess[ address(0xa2681553681a6A317F33BdCA233C510e7E9A94fC) ] = 8;
freeMintAccess[ address(0xC6Ac567b250b986acAE49A842Dad7865dA4be3a0) ] = 8;
freeMintAccess[ address(0xe78ec69BF9f6546fB7167f9F04B8B561e41456B3) ] = 8;
freeMintAccess[ address(0x25840805c7B742488f2E5566398C99d0c39A373B) ] = 7;
freeMintAccess[ address(0xA5f83912B9A8B0a6ac0DDbd24c68F88954E4C414) ] = 7;
freeMintAccess[ address(0xAdBe5D005Dde820018e66D76E1295596C08E46B6) ] = 7;
freeMintAccess[ address(0xbff3041A372573f65557CB58239f945b61021ee2) ] = 7;
freeMintAccess[ address(0xF73931eF77Cb25dE6A06dAB426e592ED96eFe6b0) ] = 7;
freeMintAccess[ address(0x1F23E7b50677C921663AA4e0c9964229fd144Df6) ] = 6;
freeMintAccess[ address(0x9Aa9851eB948F1aE54388df486D45EE96fB90079) ] = 6;
freeMintAccess[ address(0xD0BB6e64e1C6dEbADD41298E0fF39676630F03a8) ] = 6;
freeMintAccess[ address(0x029AdC78D419072Ab70EC984C7b677BE51b0e121) ] = 5;
freeMintAccess[ address(0x0fd24D3737831DcE1bbf70bEA0c66d7652e7e9Fd) ] = 5;
freeMintAccess[ address(0x11eFD8579B24e49F0ff2c14Be23241045c8f7C01) ] = 5;
freeMintAccess[ address(0x29425A1f1172628450c2d915317a5e2A2Ae9e8D8) ] = 5;
freeMintAccess[ address(0x31B9A8347e5086B2D9C4bcA33B46CDcb04914fb1) ] = 5;
freeMintAccess[ address(0x41C3BD08f55a1279C3c596449eB42e00A2E86823) ] = 5;
freeMintAccess[ address(0x4e0D6e9081EEA4B76489EE135387bD99AA5e808E) ] = 5;
freeMintAccess[ address(0x85EB1C61734d92d915cb54296E85473e35603ecF) ] = 5;
freeMintAccess[ address(0x89EFf4ACa6aEC1e93E48DcCAF9098aD09E8A11F9) ] = 5;
freeMintAccess[ address(0x8Eb0a8aa228148690313FBAfA4A7805aB304F9ce) ] = 5;
freeMintAccess[ address(0xa953Ca657Eea71E5d6591B62551026E0CD6733c8) ] = 5;
freeMintAccess[ address(0xB1F8D4D0eD25282A96B9D407944d69c9a988C2Ed) ] = 5;
freeMintAccess[ address(0xb3caedA9DED7930a5485F6a36326B789C33c6c1e) ] = 5;
freeMintAccess[ address(0xBBDCEDCC7cDac2F336d5F8f2C31cf35a29b5e4f7) ] = 5;
freeMintAccess[ address(0xbfdA5CAEbFaA57871a14611F8d182d51e144C699) ] = 5;
freeMintAccess[ address(0xc3C0465798ce9071513E21Ef244df6AD5f1B2eAB) ] = 5;
freeMintAccess[ address(0xC53A22e8c57B7d1fecf9ec90973ea9B4C887b507) ] = 5;
freeMintAccess[ address(0xCFF9Dd2C80140A8c72B9d6A04fb68A8A845c46e5) ] = 5;
freeMintAccess[ address(0xE0F6Bb10e17Ae2fEcD114d43603482fcEa5A9654) ] = 9;
freeMintAccess[ address(0xEa0bC5d9E7e7209Db6d154589EcB5A9eC834789B) ] = 5;
freeMintAccess[ address(0xEbdE91900cC5D8B21e54Cf22200bC0BcfF797A3f) ] = 5;
freeMintAccess[ address(0xfcEDD0aF38ee1F6D868Ee15ec3407A7ea4fBbDc0) ] = 5;
freeMintAccess[ address(0x0783FD17d11589b59Ef7837803Bfb046c025C5Af) ] = 4;
freeMintAccess[ address(0x11CfD3FAA2c11DE05B03D2bAA8720Ed650FDcfFF) ] = 4;
freeMintAccess[ address(0x237f5828F189a57B0c41c260faD26fB3AabcBdB3) ] = 4;
freeMintAccess[ address(0x2b2aAA6777Bd6BB6F3d0DDA951e8cd72382850A9) ] = 4;
freeMintAccess[ address(0x3817Ee9AAe5Fe0260294B32D7feE557A12CaDf20) ] = 4;
freeMintAccess[ address(0x55A2F801dC8C599510ffb87818dB0d5110dca971) ] = 4;
freeMintAccess[ address(0x55f82Ab0Db89Fa58259fD08cf53Ab49a513d94B9) ] = 4;
freeMintAccess[ address(0x611769a86D9AF4ECc50D96F62D5638F7b9a2C8b0) ] = 4;
freeMintAccess[ address(0x773823a2122dC67422D80dE9F7171ed735073c99) ] = 4;
freeMintAccess[ address(0x7B34328fCee7412409b2d2154b30A69603D4B1b3) ] = 4;
freeMintAccess[ address(0x858dcFf3A742Ece5BF9AE20D7b1785d71097ED13) ] = 4;
freeMintAccess[ address(0x9B767B0F52E63ED2CF964E7AC6f560090A90dAfB) ] = 4;
freeMintAccess[ address(0xa6A7b9c9395AF131414b9d2a8500F3A9bEe4b666) ] = 4;
freeMintAccess[ address(0xC28ADD98Fe22898B95267766D728bB604a9f84A4) ] = 4;
freeMintAccess[ address(0xCB4DB3f102F0F505a4D545f8be593364B1c66A3C) ] = 4;
freeMintAccess[ address(0xDc72374CE12BB418Aad6D6ccE5c18bE8A542D6a8) ] = 4;
freeMintAccess[ address(0xE0687e41123fC40797136F4cdBC199DB6f25A807) ] = 4;
freeMintAccess[ address(0x00E101ffd6eF0217fdA6d5226e5a213E216b332b) ] = 3;
freeMintAccess[ address(0x02098bf554A48707579FcB28182D42947c013cfA) ] = 3;
freeMintAccess[ address(0x0668f77dD7AA869AaDA6aA79bC2066B04402f33D) ] = 3;
freeMintAccess[ address(0x278868be49d73284e6415d68b8583211eE96ce1F) ] = 3;
freeMintAccess[ address(0x2b617e50120131172cb4f83B003C2B9870181a4b) ] = 3;
freeMintAccess[ address(0x2bD89Adf988609Ba5bB91CDc4250230dDC3D9dA7) ] = 3;
freeMintAccess[ address(0x2f8fb999B325FCb5182Df1a2d94801B8C8C09800) ] = 3;
freeMintAccess[ address(0x316A35eBc7bFb945aB84E8BF6167585602306192) ] = 3;
freeMintAccess[ address(0x34e5f6E7b84345d81d86Ae1afc213528b1F8FDA8) ] = 3;
freeMintAccess[ address(0x34EDC7ab60f6cBD2005Ac07C543e19CA48B23b30) ] = 3;
freeMintAccess[ address(0x39b2B1D665f018f3eE2e46947f41A83f4806e159) ] = 3;
freeMintAccess[ address(0x426709Ab969F9901654942af0eAd1966Ad111a9D) ] = 3;
freeMintAccess[ address(0x44539fbBC413c07b133d310f7713d354F3D55f0a) ] = 3;
freeMintAccess[ address(0x5a1726eC746a9c63bB699AF5d9e8eAa0007567Ed) ] = 3;
freeMintAccess[ address(0x5c8aD9343c76CCE594cB3B663410DD2fa1aC0e78) ] = 3;
freeMintAccess[ address(0x62E45D439547602F36e0879fa66600b9EdD196B0) ] = 3;
freeMintAccess[ address(0x642aB18dEbdf0A516083097b056489029D607530) ] = 3;
freeMintAccess[ address(0x69e69571d0d07EdBEde6c43849e8d877573eE6bf) ] = 3;
freeMintAccess[ address(0x6a4e2bC8529c43Bc02e7007762eBA16fe5bDBd6F) ] = 3;
freeMintAccess[ address(0x6B6f0B36Ae5B19f9D0c1BD62DFF3E0bEDaA0C039) ] = 3;
freeMintAccess[ address(0x76cAD91850548726F41FABedDA8119fd133ae2d9) ] = 3;
freeMintAccess[ address(0x7C922CDC663367ed2ba6E84c074385121AA79291) ] = 3;
freeMintAccess[ address(0x7D259bb55d3481aD0b3A39FaDd9bAf1e1E66FbB7) ] = 3;
freeMintAccess[ address(0x81fA49241483A6eFB50E540b1185ED54Aa7fb5E4) ] = 3;
freeMintAccess[ address(0x88acF47cdF0030F7E52e82C49606E0B7078D5E6A) ] = 3;
freeMintAccess[ address(0x936c80387b8ba716FbB0Ea889BE3C37C45Dd255B) ] = 3;
freeMintAccess[ address(0x9CA6103A2c7Ca4028aC7ff7163D58fFDad6aa5A1) ] = 3;
freeMintAccess[ address(0x9f873b00048CbF31004968579D8beE032A509F7b) ] = 3;
freeMintAccess[ address(0xA0F9Ae81cD597A889BA519f20e06C5dE63162146) ] = 3;
freeMintAccess[ address(0xA9Eaa007aAE4924D650c50381b278841Ee4d4e01) ] = 3;
freeMintAccess[ address(0xad1f11c7c621e628E47E164A87d97D5A048Cb2E5) ] = 3;
freeMintAccess[ address(0xAeA9E80d59831660814A98109102bA1DD7A3DB0b) ] = 3;
freeMintAccess[ address(0xB320cd14bCf767d2Be6831686fFf2AB8DF5B68A5) ] = 3;
freeMintAccess[ address(0xB50b39a360D664D2b9e48404A0C7a64Af6eE2714) ] = 3;
freeMintAccess[ address(0xB82f8752410eFb54aAeBAE73EDae3e763e95FF53) ] = 3;
freeMintAccess[ address(0xc91D7378ADfF02593f5d67991C6B9721d3Bc244d) ] = 3;
freeMintAccess[ address(0xcb6dBC850121BffbF43B6A9DF3C609FC8F42a111) ] = 3;
freeMintAccess[ address(0xcBaECfE19E1CCb9B48eC729Ffd82AC1a0F7112eD) ] = 3;
freeMintAccess[ address(0xcFEF2A369dBdFF9Ae1E632013E34ea33285969d6) ] = 3;
freeMintAccess[ address(0xD0c4ADd4eD42b02443CEF35Ab64B670b8D81f5bC) ] = 3;
freeMintAccess[ address(0xE15F465a129e9B7E26fC1E4e71a13D118c10cE33) ] = 3;
freeMintAccess[ address(0xe4458edE9a736AEc5dB456d04B3386313a29dC46) ] = 3;
freeMintAccess[ address(0xF6a7629CB1DB16B4F12DFa73085d794483771514) ] = 3;
freeMintAccess[ address(0x00651B9E2924f1a5B63F6460832ab211E5829190) ] = 2;
freeMintAccess[ address(0x01F3a298eb502dB16E298e31CF5Ae8974Fc2de12) ] = 2;
freeMintAccess[ address(0x0360beFfdc22278fd5198e2608f5759EB9B40be4) ] = 2;
freeMintAccess[ address(0x05635698333c7bD541E20d212B201d8f464D286a) ] = 2;
freeMintAccess[ address(0x063972361f92495B2A3d91614B6E18711e8C765D) ] = 2;
freeMintAccess[ address(0x08c85509e3B4bC0b08eB39D7acC06A1D9CDE7B1F) ] = 2;
freeMintAccess[ address(0x0Eb1e0118CCc4E329c9e88efF8c2f6AD14325309) ] = 2;
freeMintAccess[ address(0x142E4B0C91aD69Da00b89e01Bef41f66dE8DA45c) ] = 2;
freeMintAccess[ address(0x14D4c369B7792EE9A1BeaDa5eb8D25555aD246BF) ] = 2;
freeMintAccess[ address(0x18A5862eC62C95B3b370aEdAF40e8971dfAAF7E4) ] = 2;
freeMintAccess[ address(0x1Ee67146295bEB4F64ED72BBb00d00C455D75003) ] = 2;
freeMintAccess[ address(0x1FB7e0cA57d8a22dCc3a8A8FCeB7827eFe7AaBFc) ] = 2;
freeMintAccess[ address(0x203073d988EA2f651f7363CC4468Ae8076BaF84D) ] = 2;
freeMintAccess[ address(0x2110A3BC29CAb77062540fe613952994665406d5) ] = 2;
freeMintAccess[ address(0x21AE1e7524c340709D5734185a89fEb1040a4393) ] = 2;
freeMintAccess[ address(0x242263064cEB2Be99A376C990A52110F6472d879) ] = 2;
freeMintAccess[ address(0x285bB8B9B7331e78B6aAcAd72Ae62a61Db2EAAb2) ] = 2;
freeMintAccess[ address(0x297EA7fa152614C6e65E0c177A8F8c5A52BA2F14) ] = 2;
freeMintAccess[ address(0x2Af6D6ec3a49443d71729f184C3Df65b827411D9) ] = 2;
freeMintAccess[ address(0x2e16ee698B05BDFc0125DD0de5C8913004F5E5c3) ] = 2;
freeMintAccess[ address(0x3172d85857E1ae86F4Fdb6e3143C0b4529e71084) ] = 2;
freeMintAccess[ address(0x323A4e8BD47c9cF0275A31D8a23c8Bbc23367Fcc) ] = 2;
freeMintAccess[ address(0x3364906e33d47B3770A0Db4C6f81824f1881c63a) ] = 2;
freeMintAccess[ address(0x356f221097C5FEB632BB23A9E52eaE8C8a5Fe54B) ] = 2;
freeMintAccess[ address(0x35C663401DC5B007974fcDcc3317596d1378b910) ] = 2;
freeMintAccess[ address(0x35f12c7c6Ad9f23CC0D9Adc2D0f2E7254B03169F) ] = 2;
freeMintAccess[ address(0x35F8aAFEd6658e4A85Eb7431761B4E82E0275d4B) ] = 2;
freeMintAccess[ address(0x383cf70da21bbF077320B1398dFda88f48B7e80F) ] = 2;
freeMintAccess[ address(0x3fA4682DfdC0768f338C4Ac6FADb20379Cf9d3e2) ] = 2;
freeMintAccess[ address(0x4441FD519053AC38601358dC51EF91f672AF1bB9) ] = 2;
freeMintAccess[ address(0x4537628215a44154ea1f9C33c544B3329721E9a6) ] = 2;
freeMintAccess[ address(0x4a9b4cea73531Ebbe64922639683574104e72E4E) ] = 2;
freeMintAccess[ address(0x4b427cC127371621b82a89a02301ef5ee45EA1ED) ] = 2;
freeMintAccess[ address(0x4B71b5420e68Ff460A8154C311cD94aE12222300) ] = 2;
freeMintAccess[ address(0x4Ce304754Bbd6Bfe8643ebba72Cf494ccb089d8e) ] = 2;
freeMintAccess[ address(0x51D0eAA18e9dc6b236a14521a1462bd202894913) ] = 2;
freeMintAccess[ address(0x5226060F20bD813d4fCdc9E3344e493959726648) ] = 2;
freeMintAccess[ address(0x541a62d184c8A00AaaCA48fAd3ad5f1E2ABD1B6C) ] = 2;
freeMintAccess[ address(0x56bF222b0e3a78ad594DB4CcD851706BCCb35eC7) ] = 2;
freeMintAccess[ address(0x56E48cad4419A8a27DE6444f5839d85bCdBAfA27) ] = 2;
freeMintAccess[ address(0x578E141720128EAFFf1261815C85cDFEd438b1Cd) ] = 2;
freeMintAccess[ address(0x59D7F9858a959fD555BF4E81646EE425aAdFE8CE) ] = 2;
freeMintAccess[ address(0x5B50AD735b4B70a764861478545AF6e2CE1Aaafe) ] = 2;
freeMintAccess[ address(0x5c6141CeF1e7eee4778358E4485146fA3d503959) ] = 2;
freeMintAccess[ address(0x5Db8AD9A84AeEAe718C8B225737B2c3C78BdcA59) ] = 2;
freeMintAccess[ address(0x60Fc4A8Db5447EcF020c803464f2aDf5E9647C66) ] = 2;
freeMintAccess[ address(0x612800D4Fc2ea61d24564c9d921a3018647B3d7c) ] = 2;
freeMintAccess[ address(0x64026c16426F07D8B43c1fd37C133EBF7B92dEB4) ] = 2;
freeMintAccess[ address(0x64D479a9326552bCea6F9284ca627CE6F18B5a28) ] = 2;
freeMintAccess[ address(0x64fC6C7CAd57482844f239D9910336a03E6Ce831) ] = 2;
freeMintAccess[ address(0x65EE7980da550072805A12d158Bf14406572F6A8) ] = 2;
freeMintAccess[ address(0x68B7eA5BAB27c42be609AC02505E1120CEd72A7d) ] = 2;
freeMintAccess[ address(0x690ae2e0adf1d939d0Dc9EB757ffC5AcA5a16d00) ] = 2;
freeMintAccess[ address(0x6b37Cc92c7653D4c33d144Cb8284c48a02968fd2) ] = 2;
freeMintAccess[ address(0x6d22E1F7060D78C753A4498C2d48fE71643Fa1d6) ] = 2;
freeMintAccess[ address(0x705AB1Ff5205216e3d49B53223B56A5E159e7835) ] = 2;
freeMintAccess[ address(0x70C01b34BC0B8963FD747100430aeD647F4dDcdC) ] = 2;
freeMintAccess[ address(0x77AEeA17E3e367A0966a8b8BE8eC912797F4A929) ] = 2;
freeMintAccess[ address(0x7E7CfF0bE2A2baD0e5e879Ff17eD9B615dFe3Ab4) ] = 2;
freeMintAccess[ address(0x80C56dE765ebDFBB5b2992337B1F247C7F728dFC) ] = 2;
freeMintAccess[ address(0x816F81C3fA8368CDB1EaaD755ca50c62fdA9b60D) ] = 2;
freeMintAccess[ address(0x8205EB5Ed2D325e6381f62e4c0e6537F5B968bD5) ] = 2;
freeMintAccess[ address(0x821fD4c8f28B47619811A7825540A7B0049B0f66) ] = 2;
freeMintAccess[ address(0x8364E59631d012EaD8a4DB965df4f174DA05A260) ] = 2;
freeMintAccess[ address(0x848573085b783511a47850f7C0475F3224a0fc2D) ] = 2;
freeMintAccess[ address(0x866241207F759B646Dad2C9416d55045aE55Bc0B) ] = 2;
freeMintAccess[ address(0x8b835e35838448a8A29Be15E926D99E9FB040822) ] = 2;
freeMintAccess[ address(0x8Dc047Ce563680D2553a95Cb357EE321c164aFe0) ] = 2;
freeMintAccess[ address(0x95631A17dd0F4D19eb90Cc6A0a7e330C987a5139) ] = 2;
freeMintAccess[ address(0x986eAa8d5a0EC0a0f0433BBB249D15E5430CF550) ] = 2;
freeMintAccess[ address(0x990450d56c41ef5e7d818E0453c2f813FEb9448A) ] = 2;
freeMintAccess[ address(0x996d25fc973756cA9a177510C28afa18BEf27499) ] = 2;
freeMintAccess[ address(0x9EC02aAE4653bd59aC2cE64A135c22Ade5c1856A) ] = 2;
freeMintAccess[ address(0xA22F59899BFa6D3d24a0b488fBD830f6B922e1dA) ] = 2;
freeMintAccess[ address(0xa6B59f2d1409B2240c4a7A02B2d27d8b15Bd2248) ] = 2;
freeMintAccess[ address(0xa8f6deDCAe4D391Eaa009CB6f848bB31fDB47D02) ] = 2;
freeMintAccess[ address(0xa91A55e5EfEB84Ce3d7f0Eac207B175f4c1940Ca) ] = 2;
freeMintAccess[ address(0xb4C69Cf41894F7c372f349C35F0477511881bDEF) ] = 2;
freeMintAccess[ address(0xB631f4eA32A8876ae37ee475C6912e94AB853694) ] = 2;
freeMintAccess[ address(0xB7c6020f4A7B4ef1b4a621E48B5bA0284f2BEee1) ] = 2;
freeMintAccess[ address(0xBc48d0cb0f85434186b83263dcBbA6bfE79CAa10) ] = 2;
freeMintAccess[ address(0xbC4afF27c74e76e4639993679e243f80f8F455fc) ] = 2;
freeMintAccess[ address(0xBd03118971755fC60e769C05067061ebf97064ba) ] = 2;
freeMintAccess[ address(0xBF7FD93Fe70Fd6126c6f06DfBCe4EcA9Ac09e050) ] = 2;
freeMintAccess[ address(0xC5301285da585125B1dc8CCCedD1de1845b68c0F) ] = 2;
freeMintAccess[ address(0xC58BD7961088bC22Bb26232b7973973322E272f5) ] = 2;
freeMintAccess[ address(0xC7fbAda2D0596377B748a73428749874BD037c39) ] = 2;
freeMintAccess[ address(0xCbC0A5724626618EA59dfcc1923f16FB370E602b) ] = 2;
freeMintAccess[ address(0xCf81AfD911E4c86fe1c3396776eDAa4972c4033c) ] = 2;
freeMintAccess[ address(0xd10C4a705bB5eDA3498EC9a1eBFf1fDBfE265352) ] = 2;
freeMintAccess[ address(0xda51c29BA453229eb2A606AB771800E341EDE8c8) ] = 2;
freeMintAccess[ address(0xdEe435A6d24bed1c5391515417692239f3d5951f) ] = 2;
freeMintAccess[ address(0xdFDBca65041662139e87555646967B5aBb628c5c) ] = 2;
freeMintAccess[ address(0xe324C2f2524c0a7288866F9D132d5b43ef038349) ] = 2;
freeMintAccess[ address(0xe3b29c5794Ac8C9c7c9fdE346209d1927A1E7B33) ] = 2;
freeMintAccess[ address(0xE8eb3Ab24b9770a9A7ab9e245D21F4D6F607c651) ] = 2;
freeMintAccess[ address(0xea6A7C8064e528205f36b1971CDAcf114762e1Ee) ] = 2;
freeMintAccess[ address(0xeB96B4217DA1221054F9f40d47191a2CD900285c) ] = 2;
freeMintAccess[ address(0xeD176ef200Ac42bDdDB95983815265b8063fcA48) ] = 2;
freeMintAccess[ address(0xeE4B71C36d17b1c70E438F8204907C5e068229cc) ] = 2;
freeMintAccess[ address(0xEeA5F603558a2b700291511B030fF1F5edFb1287) ] = 2;
freeMintAccess[ address(0xf208A854d8dd608Ad95644e7ca3A59a31aAcDE9E) ] = 2;
freeMintAccess[ address(0xF27f990990803513D65710c6615664Ed8F6830b8) ] = 2;
freeMintAccess[ address(0xff4Ca96eD50cd35e165Ac65a56b3524BBD30BfE1) ] = 2;
}
} | Max per wallet checkPrice check | function presaleMint(
uint256 amount,
bytes calldata signature
) external payable {
require(
workflow == WorkflowStatus.Presale,
"NaftyDolls: Presale is not currently active."
);
require(
validateSignature(
presaleAddress,
signature
),
"SIGNATURE_VALIDATION_FAILED"
);
require(amount > 0, "You must mint at least one token");
require(
presaleMintLog[ msg.sender ] + amount <= maxPerWallet,
"NaftyDolls: You have exceeded the max per wallet amount!"
);
require(
msg.value >= presalePrice * amount,
"NaftyDolls: Insuficient ETH amount sent."
);
require(
presaleCount + amount <= MAX_PRESALE,
"NaftyDolls: Selected amount exceeds the max presale supply"
);
presaleCount += amount;
currentSupply += amount;
presaleMintLog[ msg.sender ] += amount;
mintBatch(msg.sender, currentSupply - amount, amount);
}
| 14,692,373 |
// https://etherscan.io/address/0x594a198048501a304267e63b3bad0f0638da7628#code
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
import "../../lib/erc20.sol";
import "../../lib/safe-math.sol";
import "./scrv-voter.sol";
import "./crv-locker.sol";
import "../../interfaces/jar.sol";
import "../../interfaces/curve.sol";
import "../../interfaces/uniswapv2.sol";
import "../../interfaces/controller.sol";
import "../strategy-base.sol";
contract StrategyCurveSCRVv4_1 is StrategyBase {
// Curve
address public scrv = 0xC25a3A3b969415c80451098fa907EC722572917F;
address public susdv2_gauge = 0xA90996896660DEcC6E997655E065b23788857849;
address public susdv2_pool = 0xA5407eAE9Ba41422680e2e00537571bcC53efBfD;
address public escrow = 0x5f3b5DfEb7B28CDbD7FAba78963EE202a494e2A2;
// curve dao
address public gauge;
address public curve;
address public mintr = 0xd061D61a4d941c39E5453435B6345Dc261C2fcE0;
// tokens we're farming
address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52;
address public constant snx = 0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F;
// stablecoins
address public dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
address public susd = 0x57Ab1ec28D129707052df4dF418D58a2D46d5f51;
// How much CRV tokens to keep
uint256 public keepCRV = 500;
uint256 public keepCRVMax = 10000;
// crv-locker and voter
address public scrvVoter;
address public crvLocker;
constructor(
address _scrvVoter,
address _crvLocker,
address _governance,
address _strategist,
address _controller,
address _timelock
)
public
StrategyBase(scrv, _governance, _strategist, _controller, _timelock)
{
curve = susdv2_pool;
gauge = susdv2_gauge;
scrvVoter = _scrvVoter;
crvLocker = _crvLocker;
}
// **** Getters ****
function balanceOfPool() public override view returns (uint256) {
return SCRVVoter(scrvVoter).balanceOf(gauge);
}
function getName() external override pure returns (string memory) {
return "StrategyCurveSCRVv4_1";
}
function getHarvestable() external returns (uint256) {
return ICurveGauge(gauge).claimable_tokens(crvLocker);
}
function getMostPremium() public view returns (address, uint8) {
uint256[] memory balances = new uint256[](4);
balances[0] = ICurveFi_4(curve).balances(0); // DAI
balances[1] = ICurveFi_4(curve).balances(1).mul(10**12); // USDC
balances[2] = ICurveFi_4(curve).balances(2).mul(10**12); // USDT
balances[3] = ICurveFi_4(curve).balances(3); // sUSD
// DAI
if (
balances[0] < balances[1] &&
balances[0] < balances[2] &&
balances[0] < balances[3]
) {
return (dai, 0);
}
// USDC
if (
balances[1] < balances[0] &&
balances[1] < balances[2] &&
balances[1] < balances[3]
) {
return (usdc, 1);
}
// USDT
if (
balances[2] < balances[0] &&
balances[2] < balances[1] &&
balances[2] < balances[3]
) {
return (usdt, 2);
}
// SUSD
if (
balances[3] < balances[0] &&
balances[3] < balances[1] &&
balances[3] < balances[2]
) {
return (susd, 3);
}
// If they're somehow equal, we just want DAI
return (dai, 0);
}
// **** Setters ****
function setKeepCRV(uint256 _keepCRV) external {
require(msg.sender == governance, "!governance");
keepCRV = _keepCRV;
}
// **** State Mutations ****
function deposit() public override {
uint256 _want = IERC20(want).balanceOf(address(this));
if (_want > 0) {
IERC20(want).safeTransfer(scrvVoter, _want);
SCRVVoter(scrvVoter).deposit(gauge, want);
}
}
function _withdrawSome(uint256 _amount)
internal
override
returns (uint256)
{
return SCRVVoter(scrvVoter).withdraw(gauge, want, _amount);
}
function harvest() public override onlyBenevolent {
// Anyone can harvest it at any given time.
// I understand the possibility of being frontrun / sandwiched
// But ETH is a dark forest, and I wanna see how this plays out
// i.e. will be be heavily frontrunned/sandwiched?
// if so, a new strategy will be deployed.
// stablecoin we want to convert to
(address to, uint256 toIndex) = getMostPremium();
// Collects crv tokens
// Don't bother voting in v1
SCRVVoter(scrvVoter).harvest(gauge);
uint256 _crv = IERC20(crv).balanceOf(address(this));
if (_crv > 0) {
// How much CRV to keep to restake?
uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax);
IERC20(crv).safeTransfer(address(crvLocker), _keepCRV);
// How much CRV to swap?
_crv = _crv.sub(_keepCRV);
_swapUniswap(crv, to, _crv);
}
// Collects SNX tokens
SCRVVoter(scrvVoter).claimRewards();
uint256 _snx = IERC20(snx).balanceOf(address(this));
if (_snx > 0) {
_swapUniswap(snx, to, _snx);
}
// Adds liquidity to curve.fi's susd pool
// to get back want (scrv)
uint256 _to = IERC20(to).balanceOf(address(this));
if (_to > 0) {
IERC20(to).safeApprove(curve, 0);
IERC20(to).safeApprove(curve, _to);
uint256[4] memory liquidity;
liquidity[toIndex] = _to;
ICurveFi_4(curve).add_liquidity(liquidity, 0);
}
// We want to get back sCRV
_distributePerformanceFeesAndDeposit();
}
}
| Anyone can harvest it at any given time. I understand the possibility of being frontrun / sandwiched But ETH is a dark forest, and I wanna see how this plays out i.e. will be be heavily frontrunned/sandwiched? if so, a new strategy will be deployed. stablecoin we want to convert to Collects crv tokens Don't bother voting in v1 How much CRV to keep to restake? How much CRV to swap? | function harvest() public override onlyBenevolent {
(address to, uint256 toIndex) = getMostPremium();
SCRVVoter(scrvVoter).harvest(gauge);
uint256 _crv = IERC20(crv).balanceOf(address(this));
if (_crv > 0) {
uint256 _keepCRV = _crv.mul(keepCRV).div(keepCRVMax);
IERC20(crv).safeTransfer(address(crvLocker), _keepCRV);
_crv = _crv.sub(_keepCRV);
_swapUniswap(crv, to, _crv);
}
uint256 _snx = IERC20(snx).balanceOf(address(this));
if (_snx > 0) {
_swapUniswap(snx, to, _snx);
}
if (_to > 0) {
IERC20(to).safeApprove(curve, 0);
IERC20(to).safeApprove(curve, _to);
uint256[4] memory liquidity;
liquidity[toIndex] = _to;
ICurveFi_4(curve).add_liquidity(liquidity, 0);
}
}
| 1,774,374 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.6.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IEmiswap.sol";
import "./libraries/EmiswapLib.sol";
import "./libraries/TransferHelper.sol";
import "./interfaces/IWETH.sol";
contract EmiRouter {
using SafeMath for uint256;
address public immutable factory;
address public immutable WETH;
event Log(uint256 a, uint256 b);
constructor(address _factory, address _WETH) public {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** Liquidity ****
/**
* @param tokenA address of first token in pair
* @param tokenB address of second token in pair
* @return LP balance
*/
function getLiquidity(
address tokenA,
address tokenB
)
external
view
returns (uint256)
{
return(
IERC20(
address( IEmiswapRegistry(factory).pools(IERC20(tokenA), IERC20(tokenB)) )
).balanceOf(msg.sender)
);
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin
)
internal
returns (uint256 amountA, uint256 amountB)
{
IERC20 ERC20tokenA = IERC20(tokenA);
IERC20 ERC20tokenB = IERC20(tokenB);
IEmiswap pairContract = IEmiswapRegistry(factory).pools(ERC20tokenA, ERC20tokenB);
// create the pair if it doesn't exist yet
if (pairContract == IEmiswap(0)) {
pairContract = IEmiswapRegistry(factory).deploy(ERC20tokenA, ERC20tokenB);
}
uint256 reserveA = pairContract.getBalanceForAddition(ERC20tokenA);
uint256 reserveB = pairContract.getBalanceForRemoval(ERC20tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = EmiswapLib.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, "EmiswapRouter: INSUFFICIENT_B_AMOUNT");
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = EmiswapLib.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, "EmiswapRouter: INSUFFICIENT_A_AMOUNT");
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
/**
* @param tokenA address of first token in pair
* @param tokenB address of second token in pair
* @param amountADesired desired amount of first token
* @param amountBDesired desired amount of second token
* @param amountAMin minimum amount of first token
* @param amountBMin minimum amount of second token
* @return amountA added liquidity of first token
* @return amountB added liquidity of second token
* @return liquidity
*/
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin
)
external
returns (uint256 amountA, uint256 amountB, uint256 liquidity)
{
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
IEmiswap pairContract = IEmiswapRegistry(factory).pools(IERC20(tokenA), IERC20(tokenB));
TransferHelper.safeTransferFrom(tokenA, msg.sender, address(this), amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, address(this), amountB);
TransferHelper.safeApprove(tokenA, address(pairContract), amountA);
TransferHelper.safeApprove(tokenB, address(pairContract), amountB);
uint256[] memory amounts;
amounts = new uint256[](2);
uint256[] memory minAmounts;
minAmounts = new uint256[](2);
if (tokenA < tokenB) {
amounts[0] = amountA;
amounts[1] = amountB;
minAmounts[0] = amountAMin;
minAmounts[1] = amountBMin;
} else {
amounts[0] = amountB;
amounts[1] = amountA;
minAmounts[0] = amountBMin;
minAmounts[1] = amountAMin;
}
//emit Log(amounts[0], amounts[1]);
liquidity = IEmiswap(pairContract).deposit(amounts, minAmounts);
TransferHelper.safeTransfer(address(pairContract), msg.sender, liquidity);
}
/**
* @param token address of token
* @param amountTokenDesired desired amount of token
* @param amountTokenMin minimum amount of token
* @param amountETHMin minimum amount of ETH
* @return amountToken added liquidity of token
* @return amountETH added liquidity of ETH
* @return liquidity
*/
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin
)
external
payable
returns (uint amountToken, uint amountETH, uint liquidity)
{
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
IEmiswap pairContract = IEmiswapRegistry(factory).pools(IERC20(token), IERC20(WETH));
TransferHelper.safeTransferFrom(token, msg.sender, address(this), amountToken);
TransferHelper.safeApprove(token, address(pairContract), amountToken);
IWETH(WETH).deposit{value: amountETH}();
TransferHelper.safeApprove(WETH, address(pairContract), amountToken);
uint256[] memory amounts;
amounts = new uint256[](2);
uint256[] memory minAmounts;
minAmounts = new uint256[](2);
if (token < WETH) {
amounts[0] = amountToken;
amounts[1] = amountETH;
minAmounts[0] = amountTokenMin;
minAmounts[1] = amountETHMin;
} else {
amounts[0] = amountETH;
amounts[1] = amountToken;
minAmounts[0] = amountETHMin;
minAmounts[1] = amountTokenMin;
}
liquidity = IEmiswap(pairContract).deposit(amounts, minAmounts);
TransferHelper.safeTransfer(address(pairContract), msg.sender, liquidity);
}
// **** REMOVE LIQUIDITY ****
/**
* @param tokenA address of first token in pair
* @param tokenB address of second token in pair
* @param liquidity LP token
* @param amountAMin minimum amount of first token
* @param amountBMin minimum amount of second token
*/
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin
)
public
{
IEmiswap pairContract = IEmiswapRegistry(factory).pools(IERC20(tokenA), IERC20(tokenB));
TransferHelper.safeTransferFrom(address(pairContract), msg.sender, address(this), liquidity); // send liquidity to this
uint256[] memory minReturns;
minReturns = new uint256[](2);
if (tokenA < tokenB) {
minReturns[0] = amountAMin;
minReturns[1] = amountBMin;
} else {
minReturns[0] = amountBMin;
minReturns[1] = amountAMin;
}
uint256 tokenAbalance = IERC20(tokenA).balanceOf(address(this));
uint256 tokenBbalance = IERC20(tokenB).balanceOf(address(this));
pairContract.withdraw(liquidity, minReturns);
tokenAbalance = IERC20(tokenA).balanceOf(address(this)).sub(tokenAbalance);
tokenBbalance = IERC20(tokenB).balanceOf(address(this)).sub(tokenBbalance);
TransferHelper.safeTransfer(tokenA, msg.sender, tokenAbalance);
TransferHelper.safeTransfer(tokenB, msg.sender, tokenBbalance);
}
/**
* @param token address of token
* @param liquidity LP token amount
* @param amountTokenMin minimum amount of token
* @param amountETHMin minimum amount of ETH
*/
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin
)
public
{
IEmiswap pairContract = IEmiswapRegistry(factory).pools(IERC20(token), IERC20(WETH));
TransferHelper.safeTransferFrom( address(pairContract), msg.sender, address(this), liquidity ); // send liquidity to this
uint256[] memory minReturns;
minReturns = new uint256[](2);
if (token < WETH) {
minReturns[0] = amountTokenMin;
minReturns[1] = amountETHMin;
} else {
minReturns[0] = amountETHMin;
minReturns[1] = amountTokenMin;
}
uint256 tokenbalance = IERC20(token).balanceOf(address(this));
uint256 WETHbalance = IERC20(WETH).balanceOf(address(this));
pairContract.withdraw(liquidity, minReturns);
tokenbalance = IERC20(token).balanceOf(address(this)).sub(tokenbalance);
WETHbalance = IERC20(WETH).balanceOf(address(this)).sub(WETHbalance);
TransferHelper.safeTransfer(token, msg.sender, tokenbalance);
// convert WETH and send back raw ETH
IWETH(WETH).withdraw(WETHbalance);
TransferHelper.safeTransferETH(msg.sender, WETHbalance);
}
// **** SWAP ****
function _swap_(
address tokenFrom,
address tokenTo,
uint256 ammountFrom,
address to,
address ref
)
internal
returns(uint256 ammountTo)
{
IEmiswap pairContract = IEmiswapRegistry(factory).pools(IERC20(tokenFrom), IERC20(tokenTo));
if (pairContract.getReturn(IERC20(tokenFrom), IERC20(tokenTo), ammountFrom) > 0)
{
TransferHelper.safeApprove(tokenFrom, address(pairContract), ammountFrom);
ammountTo = pairContract.swap(IERC20(tokenFrom), IERC20(tokenTo), ammountFrom, 0, to, ref);
}
}
function _swapbyRoute (
address[] memory path,
uint256 ammountFrom,
address to,
address ref
)
internal
returns(uint256 ammountTo)
{
for (uint256 i=0; i < path.length - 1; i++) {
if (path.length >= 2) {
uint256 _ammountTo = _swap_(path[i], path[i+1], ammountFrom, to, ref);
if (i == (path.length - 2)) {
return(_ammountTo);
} else {
ammountFrom = _ammountTo;
}
}
}
}
/**
* @param amountIn exact in value of source token
* @param amountOutMin minimum amount value of result token
* @param path array of token addresses, represent the path for swaps
* @param to send result token to
* @param ref referral
* @return amounts result amount
*/
function swapExactTokensForTokens (
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
address ref
)
external
returns (uint256[] memory amounts)
{
amounts = getAmountsOut(amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, "EmiswapRouter: INSUFFICIENT_OUTPUT_AMOUNT");
TransferHelper.safeTransferFrom(path[0], msg.sender, address(this), amountIn);
_swapbyRoute(path, amountIn, to, ref);
}
/**
* @param amountOut exact in value of result token
* @param amountInMax maximum amount value of source token
* @param path array of token addresses, represent the path for swaps
* @param to send result token to
* @param ref referral
* @return amounts result amount values
*/
function swapTokensForExactTokens (
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
address ref
)
external
returns (uint256[] memory amounts)
{
amounts = getAmountsIn(amountOut, path);
require(amounts[0] <= amountInMax, "EmiswapRouter: EXCESSIVE_INPUT_AMOUNT");
TransferHelper.safeTransferFrom(path[0], msg.sender, address(this), amounts[0]);
_swapbyRoute(path, amounts[0], to, ref);
}
/**
* @param amountOutMin minimum amount value of result token
* @param path array of token addresses, represent the path for swaps
* @param to send result token to
* @param ref referral
* @return amounts result token amount values
*/
function swapExactETHForTokens (
uint256 amountOutMin,
address[] calldata path,
address to,
address ref
)
external
payable
returns (uint[] memory amounts)
{
require(path[0] == WETH, "EmiswapRouter: INVALID_PATH");
amounts = getAmountsOut(msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, "EmiswapRouter: INSUFFICIENT_OUTPUT_AMOUNT");
IWETH(WETH).deposit{value: amounts[0]}();
_swapbyRoute(path, amounts[0], to, ref);
}
/**
* @param amountOut amount value of result ETH
* @param amountInMax maximum amount of source token
* @param path array of token addresses, represent the path for swaps, (WETH for ETH)
* @param to send result token to
* @param ref referral
* @return amounts result token amount values
*/
function swapTokensForExactETH (
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
address ref
)
external
returns (uint256[] memory amounts)
{
require(path[path.length - 1] == WETH, "EmiswapRouter: INVALID_PATH");
amounts = getAmountsIn(amountOut, path);
require(amounts[0] <= amountInMax, "EmiswapRouter: EXCESSIVE_INPUT_AMOUNT");
TransferHelper.safeTransferFrom( path[0], msg.sender, address(this), amounts[0]);
uint256 result = _swapbyRoute(path, amounts[0], address(this), ref);
IWETH(WETH).withdraw(result);
TransferHelper.safeTransferETH(to, result);
}
/**
* @param amountIn amount value of source token
* @param path array of token addresses, represent the path for swaps, (WETH for ETH)
* @param to send result token to
* @param ref referral
*/
function swapExactTokensForETH (
uint256 amountIn,
address[] calldata path,
address to,
address ref
)
external
{
require(path[path.length - 1] == WETH, "EmiswapRouter: INVALID_PATH");
TransferHelper.safeTransferFrom( path[0], msg.sender, address(this), amountIn);
uint256 result = _swapbyRoute(path, amountIn, address(this), ref);
IWETH(WETH).withdraw( result );
TransferHelper.safeTransferETH(to, result);
}
/**
* @param amountOut amount of result tokens
* @param path array of token addresses, represent the path for swaps, (WETH for ETH)
* @param to send result token to
* @param ref referral
* @return amounts result token amount values
*/
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
address ref
)
external
payable
returns (uint256[] memory amounts)
{
require(path[0] == WETH, "EmiswapRouter: INVALID_PATH");
amounts = getAmountsIn(amountOut, path);
require(amounts[0] <= msg.value, "EmiswapRouter: EXCESSIVE_INPUT_AMOUNT");
IWETH(WETH).deposit{value: amounts[0]}();
_swapbyRoute(path, amounts[0], to, ref);
}
// **** LIBRARY FUNCTIONS ****
/**
* @param amountIn amount of source token
* @param path array of token addresses, represent the path for swaps, (WETH for ETH)
* @return amounts result token amount values
*/
function getAmountsOut(uint amountIn, address[] memory path)
public
view
returns (uint[] memory amounts)
{
return EmiswapLib.getAmountsOut(factory, amountIn, path);
}
/**
* @param amountOut amount of result token
* @param path array of token addresses, represent the path for swaps, (WETH for ETH)
* @return amounts result token amount values
*/
function getAmountsIn(uint amountOut, address[] memory path)
public
view
returns (uint[] memory amounts)
{
return EmiswapLib.getAmountsIn(factory, amountOut, path);
}
} | REMOVE LIQUIDITY tokenA address of first token in pair tokenB address of second token in pair liquidity LP token amountAMin minimum amount of first token amountBMin minimum amount of second token/ | function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin
)
public
{
IEmiswap pairContract = IEmiswapRegistry(factory).pools(IERC20(tokenA), IERC20(tokenB));
uint256[] memory minReturns;
minReturns = new uint256[](2);
if (tokenA < tokenB) {
minReturns[0] = amountAMin;
minReturns[1] = amountBMin;
minReturns[0] = amountBMin;
minReturns[1] = amountAMin;
}
uint256 tokenAbalance = IERC20(tokenA).balanceOf(address(this));
uint256 tokenBbalance = IERC20(tokenB).balanceOf(address(this));
pairContract.withdraw(liquidity, minReturns);
tokenAbalance = IERC20(tokenA).balanceOf(address(this)).sub(tokenAbalance);
tokenBbalance = IERC20(tokenB).balanceOf(address(this)).sub(tokenBbalance);
TransferHelper.safeTransfer(tokenA, msg.sender, tokenAbalance);
TransferHelper.safeTransfer(tokenB, msg.sender, tokenBbalance);
}
| 13,132,283 |
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/utils/EnumerableSet.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
function _ADD852(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
if (!_CONTAINS492(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
function _REMOVE675(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
function _CONTAINS492(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING
return set._indexes[value] != 0;
}
function _LENGTH742(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING
return set._values.length;
}
function _AT360(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
function ADD146(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD852(set._inner, bytes32(uint256(value)));
}
function REMOVE620(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE675(set._inner, bytes32(uint256(value)));
}
function CONTAINS72(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS492(set._inner, bytes32(uint256(value)));
}
function LENGTH675(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH742(set._inner);
}
function AT889(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING
return address(uint256(_AT360(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
function ADD146(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD852(set._inner, bytes32(value));
}
function REMOVE620(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE675(set._inner, bytes32(value));
}
function CONTAINS72(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS492(set._inner, bytes32(value));
}
function LENGTH675(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH742(set._inner);
}
function AT889(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING
return uint256(_AT360(set._inner, index));
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/GSN/Context.sol
//
pragma solidity ^0.7.0;
abstract contract Context {
function _MSGSENDER914() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA708() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/access/AccessControl.sol
//
pragma solidity ^0.7.0;
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant default_admin_role935 = 0x00; //inject NONSTANDARD NAMING
event ROLEADMINCHANGED723(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); //inject NONSTANDARD NAMING
event ROLEGRANTED103(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING
event ROLEREVOKED950(bytes32 indexed role, address indexed account, address indexed sender); //inject NONSTANDARD NAMING
function HASROLE117(bytes32 role, address account) public view returns (bool) { //inject NONSTANDARD NAMING
return _roles[role].members.CONTAINS72(account);
}
function GETROLEMEMBERCOUNT773(bytes32 role) public view returns (uint256) { //inject NONSTANDARD NAMING
return _roles[role].members.LENGTH675();
}
function GETROLEMEMBER894(bytes32 role, uint256 index) public view returns (address) { //inject NONSTANDARD NAMING
return _roles[role].members.AT889(index);
}
function GETROLEADMIN738(bytes32 role) public view returns (bytes32) { //inject NONSTANDARD NAMING
return _roles[role].adminRole;
}
function GRANTROLE962(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(HASROLE117(_roles[role].adminRole, _MSGSENDER914()), "AccessControl: sender must be an admin to grant");
_GRANTROLE886(role, account);
}
function REVOKEROLE159(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(HASROLE117(_roles[role].adminRole, _MSGSENDER914()), "AccessControl: sender must be an admin to revoke");
_REVOKEROLE39(role, account);
}
function RENOUNCEROLE17(bytes32 role, address account) public virtual { //inject NONSTANDARD NAMING
require(account == _MSGSENDER914(), "AccessControl: can only renounce roles for self");
_REVOKEROLE39(role, account);
}
function _SETUPROLE488(bytes32 role, address account) internal virtual { //inject NONSTANDARD NAMING
_GRANTROLE886(role, account);
}
function _SETROLEADMIN697(bytes32 role, bytes32 adminRole) internal virtual { //inject NONSTANDARD NAMING
emit ROLEADMINCHANGED723(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _GRANTROLE886(bytes32 role, address account) private { //inject NONSTANDARD NAMING
if (_roles[role].members.ADD146(account)) {
emit ROLEGRANTED103(role, account, _MSGSENDER914());
}
}
function _REVOKEROLE39(bytes32 role, address account) private { //inject NONSTANDARD NAMING
if (_roles[role].members.REMOVE620(account)) {
emit ROLEREVOKED950(role, account, _MSGSENDER914());
}
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/utils/Address.sol
//
pragma solidity ^0.7.0;
library Address {
function ISCONTRACT647(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function SENDVALUE238(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function FUNCTIONCALL669(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL669(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL669(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE523(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE570(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE570(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE570(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= value, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE523(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE523(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT647(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/math/SafeMath.sol
//
pragma solidity ^0.7.0;
library SafeMath {
function ADD146(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB570(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB570(a, b, "SafeMath: subtraction overflow");
}
function SUB570(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL634(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV640(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV640(a, b, "SafeMath: division by zero");
}
function DIV640(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD654(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD654(a, b, "SafeMath: modulo by zero");
}
function MOD654(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/token/ERC20/IERC20.sol
//
pragma solidity ^0.7.0;
interface IERC20 {
function TOTALSUPPLY217() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF756(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER622(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE863(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE47(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM568(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER456(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL815(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
// File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.2.0-solc-0.7/contracts/token/ERC20/ERC20.sol
//
pragma solidity ^0.7.0;
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME91() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL382() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS96() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY217() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF756(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER622(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER619(_MSGSENDER914(), recipient, amount);
return true;
}
function ALLOWANCE863(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE47(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE737(_MSGSENDER914(), spender, amount);
return true;
}
function TRANSFERFROM568(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER619(sender, recipient, amount);
_APPROVE737(sender, _MSGSENDER914(), _allowances[sender][_MSGSENDER914()].SUB570(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE53(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE737(_MSGSENDER914(), spender, _allowances[_MSGSENDER914()][spender].ADD146(addedValue));
return true;
}
function DECREASEALLOWANCE706(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE737(_MSGSENDER914(), spender, _allowances[_MSGSENDER914()][spender].SUB570(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER619(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER428(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB570(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD146(amount);
emit TRANSFER456(sender, recipient, amount);
}
function _MINT727(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER428(address(0), account, amount);
_totalSupply = _totalSupply.ADD146(amount);
_balances[account] = _balances[account].ADD146(amount);
emit TRANSFER456(address(0), account, amount);
}
function _BURN562(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER428(account, address(0), amount);
_balances[account] = _balances[account].SUB570(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB570(amount);
emit TRANSFER456(account, address(0), amount);
}
function _APPROVE737(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL815(owner, spender, amount);
}
function _SETUPDECIMALS703(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER428(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
abstract contract ERC20Burnable is Context, ERC20 {
using SafeMath for uint256;
function BURN447(uint256 amount) public virtual { //inject NONSTANDARD NAMING
_BURN562(_MSGSENDER914(), amount);
}
function BURNFROM566(address account, uint256 amount) public virtual { //inject NONSTANDARD NAMING
uint256 decreasedAllowance = ALLOWANCE863(account, _MSGSENDER914()).SUB570(amount, "ERC20: burn amount exceeds allowance");
_APPROVE737(account, _MSGSENDER914(), decreasedAllowance);
_BURN562(account, amount);
}
}
// File: browser/TokenERC20.sol
//
pragma solidity ^0.7;
contract Token is ERC20Burnable, AccessControl {
bytes32 public constant minter_role392 = keccak256("MINTER_ROLE"); //inject NONSTANDARD NAMING
bytes32 public constant burner_role509 = keccak256("BURNER_ROLE"); //inject NONSTANDARD NAMING
constructor (string memory name, string memory symbol) ERC20(name, symbol) {
_SETUPROLE488(default_admin_role935, _MSGSENDER914());
_SETUPROLE488(minter_role392, _MSGSENDER914());
_SETUPROLE488(burner_role509, _MSGSENDER914());
}
function MINT678(address to, uint256 amount) public { //inject NONSTANDARD NAMING
require(HASROLE117(minter_role392, _MSGSENDER914()), "Caller is not a minter");
_MINT727(to, amount);
}
function BURN447(uint256 amount) public override { //inject NONSTANDARD NAMING
require(HASROLE117(burner_role509, _MSGSENDER914()), "Caller is not a burner");
super.BURN447(amount);
}
function BURNFROM566(address account, uint256 amount) public override { //inject NONSTANDARD NAMING
require(HASROLE117(burner_role509, _MSGSENDER914()), "Caller is not a burner");
super.BURNFROM566(account, amount);
}
}
interface IERC20Ops {
function MINT678(address, uint256) external; //inject NONSTANDARD NAMING
function BURNFROM566(address, uint256) external; //inject NONSTANDARD NAMING
function DECIMALS96() external view returns (uint8); //inject NONSTANDARD NAMING
}
contract TokenSwap is AccessControl {
bytes32 public constant whitelisted497 = keccak256("WHITELISTED"); //inject NONSTANDARD NAMING
address public oldToken;
address public newToken;
uint8 public decimalsFactor;
bool public positiveDecimalsFactor;
constructor(address _oldToken, address _newToken){
oldToken = _oldToken;
newToken = _newToken;
uint8 oldTokenDecimals = IERC20Ops(oldToken).DECIMALS96();
uint8 newTokenDecimals = IERC20Ops(newToken).DECIMALS96();
if (newTokenDecimals >= oldTokenDecimals){
decimalsFactor = newTokenDecimals - oldTokenDecimals;
positiveDecimalsFactor = true;
}
else {
decimalsFactor = oldTokenDecimals - newTokenDecimals;
positiveDecimalsFactor = false;
}
_SETUPROLE488(default_admin_role935, _MSGSENDER914());
_SETUPROLE488(whitelisted497, _MSGSENDER914());
}
function WHITELISTED831(address addr) public view returns (bool) { //inject NONSTANDARD NAMING
return HASROLE117(whitelisted497, addr);
}
function WHITELISTADD908(address[] memory addrs) public { //inject NONSTANDARD NAMING
require(HASROLE117(default_admin_role935, _MSGSENDER914()), "Caller is not admin");
for (uint256 i = 0; i < addrs.length; i++){
GRANTROLE962(whitelisted497, addrs[i]);
}
}
function WHITELISTREMOVE906(address[] memory addrs) public { //inject NONSTANDARD NAMING
require(HASROLE117(default_admin_role935, _MSGSENDER914()), "Caller is not admin");
for (uint256 i = 0; i < addrs.length; i++){
REVOKEROLE159(whitelisted497, addrs[i]);
}
}
function SWAP530(uint256 val) public { //inject NONSTANDARD NAMING
require(HASROLE117(whitelisted497, _MSGSENDER914()), "Caller is not whitelisted");
IERC20Ops(oldToken).BURNFROM566(_MSGSENDER914(), val);
if (positiveDecimalsFactor) IERC20Ops(newToken).MINT678(_MSGSENDER914(), val * (10 ** decimalsFactor));
else IERC20Ops(newToken).MINT678(_MSGSENDER914(), val / (10 ** decimalsFactor));
}
} | inject NONSTANDARD NAMING | function _SETROLEADMIN697(bytes32 role, bytes32 adminRole) internal virtual { | 5,351,538 |
/**
* Golden Union - Blockchain platform for direct investment in gold mining
* https://goldenunion.org
* ----------------------------
* telegram @golden_union
* developed by Inout Corp
*/
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferWholeTokens(address _to, uint256 _value) public returns (bool) {
// the sum is entered in whole tokens (1 = 1 token)
uint256 value = _value;
value = value.mul(1 ether);
return transfer(_to, value);
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract GoldenUnitToken is StandardToken {
string public constant name = "Golden Unite Token";
string public constant symbol = "GUT";
uint32 public constant decimals = 18;
uint256 public INITIAL_SUPPLY = 50000 * 1 ether;
address public CrowdsaleAddress;
event Mint(address indexed to, uint256 amount);
constructor(address _CrowdsaleAddress) public {
CrowdsaleAddress = _CrowdsaleAddress;
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
modifier onlyOwner() {
require(msg.sender == CrowdsaleAddress);
_;
}
function acceptTokens(address _from, uint256 _value) public onlyOwner returns (bool){
require (balances[_from] >= _value);
balances[_from] = balances[_from].sub(_value);
balances[CrowdsaleAddress] = balances[CrowdsaleAddress].add(_value);
emit Transfer(_from, CrowdsaleAddress, _value);
return true;
}
function mint(uint256 _amount) public onlyOwner returns (bool){
totalSupply_ = totalSupply_.add(_amount);
balances[CrowdsaleAddress] = balances[CrowdsaleAddress].add(_amount);
emit Mint(CrowdsaleAddress, _amount);
emit Transfer(address(0), CrowdsaleAddress, _amount);
return true;
}
function() external payable {
// The token contract don`t receive ether
revert();
}
}
contract Ownable {
address public owner;
address candidate;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
candidate = newOwner;
}
function confirmOwnership() public {
require(candidate == msg.sender);
owner = candidate;
delete candidate;
}
}
contract Crowdsale is Ownable {
using SafeMath for uint;
address myAddress = this;
uint public saleRate = 30; //tokens for 1 ether
uint public purchaseRate = 30; //tokens for 1 ether
bool public purchaseTokens = false;
event Mint(address indexed to, uint256 amount);
event SaleRates(uint256 indexed value);
event PurchaseRates(uint256 indexed value);
event Withdraw(address indexed from, address indexed to, uint256 amount);
modifier purchaseAlloved() {
// The contract accept tokens
require(purchaseTokens);
_;
}
GoldenUnitToken public token = new GoldenUnitToken(myAddress);
function mintTokens(uint256 _amount) public onlyOwner returns (bool){
//_amount in tokens. 1 = 1 token
uint256 amount = _amount;
require (amount <= 1000000);
amount = amount.mul(1 ether);
token.mint(amount);
return true;
}
function giveTokens(address _newInvestor, uint256 _value) public onlyOwner payable {
// the function give tokens to new investors
// the sum is entered in whole tokens (1 = 1 token)
uint256 value = _value;
require (_newInvestor != address(0));
require (value >= 1);
value = value.mul(1 ether);
token.transfer(_newInvestor, value);
}
function takeTokens(address _Investor, uint256 _value) public onlyOwner payable {
// the function take tokens from users to contract
// the sum is entered in whole tokens (1 = 1 token)
uint256 value = _value;
require (_Investor != address(0));
require (value >= 1);
value = value.mul(1 ether);
token.acceptTokens(_Investor, value);
}
function setSaleRate(uint256 newRate) public onlyOwner {
saleRate = newRate;
emit SaleRates(newRate);
}
function setPurchaseRate(uint256 newRate) public onlyOwner {
purchaseRate = newRate;
emit PurchaseRates(newRate);
}
function startPurchaseTokens() public onlyOwner {
purchaseTokens = true;
}
function stopPurchaseTokens() public onlyOwner {
purchaseTokens = false;
}
function purchase (uint256 _valueTokens) public purchaseAlloved payable {
// function purchase tokens and send ether to sender
address profitOwner = msg.sender;
require(profitOwner != address(0));
require(_valueTokens > 0);
uint256 valueTokens = _valueTokens;
valueTokens = valueTokens.mul(1 ether);
// check client tokens balance
require (token.balanceOf(profitOwner) >= valueTokens);
// calc amount of ether
require (purchaseRate>0);
uint256 valueEther = valueTokens.div(purchaseRate);
// check balance contract
require (myAddress.balance >= valueEther);
// transfer tokens
if (token.acceptTokens(msg.sender, valueTokens)){
// transfer ether
profitOwner.transfer(valueEther);
}
}
function WithdrawProfit (address _to, uint256 _value) public onlyOwner payable {
// function withdraw prohit
require (myAddress.balance >= _value);
require(_to != address(0));
_to.transfer(_value);
emit Withdraw(msg.sender, _to, _value);
}
function saleTokens() internal {
require (msg.value >= 1 ether); //minimum 1 ether
uint tokens = saleRate.mul(msg.value);
token.transfer(msg.sender, tokens);
}
function() external payable {
saleTokens();
}
} | _amount in tokens. 1 = 1 token | function mintTokens(uint256 _amount) public onlyOwner returns (bool){
uint256 amount = _amount;
require (amount <= 1000000);
amount = amount.mul(1 ether);
token.mint(amount);
return true;
}
| 10,591,273 |
./full_match/4/0x03cf51714ace856f8b80d3855Ac46c70E5e90963/sources/contracts/PaymentSplitter.sol | Getter for the amount of shares held by an account./ | function shares(address account) public view returns (uint256) {
return record(account).shares;
}
| 12,386,912 |
./full_match/3/0x6165744662Ec03C05cA19aCb6a398Ec4309e1258/sources/Kyc.sol | Add new bank {bytes32} bankName The name of the bank {address} bankAddress The address of the bankAddress {bytes32} regNumber THe unique registration number of the bank modifier isAdmin validate if only admin is able to make a request returns {bool} Returns true if success, false otherwise/ | function addBank(
bytes32 bankName,
address bankAddress,
bytes32 regNumber
) public isAdmin returns (bool) {
require(
banks[bankAddress].bank != bankAddress,
"Bank with same address already exists"
);
banks[bankAddress].name = bankName;
banks[bankAddress].bank = bankAddress;
banks[bankAddress].rating = 0;
banks[bankAddress].kycCount = 0;
banks[bankAddress].regNumber = regNumber;
bankList.push(bankAddress);
bankToBankVotes[bankAddress].push();
bankToCustomerVotes[bankAddress].push();
return true;
}
| 8,244,810 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../ERC20.sol";
import "./ERC721.sol";
import "../interfaces/Interfaces.sol";
contract EtherOrcsAllies is ERC721 {
uint256 constant startId = 5050;
mapping(uint256 => Ally) public allies;
mapping(address => bool) public auth;
uint16 shSupply;
uint16 ogSupply;
uint16 mgSupply;
uint16 rgSupply;
ERC20 boneShards;
MetadataHandlerAllies metadaHandler;
address public castle;
bool public openForMint;
bytes32 internal entropySauce;
struct Ally {uint8 class; uint16 level; uint32 lvlProgress; uint16 modF; uint8 skillCredits; bytes22 details;}
struct Shaman {uint8 body; uint8 featA; uint8 featB; uint8 helm; uint8 mainhand; uint8 offhand;}
modifier noCheaters() {
uint256 size = 0;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(auth[msg.sender] || (msg.sender == tx.origin && size == 0), "you're trying to cheat!");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
function initialize(address ct, address bs, address meta) external {
require(msg.sender == admin);
castle = ct;
boneShards = ERC20(bs);
metadaHandler = MetadataHandlerAllies(meta);
}
function setAuth(address add_, bool status) external {
require(msg.sender == admin);
auth[add_] = status;
}
function setMintOpen(bool open_) external {
require(msg.sender == admin);
openForMint = open_;
}
function tokenURI(uint256 id) external view returns(string memory) {
Ally memory ally = allies[id];
return metadaHandler.getTokenURI(id, ally.class, ally.level, ally.modF, ally.skillCredits, ally.details);
}
function mintShamans(uint256 amount) external {
for (uint256 i = 0; i < amount; i++) {
mintShaman();
}
}
function mintShaman() public noCheaters {
require(openForMint || auth[msg.sender], "not open for mint");
boneShards.burn(msg.sender, 60 ether);
_mintShaman(_rand());
}
function pull(address owner_, uint256[] calldata ids) external {
require (msg.sender == castle, "not castle");
for (uint256 index = 0; index < ids.length; index++) {
_transfer(owner_, msg.sender, ids[index]);
}
CastleLike(msg.sender).pullCallback(owner_, ids);
}
function adjustAlly(uint256 id, uint8 class_, uint16 level_, uint32 lvlProgress_, uint16 modF_, uint8 skillCredits_, bytes22 details_) external {
require(auth[msg.sender], "not authorized");
allies[id] = Ally({class: class_, level: level_, lvlProgress: lvlProgress_, modF: modF_, skillCredits: skillCredits_, details: details_});
}
function shamans(uint256 id) external view returns(uint16 level, uint32 lvlProgress, uint16 modF, uint8 skillCredits, uint8 body, uint8 featA, uint8 featB, uint8 helm, uint8 mainhand, uint8 offhand) {
Ally memory ally = allies[id];
level = ally.level;
lvlProgress = ally.lvlProgress;
modF = ally.modF;
skillCredits = ally.skillCredits;
Shaman memory sh = _shaman(ally.details);
body = sh.body;
featA = sh.featA;
featB = sh.featB;
helm = sh.helm;
mainhand = sh.mainhand;
offhand = sh.offhand;
}
function _shaman(bytes22 details) internal pure returns(Shaman memory sh) {
uint8 body = uint8(bytes1(details));
uint8 featA = uint8(bytes1(details << 8));
uint8 featB = uint8(bytes1(details << 16));
uint8 helm = uint8(bytes1(details << 24));
uint8 mainhand = uint8(bytes1(details << 32));
uint8 offhand = uint8(bytes1(details << 40));
sh.body = body;
sh.featA = featA;
sh.featB = featB;
sh.helm = helm;
sh.mainhand = mainhand;
sh.offhand = offhand;
}
function _mintShaman(uint256 rand) internal returns (uint16 id) {
id = uint16(shSupply + 1 + startId); //check that supply is less than 3000
require(shSupply++ <= 3000, "max supply reached");
// Getting Random traits
uint8 body = _getBody(_randomize(rand, "BODY", id));
uint8 featB = uint8(_randomize(rand, "featB", id) % 22) + 1;
uint8 featA = uint8(_randomize(rand, "featA", id) % 20) + 1;
uint8 helm = uint8(_randomize(rand, "HELM", id) % 7) + 1;
uint8 mainhand = uint8(_randomize(rand, "MAINHAND", id) % 7) + 1;
uint8 offhand = uint8(_randomize(rand, "OFFHAND", id) % 7) + 1;
_mint(msg.sender, id);
allies[id] = Ally({class: 1, level: 25, lvlProgress: 25000, modF: 0, skillCredits: 100, details: bytes22(abi.encodePacked(body, featA, featB, helm, mainhand, offhand))});
}
function _getBody(uint256 rand) internal pure returns (uint8) {
uint256 sixtyFivePct = type(uint16).max / 100 * 65;
uint256 nineSevenPct = type(uint16).max / 100 * 97;
uint256 nineNinePct = type(uint16).max / 100 * 99;
if (uint16(rand) < sixtyFivePct) return uint8(rand % 5) + 1;
if (uint16(rand) < nineSevenPct) return uint8(rand % 4) + 6;
if (uint16(rand) < nineNinePct) return 10;
return 11;
}
/// @dev Create a bit more of randomness
function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(rand, val, spicy)));
}
function _rand() internal view returns (uint256) {
return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.basefee, block.timestamp, entropySauce)));
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity 0.8.7;
/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// Taken from Solmate: https://github.com/Rari-Capital/solmate
abstract contract ERC20 {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
function name() external view virtual returns (string memory);
function symbol() external view virtual returns (string memory);
function decimals() external view virtual returns (uint8);
// string public constant name = "ZUG";
// string public constant symbol = "ZUG";
// uint8 public constant decimals = 18;
/*///////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
mapping(address => bool) public isMinter;
address public ruler;
/*///////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
constructor() { ruler = msg.sender;}
function approve(address spender, uint256 value) external returns (bool) {
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value) external returns (bool) {
balanceOf[msg.sender] -= value;
// This is safe because the sum of all user
// balances can't exceed type(uint256).max!
unchecked {
balanceOf[to] += value;
}
emit Transfer(msg.sender, to, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool) {
if (allowance[from][msg.sender] != type(uint256).max) {
allowance[from][msg.sender] -= value;
}
balanceOf[from] -= value;
// This is safe because the sum of all user
// balances can't exceed type(uint256).max!
unchecked {
balanceOf[to] += value;
}
emit Transfer(from, to, value);
return true;
}
/*///////////////////////////////////////////////////////////////
ORC PRIVILEGE
//////////////////////////////////////////////////////////////*/
function mint(address to, uint256 value) external {
require(isMinter[msg.sender], "FORBIDDEN TO MINT");
_mint(to, value);
}
function burn(address from, uint256 value) external {
require(isMinter[msg.sender], "FORBIDDEN TO BURN");
_burn(from, value);
}
/*///////////////////////////////////////////////////////////////
Ruler Function
//////////////////////////////////////////////////////////////*/
function setMinter(address minter, bool status) external {
require(msg.sender == ruler, "NOT ALLOWED TO RULE");
isMinter[minter] = status;
}
function setRuler(address ruler_) external {
require(msg.sender == ruler ||ruler == address(0), "NOT ALLOWED TO RULE");
ruler = ruler_;
}
/*///////////////////////////////////////////////////////////////
INTERNAL UTILS
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 value) internal {
totalSupply += value;
// This is safe because the sum of all user
// balances can't exceed type(uint256).max!
unchecked {
balanceOf[to] += value;
}
emit Transfer(address(0), to, value);
}
function _burn(address from, uint256 value) internal {
balanceOf[from] -= value;
// This is safe because a user won't ever
// have a balance larger than totalSupply!
unchecked {
totalSupply -= value;
}
emit Transfer(from, address(0), value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.7;
/// @notice Modern and gas efficient ERC-721 + ERC-20/EIP-2612-like implementation,
/// including the MetaData, and partially, Enumerable extensions.
contract ERC721 {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed spender, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
address implementation_;
address public admin; //Lame requirement from opensea
/*///////////////////////////////////////////////////////////////
ERC-721 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(uint256 => address) public ownerOf;
mapping(uint256 => address) public getApproved;
mapping(address => mapping(address => bool)) public isApprovedForAll;
/*///////////////////////////////////////////////////////////////
VIEW FUNCTION
//////////////////////////////////////////////////////////////*/
function owner() external view returns (address) {
return admin;
}
/*///////////////////////////////////////////////////////////////
ERC-20-LIKE LOGIC
//////////////////////////////////////////////////////////////*/
function transfer(address to, uint256 tokenId) external {
require(msg.sender == ownerOf[tokenId], "NOT_OWNER");
_transfer(msg.sender, to, tokenId);
}
/*///////////////////////////////////////////////////////////////
ERC-721 LOGIC
//////////////////////////////////////////////////////////////*/
function supportsInterface(bytes4 interfaceId) external pure returns (bool supported) {
supported = interfaceId == 0x80ac58cd || interfaceId == 0x5b5e139f;
}
function approve(address spender, uint256 tokenId) external {
address owner_ = ownerOf[tokenId];
require(msg.sender == owner_ || isApprovedForAll[owner_][msg.sender], "NOT_APPROVED");
getApproved[tokenId] = spender;
emit Approval(owner_, spender, tokenId);
}
function setApprovalForAll(address operator, bool approved) external {
isApprovedForAll[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function transferFrom(address from, address to, uint256 tokenId) public {
require(
msg.sender == from
|| msg.sender == getApproved[tokenId]
|| isApprovedForAll[from][msg.sender],
"NOT_APPROVED"
);
_transfer(from, to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId) external {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public {
transferFrom(from, to, tokenId);
if (to.code.length != 0) {
// selector = `onERC721Received(address,address,uint,bytes)`
(, bytes memory returned) = to.staticcall(abi.encodeWithSelector(0x150b7a02,
msg.sender, address(0), tokenId, data));
bytes4 selector = abi.decode(returned, (bytes4));
require(selector == 0x150b7a02, "NOT_ERC721_RECEIVER");
}
}
/*///////////////////////////////////////////////////////////////
INTERNAL UTILS
//////////////////////////////////////////////////////////////*/
function _transfer(address from, address to, uint256 tokenId) internal {
require(ownerOf[tokenId] == from, "not owner");
balanceOf[from]--;
balanceOf[to]++;
delete getApproved[tokenId];
ownerOf[tokenId] = to;
emit Transfer(from, to, tokenId);
}
function _mint(address to, uint256 tokenId) internal {
require(ownerOf[tokenId] == address(0), "ALREADY_MINTED");
totalSupply++;
// This is safe because the sum of all user
// balances can't exceed type(uint256).max!
unchecked {
balanceOf[to]++;
}
ownerOf[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal {
address owner_ = ownerOf[tokenId];
require(ownerOf[tokenId] != address(0), "NOT_MINTED");
totalSupply--;
balanceOf[owner_]--;
delete ownerOf[tokenId];
emit Transfer(owner_, address(0), tokenId);
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity 0.8.7;
interface OrcishLike {
function pull(address owner, uint256[] calldata ids) external;
function manuallyAdjustOrc(uint256 id, uint8 body, uint8 helm, uint8 mainhand, uint8 offhand, uint16 level, uint16 zugModifier, uint32 lvlProgress) external;
function transfer(address to, uint256 tokenId) external;
function orcs(uint256 id) external view returns(uint8 body, uint8 helm, uint8 mainhand, uint8 offhand, uint16 level, uint16 zugModifier, uint32 lvlProgress);
function allies(uint256 id) external view returns (uint8 class, uint16 level, uint32 lvlProgress, uint16 modF, uint8 skillCredits, bytes22 details);
function adjustAlly(uint256 id, uint8 class_, uint16 level_, uint32 lvlProgress_, uint16 modF_, uint8 skillCredits_, bytes22 details_) external;
}
interface PortalLike {
function sendMessage(bytes calldata message_) external;
}
interface OracleLike {
function request() external returns (uint64 key);
function getRandom(uint64 id) external view returns(uint256 rand);
}
interface MetadataHandlerLike {
function getTokenURI(uint16 id, uint8 body, uint8 helm, uint8 mainhand, uint8 offhand, uint16 level, uint16 zugModifier) external view returns (string memory);
}
interface MetadataHandlerAllies {
function getTokenURI(uint256 id_, uint256 class_, uint256 level_, uint256 modF_, uint256 skillCredits_, bytes22 details_) external view returns (string memory);
}
interface RaidsLike {
function stakeManyAndStartCampaign(uint256[] calldata ids_, address owner_, uint256 location_, bool double_) external;
function startCampaignWithMany(uint256[] calldata ids, uint256 location_, bool double_) external;
function commanders(uint256 id) external returns(address);
function unstake(uint256 id) external;
}
interface RaidsLikePoly {
function stakeManyAndStartCampaign(uint256[] calldata ids_, address owner_, uint256 location_, bool double_, uint256[] calldata potions_) external;
function startCampaignWithMany(uint256[] calldata ids, uint256 location_, bool double_, uint256[] calldata potions_) external;
function commanders(uint256 id) external returns(address);
function unstake(uint256 id) external;
}
interface CastleLike {
function pullCallback(address owner, uint256[] calldata ids) external;
}
interface EtherOrcsLike {
function ownerOf(uint256 id) external view returns (address owner_);
function activities(uint256 id) external view returns (address owner, uint88 timestamp, uint8 action);
function orcs(uint256 orcId) external view returns (uint8 body, uint8 helm, uint8 mainhand, uint8 offhand, uint16 level, uint16 zugModifier, uint32 lvlProgress);
}
interface ERC20Like {
function balanceOf(address from) external view returns(uint256 balance);
function burn(address from, uint256 amount) external;
function mint(address from, uint256 amount) external;
function transfer(address to, uint256 amount) external;
}
interface ERC1155Like {
function mint(address to, uint256 id, uint256 amount) external;
function burn(address from, uint256 id, uint256 amount) external;
}
interface ERC721Like {
function transferFrom(address from, address to, uint256 id) external;
function transfer(address to, uint256 id) external;
function ownerOf(uint256 id) external returns (address owner);
function mint(address to, uint256 tokenid) external;
}
interface HallOfChampionsLike {
function joined(uint256 orcId) external view returns (uint256 joinDate);
}
interface AlliesLike {
function allies(uint256 id) external view returns (uint8 class, uint16 level, uint32 lvlProgress, uint16 modF, uint8 skillCredits, bytes22 details);
} | This is safe because the sum of all user balances can't exceed type(uint256).max! | function _mint(address to, uint256 tokenId) internal {
require(ownerOf[tokenId] == address(0), "ALREADY_MINTED");
totalSupply++;
unchecked {
balanceOf[to]++;
}
ownerOf[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
| 617,317 |
./full_match/43114/0x37A83906a69d6236DBcB4d8257D8f62d1f3BBcD5/sources/contracts/BambooStrategyForLP.sol | Withdraws deposit tokens from Staking Contract Reward tokens are automatically collected Reward tokens are not automatically reinvested amount deposit tokens to remove/ | function _withdrawDepositTokens(uint amount) internal {
require(amount > 0, "amount too low");
stakingContract.withdraw(PID, amount);
}
| 4,536,116 |
pragma solidity ^0.4.24;
import "./ITransferManager.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../../libraries/BokkyPooBahsDateTimeLibrary.sol";
import "../../libraries/VolumeRestrictionLib.sol";
contract VolumeRestrictionTM is VolumeRestrictionTMStorage, ITransferManager {
using SafeMath for uint256;
// permission definition
bytes32 internal constant ADMIN = "ADMIN";
// Emit when the token holder is added/removed from the exemption list
event ChangedExemptWalletList(address indexed _wallet, bool _change);
// Emit when the new individual restriction is added corresponds to new token holders
event AddIndividualRestriction(
address indexed _holder,
uint256 _allowedTokens,
uint256 _startTime,
uint256 _rollingPeriodInDays,
uint256 _endTime,
RestrictionType _typeOfRestriction
);
// Emit when the new daily (Individual) restriction is added
event AddIndividualDailyRestriction(
address indexed _holder,
uint256 _allowedTokens,
uint256 _startTime,
uint256 _rollingPeriodInDays,
uint256 _endTime,
RestrictionType _typeOfRestriction
);
// Emit when the individual restriction is modified for a given address
event ModifyIndividualRestriction(
address indexed _holder,
uint256 _allowedTokens,
uint256 _startTime,
uint256 _rollingPeriodInDays,
uint256 _endTime,
RestrictionType _typeOfRestriction
);
// Emit when individual daily restriction get modified
event ModifyIndividualDailyRestriction(
address indexed _holder,
uint256 _allowedTokens,
uint256 _startTime,
uint256 _rollingPeriodInDays,
uint256 _endTime,
RestrictionType _typeOfRestriction
);
// Emit when the new global restriction is added
event AddDefaultRestriction(
uint256 _allowedTokens,
uint256 _startTime,
uint256 _rollingPeriodInDays,
uint256 _endTime,
RestrictionType _typeOfRestriction
);
// Emit when the new daily (Default) restriction is added
event AddDefaultDailyRestriction(
uint256 _allowedTokens,
uint256 _startTime,
uint256 _rollingPeriodInDays,
uint256 _endTime,
RestrictionType _typeOfRestriction
);
// Emit when default restriction get modified
event ModifyDefaultRestriction(
uint256 _allowedTokens,
uint256 _startTime,
uint256 _rollingPeriodInDays,
uint256 _endTime,
RestrictionType _typeOfRestriction
);
// Emit when daily default restriction get modified
event ModifyDefaultDailyRestriction(
uint256 _allowedTokens,
uint256 _startTime,
uint256 _rollingPeriodInDays,
uint256 _endTime,
RestrictionType _typeOfRestriction
);
// Emit when the individual restriction gets removed
event IndividualRestrictionRemoved(address indexed _holder);
// Emit when individual daily restriction removed
event IndividualDailyRestrictionRemoved(address indexed _holder);
// Emit when the default restriction gets removed
event DefaultRestrictionRemoved();
// Emit when the daily default restriction gets removed
event DefaultDailyRestrictionRemoved();
/**
* @notice Constructor
* @param _securityToken Address of the security token
* @param _polyAddress Address of the polytoken
*/
constructor (address _securityToken, address _polyAddress)
public
Module(_securityToken, _polyAddress)
{
}
/**
* @notice Used to verify the transfer/transferFrom transaction and prevent tranaction
* whose volume of tokens will voilate the maximum volume transfer restriction
* @param _from Address of the sender
* @param _amount The amount of tokens to transfer
* @param _isTransfer Whether or not this is an actual transfer or just a test to see if the tokens would be transferrable
*/
function verifyTransfer(address _from, address /*_to */, uint256 _amount, bytes /*_data*/, bool _isTransfer) public returns (Result) {
// If `_from` is present in the exemptionList or it is `0x0` address then it will not follow the vol restriction
if (!paused && _from != address(0) && exemptIndex[_from] == 0) {
// Function must only be called by the associated security token if _isTransfer == true
require(msg.sender == securityToken || !_isTransfer);
// Checking the individual restriction if the `_from` comes in the individual category
if ((individualRestriction[_from].endTime >= now && individualRestriction[_from].startTime <= now)
|| (individualDailyRestriction[_from].endTime >= now && individualDailyRestriction[_from].startTime <= now)) {
return _restrictionCheck(_isTransfer, _from, _amount, userToBucket[_from], individualRestriction[_from], false);
// If the `_from` doesn't fall under the individual category. It will processed with in the global category automatically
} else if ((defaultRestriction.endTime >= now && defaultRestriction.startTime <= now)
|| (defaultDailyRestriction.endTime >= now && defaultDailyRestriction.startTime <= now)) {
return _restrictionCheck(_isTransfer, _from, _amount, defaultUserToBucket[_from], defaultRestriction, true);
}
}
return Result.NA;
}
/**
* @notice Add/Remove wallet address from the exempt list
* @param _wallet Ethereum wallet/contract address that need to be exempted
* @param _change Boolean value used to add (i.e true) or remove (i.e false) from the list
*/
function changeExemptWalletList(address _wallet, bool _change) external withPerm(ADMIN) {
require(_wallet != address(0));
uint256 exemptIndexWallet = exemptIndex[_wallet];
require((exemptIndexWallet == 0) == _change);
if (_change) {
exemptAddresses.push(_wallet);
exemptIndex[_wallet] = exemptAddresses.length;
} else {
exemptAddresses[exemptIndexWallet - 1] = exemptAddresses[exemptAddresses.length - 1];
exemptIndex[exemptAddresses[exemptIndexWallet - 1]] = exemptIndexWallet;
delete exemptIndex[_wallet];
exemptAddresses.length --;
}
emit ChangedExemptWalletList(_wallet, _change);
}
/**
* @notice Use to add the new individual restriction for a given token holder
* @param _holder Address of the token holder, whom restriction will be implied
* @param _allowedTokens Amount of tokens allowed to be trade for a given address.
* @param _startTime Unix timestamp at which restriction get into effect
* @param _rollingPeriodInDays Rolling period in days (Minimum value should be 1 day)
* @param _endTime Unix timestamp at which restriction effects will gets end.
* @param _restrictionType Whether it will be `Fixed` (fixed no. of tokens allowed to transact)
* or `Percentage` (tokens are calculated as per the totalSupply in the fly).
*/
function addIndividualRestriction(
address _holder,
uint256 _allowedTokens,
uint256 _startTime,
uint256 _rollingPeriodInDays,
uint256 _endTime,
RestrictionType _restrictionType
)
external
withPerm(ADMIN)
{
_addIndividualRestriction(
_holder,
_allowedTokens,
_startTime,
_rollingPeriodInDays,
_endTime,
_restrictionType
);
}
/// @notice Internal function to facilitate the addition of individual restriction
function _addIndividualRestriction(
address _holder,
uint256 _allowedTokens,
uint256 _startTime,
uint256 _rollingPeriodInDays,
uint256 _endTime,
RestrictionType _restrictionType
)
internal
{
// It will help to reduce the chances of transaction failure (Specially when the issuer
// wants to set the startTime near to the current block.timestamp) and minting delayed because
// of the gas fee or network congestion that lead to the process block timestamp may grater
// than the given startTime.
uint256 startTime = _getValidStartTime(_startTime);
require(_holder != address(0) && exemptIndex[_holder] == 0, "Invalid address");
_checkInputParams(_allowedTokens, startTime, _rollingPeriodInDays, _endTime, _restrictionType, now, false);
if (individualRestriction[_holder].endTime != 0) {
_removeIndividualRestriction(_holder);
}
individualRestriction[_holder] = VolumeRestriction(
_allowedTokens,
startTime,
_rollingPeriodInDays,
_endTime,
_restrictionType
);
VolumeRestrictionLib.addRestrictionData(holderData, _holder, TypeOfPeriod.MultipleDays, individualRestriction[_holder].endTime);
emit AddIndividualRestriction(
_holder,
_allowedTokens,
startTime,
_rollingPeriodInDays,
_endTime,
_restrictionType
);
}
/**
* @notice Use to add the new individual daily restriction for a given token holder
* @param _holder Address of the token holder, whom restriction will be implied
* @param _allowedTokens Amount of tokens allowed to be traded for all token holder.
* @param _startTime Unix timestamp at which restriction get into effect
* @param _endTime Unix timestamp at which restriction effects will gets end.
* @param _restrictionType Whether it will be `Fixed` (fixed no. of tokens allowed to transact)
* or `Percentage` (tokens are calculated as per the totalSupply in the fly).
*/
function addIndividualDailyRestriction(
address _holder,
uint256 _allowedTokens,
uint256 _startTime,
uint256 _endTime,
RestrictionType _restrictionType
)
external
withPerm(ADMIN)
{
_addIndividualDailyRestriction(
_holder,
_allowedTokens,
_startTime,
_endTime,
_restrictionType
);
}
/// @notice Internal function to facilitate the addition of individual daily restriction
function _addIndividualDailyRestriction(
address _holder,
uint256 _allowedTokens,
uint256 _startTime,
uint256 _endTime,
RestrictionType _restrictionType
)
internal
{
uint256 startTime = _getValidStartTime(_startTime);
_checkInputParams(_allowedTokens, startTime, 1, _endTime, _restrictionType, now, false);
if (individualDailyRestriction[_holder].endTime != 0) {
_removeIndividualDailyRestriction(_holder);
}
individualDailyRestriction[_holder] = VolumeRestriction(
_allowedTokens,
startTime,
1,
_endTime,
_restrictionType
);
VolumeRestrictionLib.addRestrictionData(holderData, _holder, TypeOfPeriod.OneDay, individualRestriction[_holder].endTime);
emit AddIndividualDailyRestriction(
_holder,
_allowedTokens,
startTime,
1,
_endTime,
_restrictionType
);
}
/**
* @notice Use to add the new individual daily restriction for multiple token holders
* @param _holders Array of address of the token holders, whom restriction will be implied
* @param _allowedTokens Array of amount of tokens allowed to be trade for a given address.
* @param _startTimes Array of unix timestamps at which restrictions get into effect
* @param _endTimes Array of unix timestamps at which restriction effects will gets end.
* @param _restrictionTypes Array of restriction types value whether it will be `Fixed` (fixed no. of tokens allowed to transact)
* or `Percentage` (tokens are calculated as per the totalSupply in the fly).
*/
function addIndividualDailyRestrictionMulti(
address[] _holders,
uint256[] _allowedTokens,
uint256[] _startTimes,
uint256[] _endTimes,
RestrictionType[] _restrictionTypes
)
public //Marked public to save code size
withPerm(ADMIN)
{
//NB - we duplicate _startTimes below to allow function reuse
_checkLengthOfArray(_holders, _allowedTokens, _startTimes, _startTimes, _endTimes, _restrictionTypes);
for (uint256 i = 0; i < _holders.length; i++) {
_addIndividualDailyRestriction(
_holders[i],
_allowedTokens[i],
_startTimes[i],
_endTimes[i],
_restrictionTypes[i]
);
}
}
/**
* @notice Use to add the new individual restriction for multiple token holders
* @param _holders Array of address of the token holders, whom restriction will be implied
* @param _allowedTokens Array of amount of tokens allowed to be trade for a given address.
* @param _startTimes Array of unix timestamps at which restrictions get into effect
* @param _rollingPeriodInDays Array of rolling period in days (Minimum value should be 1 day)
* @param _endTimes Array of unix timestamps at which restriction effects will gets end.
* @param _restrictionTypes Array of restriction types value whether it will be `Fixed` (fixed no. of tokens allowed to transact)
* or `Percentage` (tokens are calculated as per the totalSupply in the fly).
*/
function addIndividualRestrictionMulti(
address[] _holders,
uint256[] _allowedTokens,
uint256[] _startTimes,
uint256[] _rollingPeriodInDays,
uint256[] _endTimes,
RestrictionType[] _restrictionTypes
)
public //Marked public to save code size
withPerm(ADMIN)
{
_checkLengthOfArray(_holders, _allowedTokens, _startTimes, _rollingPeriodInDays, _endTimes, _restrictionTypes);
for (uint256 i = 0; i < _holders.length; i++) {
_addIndividualRestriction(
_holders[i],
_allowedTokens[i],
_startTimes[i],
_rollingPeriodInDays[i],
_endTimes[i],
_restrictionTypes[i]
);
}
}
/**
* @notice Use to add the new default restriction for all token holder
* @param _allowedTokens Amount of tokens allowed to be traded for all token holder.
* @param _startTime Unix timestamp at which restriction get into effect
* @param _rollingPeriodInDays Rolling period in days (Minimum value should be 1 day)
* @param _endTime Unix timestamp at which restriction effects will gets end.
* @param _restrictionType Whether it will be `Fixed` (fixed no. of tokens allowed to transact)
* or `Percentage` (tokens are calculated as per the totalSupply in the fly).
*/
function addDefaultRestriction(
uint256 _allowedTokens,
uint256 _startTime,
uint256 _rollingPeriodInDays,
uint256 _endTime,
RestrictionType _restrictionType
)
public //Marked public to save code size
withPerm(ADMIN)
{
uint256 startTime = _getValidStartTime(_startTime);
_checkInputParams(_allowedTokens, startTime, _rollingPeriodInDays, _endTime, _restrictionType, now, false);
defaultRestriction = VolumeRestriction(
_allowedTokens,
startTime,
_rollingPeriodInDays,
_endTime,
_restrictionType
);
emit AddDefaultRestriction(
_allowedTokens,
startTime,
_rollingPeriodInDays,
_endTime,
_restrictionType
);
}
/**
* @notice Use to add the new default daily restriction for all token holder
* @param _allowedTokens Amount of tokens allowed to be traded for all token holder.
* @param _startTime Unix timestamp at which restriction get into effect
* @param _endTime Unix timestamp at which restriction effects will gets end.
* @param _restrictionType Whether it will be `Fixed` (fixed no. of tokens allowed to transact)
* or `Percentage` (tokens are calculated as per the totalSupply in the fly).
*/
function addDefaultDailyRestriction(
uint256 _allowedTokens,
uint256 _startTime,
uint256 _endTime,
RestrictionType _restrictionType
)
public //Marked public to save code size
withPerm(ADMIN)
{
uint256 startTime = _getValidStartTime(_startTime);
_checkInputParams(_allowedTokens, startTime, 1, _endTime, _restrictionType, now, false);
defaultDailyRestriction = VolumeRestriction(
_allowedTokens,
startTime,
1,
_endTime,
_restrictionType
);
emit AddDefaultDailyRestriction(
_allowedTokens,
startTime,
1,
_endTime,
_restrictionType
);
}
/**
* @notice use to remove the individual restriction for a given address
* @param _holder Address of the user
*/
function removeIndividualRestriction(address _holder) external withPerm(ADMIN) {
_removeIndividualRestriction(_holder);
}
/// @notice Internal function to facilitate the removal of individual restriction
function _removeIndividualRestriction(address _holder) internal {
require(_holder != address(0));
require(individualRestriction[_holder].endTime != 0);
individualRestriction[_holder] = VolumeRestriction(0, 0, 0, 0, RestrictionType(0));
VolumeRestrictionLib.deleteHolderFromList(holderData, _holder, TypeOfPeriod.OneDay);
userToBucket[_holder].lastTradedDayTime = 0;
userToBucket[_holder].sumOfLastPeriod = 0;
userToBucket[_holder].daysCovered = 0;
emit IndividualRestrictionRemoved(_holder);
}
/**
* @notice use to remove the individual restriction for a given address
* @param _holders Array of address of the user
*/
function removeIndividualRestrictionMulti(address[] _holders) external withPerm(ADMIN) {
for (uint256 i = 0; i < _holders.length; i++) {
_removeIndividualRestriction(_holders[i]);
}
}
/**
* @notice use to remove the individual daily restriction for a given address
* @param _holder Address of the user
*/
function removeIndividualDailyRestriction(address _holder) external withPerm(ADMIN) {
_removeIndividualDailyRestriction(_holder);
}
/// @notice Internal function to facilitate the removal of individual daily restriction
function _removeIndividualDailyRestriction(address _holder) internal {
require(_holder != address(0));
require(individualDailyRestriction[_holder].endTime != 0);
individualDailyRestriction[_holder] = VolumeRestriction(0, 0, 0, 0, RestrictionType(0));
VolumeRestrictionLib.deleteHolderFromList(holderData, _holder, TypeOfPeriod.MultipleDays);
userToBucket[_holder].dailyLastTradedDayTime = 0;
emit IndividualDailyRestrictionRemoved(_holder);
}
/**
* @notice use to remove the individual daily restriction for a given address
* @param _holders Array of address of the user
*/
function removeIndividualDailyRestrictionMulti(address[] _holders) external withPerm(ADMIN) {
for (uint256 i = 0; i < _holders.length; i++) {
_removeIndividualDailyRestriction(_holders[i]);
}
}
/**
* @notice Use to remove the default restriction
*/
function removeDefaultRestriction() external withPerm(ADMIN) {
require(defaultRestriction.endTime != 0);
defaultRestriction = VolumeRestriction(0, 0, 0, 0, RestrictionType(0));
emit DefaultRestrictionRemoved();
}
/**
* @notice Use to remove the daily default restriction
*/
function removeDefaultDailyRestriction() external withPerm(ADMIN) {
require(defaultDailyRestriction.endTime != 0);
defaultDailyRestriction = VolumeRestriction(0, 0, 0, 0, RestrictionType(0));
emit DefaultDailyRestrictionRemoved();
}
/**
* @notice Use to modify the existing individual restriction for a given token holder
* @param _holder Address of the token holder, whom restriction will be implied
* @param _allowedTokens Amount of tokens allowed to be trade for a given address.
* @param _startTime Unix timestamp at which restriction get into effect
* @param _rollingPeriodInDays Rolling period in days (Minimum value should be 1 day)
* @param _endTime Unix timestamp at which restriction effects will gets end.
* @param _restrictionType Whether it will be `Fixed` (fixed no. of tokens allowed to transact)
* or `Percentage` (tokens are calculated as per the totalSupply in the fly).
*/
function modifyIndividualRestriction(
address _holder,
uint256 _allowedTokens,
uint256 _startTime,
uint256 _rollingPeriodInDays,
uint256 _endTime,
RestrictionType _restrictionType
)
external
withPerm(ADMIN)
{
_modifyIndividualRestriction(
_holder,
_allowedTokens,
_startTime,
_rollingPeriodInDays,
_endTime,
_restrictionType
);
}
/// @notice Internal function to facilitate the modification of individual restriction
function _modifyIndividualRestriction(
address _holder,
uint256 _allowedTokens,
uint256 _startTime,
uint256 _rollingPeriodInDays,
uint256 _endTime,
RestrictionType _restrictionType
)
internal
{
_isAllowedToModify(individualRestriction[_holder].startTime);
uint256 startTime = _getValidStartTime(_startTime);
_checkInputParams(_allowedTokens, startTime, _rollingPeriodInDays, _endTime, _restrictionType, now, false);
individualRestriction[_holder] = VolumeRestriction(
_allowedTokens,
startTime,
_rollingPeriodInDays,
_endTime,
_restrictionType
);
emit ModifyIndividualRestriction(
_holder,
_allowedTokens,
startTime,
_rollingPeriodInDays,
_endTime,
_restrictionType
);
}
/**
* @notice Use to modify the existing individual daily restriction for a given token holder
* @dev Changing of startTime will affect the 24 hrs span. i.e if in earlier restriction days start with
* morning and end on midnight while after the change day may start with afternoon and end with other day afternoon
* @param _holder Address of the token holder, whom restriction will be implied
* @param _allowedTokens Amount of tokens allowed to be trade for a given address.
* @param _startTime Unix timestamp at which restriction get into effect
* @param _endTime Unix timestamp at which restriction effects will gets end.
* @param _restrictionType Whether it will be `Fixed` (fixed no. of tokens allowed to transact)
* or `Percentage` (tokens are calculated as per the totalSupply in the fly).
*/
function modifyIndividualDailyRestriction(
address _holder,
uint256 _allowedTokens,
uint256 _startTime,
uint256 _endTime,
RestrictionType _restrictionType
)
external
withPerm(ADMIN)
{
_modifyIndividualDailyRestriction(
_holder,
_allowedTokens,
_startTime,
_endTime,
_restrictionType
);
}
/// @notice Internal function to facilitate the modification of individual daily restriction
function _modifyIndividualDailyRestriction(
address _holder,
uint256 _allowedTokens,
uint256 _startTime,
uint256 _endTime,
RestrictionType _restrictionType
)
internal
{
uint256 startTime = _getValidStartTime(_startTime);
_checkInputParams(_allowedTokens, startTime, 1, _endTime, _restrictionType,
(individualDailyRestriction[_holder].startTime <= now ? individualDailyRestriction[_holder].startTime : now),
true
);
individualDailyRestriction[_holder] = VolumeRestriction(
_allowedTokens,
startTime,
1,
_endTime,
_restrictionType
);
emit ModifyIndividualDailyRestriction(
_holder,
_allowedTokens,
startTime,
1,
_endTime,
_restrictionType
);
}
/**
* @notice Use to modify the existing individual daily restriction for multiple token holders
* @param _holders Array of address of the token holders, whom restriction will be implied
* @param _allowedTokens Array of amount of tokens allowed to be trade for a given address.
* @param _startTimes Array of unix timestamps at which restrictions get into effect
* @param _endTimes Array of unix timestamps at which restriction effects will gets end.
* @param _restrictionTypes Array of restriction types value whether it will be `Fixed` (fixed no. of tokens allowed to transact)
* or `Percentage` (tokens are calculated as per the totalSupply in the fly).
*/
function modifyIndividualDailyRestrictionMulti(
address[] _holders,
uint256[] _allowedTokens,
uint256[] _startTimes,
uint256[] _endTimes,
RestrictionType[] _restrictionTypes
)
public //Marked public to save code size
withPerm(ADMIN)
{
//NB - we duplicate _startTimes below to allow function reuse
_checkLengthOfArray(_holders, _allowedTokens, _startTimes, _startTimes, _endTimes, _restrictionTypes);
for (uint256 i = 0; i < _holders.length; i++) {
_modifyIndividualDailyRestriction(
_holders[i],
_allowedTokens[i],
_startTimes[i],
_endTimes[i],
_restrictionTypes[i]
);
}
}
/**
* @notice Use to modify the existing individual restriction for multiple token holders
* @param _holders Array of address of the token holders, whom restriction will be implied
* @param _allowedTokens Array of amount of tokens allowed to be trade for a given address.
* @param _startTimes Array of unix timestamps at which restrictions get into effect
* @param _rollingPeriodInDays Array of rolling period in days (Minimum value should be 1 day)
* @param _endTimes Array of unix timestamps at which restriction effects will gets end.
* @param _restrictionTypes Array of restriction types value whether it will be `Fixed` (fixed no. of tokens allowed to transact)
* or `Percentage` (tokens are calculated as per the totalSupply in the fly).
*/
function modifyIndividualRestrictionMulti(
address[] _holders,
uint256[] _allowedTokens,
uint256[] _startTimes,
uint256[] _rollingPeriodInDays,
uint256[] _endTimes,
RestrictionType[] _restrictionTypes
)
public //Marked public to save code size
withPerm(ADMIN)
{
_checkLengthOfArray(_holders, _allowedTokens, _startTimes, _rollingPeriodInDays, _endTimes, _restrictionTypes);
for (uint256 i = 0; i < _holders.length; i++) {
_modifyIndividualRestriction(
_holders[i],
_allowedTokens[i],
_startTimes[i],
_rollingPeriodInDays[i],
_endTimes[i],
_restrictionTypes[i]
);
}
}
/**
* @notice Use to modify the global restriction for all token holder
* @param _allowedTokens Amount of tokens allowed to be traded for all token holder.
* @param _startTime Unix timestamp at which restriction get into effect
* @param _rollingPeriodInDays Rolling period in days (Minimum value should be 1 day)
* @param _endTime Unix timestamp at which restriction effects will gets end.
* @param _restrictionType Whether it will be `Fixed` (fixed no. of tokens allowed to transact)
* or `Percentage` (tokens are calculated as per the totalSupply in the fly).
*/
function modifyDefaultRestriction(
uint256 _allowedTokens,
uint256 _startTime,
uint256 _rollingPeriodInDays,
uint256 _endTime,
RestrictionType _restrictionType
)
public //Marked public to save code size
withPerm(ADMIN)
{
_isAllowedToModify(defaultRestriction.startTime);
uint256 startTime = _getValidStartTime(_startTime);
_checkInputParams(_allowedTokens, startTime, _rollingPeriodInDays, _endTime, _restrictionType, now, false);
defaultRestriction = VolumeRestriction(
_allowedTokens,
startTime,
_rollingPeriodInDays,
_endTime,
_restrictionType
);
emit ModifyDefaultRestriction(
_allowedTokens,
startTime,
_rollingPeriodInDays,
_endTime,
_restrictionType
);
}
/**
* @notice Use to modify the daily default restriction for all token holder
* @dev Changing of startTime will affect the 24 hrs span. i.e if in earlier restriction days start with
* morning and end on midnight while after the change day may start with afternoon and end with other day afternoon.
* @param _allowedTokens Amount of tokens allowed to be traded for all token holder.
* @param _startTime Unix timestamp at which restriction get into effect
* @param _endTime Unix timestamp at which restriction effects will gets end.
* @param _restrictionType Whether it will be `Fixed` (fixed no. of tokens allowed to transact)
* or `Percentage` (tokens are calculated as per the totalSupply in the fly).
*/
function modifyDefaultDailyRestriction(
uint256 _allowedTokens,
uint256 _startTime,
uint256 _endTime,
RestrictionType _restrictionType
)
public //Marked public to save code size
withPerm(ADMIN)
{
uint256 startTime = _getValidStartTime(_startTime);
// If old startTime is already passed then new startTime should be greater than or equal to the
// old startTime otherwise any past startTime can be allowed in compare to earlier startTime.
_checkInputParams(_allowedTokens, startTime, 1, _endTime, _restrictionType,
(defaultDailyRestriction.startTime <= now ? defaultDailyRestriction.startTime : now),
true
);
defaultDailyRestriction = VolumeRestriction(
_allowedTokens,
startTime,
1,
_endTime,
_restrictionType
);
emit ModifyDefaultDailyRestriction(
_allowedTokens,
startTime,
1,
_endTime,
_restrictionType
);
}
/**
* @notice Internal function used to validate the transaction for a given address
* If it validates then it also update the storage corressponds to the default restriction
*/
function _restrictionCheck(
bool _isTransfer,
address _from,
uint256 _amount,
BucketDetails memory _bucketDetails,
VolumeRestriction memory _restriction,
bool _isDefault
)
internal
returns (Result)
{
// using the variable to avoid stack too deep error
VolumeRestriction memory dailyRestriction = _isDefault ? defaultDailyRestriction :individualDailyRestriction[_from];
uint256 daysCovered = _restriction.rollingPeriodInDays;
uint256 fromTimestamp = 0;
uint256 sumOfLastPeriod = 0;
uint256 dailyTime = 0;
// This variable works for both allowedDefault or allowedIndividual
bool allowedDefault = true;
bool allowedDaily;
if (_restriction.endTime >= now && _restriction.startTime <= now) {
if (_bucketDetails.lastTradedDayTime < _restriction.startTime) {
// It will execute when the txn is performed first time after the addition of individual restriction
fromTimestamp = _restriction.startTime;
} else {
// Picking up the last timestamp
fromTimestamp = _bucketDetails.lastTradedDayTime;
}
// Check with the bucket and parse all the new timestamps to calculate the sumOfLastPeriod
// re-using the local variables to avoid the stack too deep error.
(sumOfLastPeriod, fromTimestamp, daysCovered) = _bucketCheck(
fromTimestamp,
BokkyPooBahsDateTimeLibrary.diffDays(fromTimestamp, now),
_from,
daysCovered,
_bucketDetails,
_isDefault
);
// validation of the transaction amount
if (
!_checkValidAmountToTransact(
_isDefault, _from, sumOfLastPeriod, _amount, _restriction.typeOfRestriction, _restriction.allowedTokens
)
) {
allowedDefault = false;
}
}
(allowedDaily, dailyTime) = _dailyTxCheck(_from, _amount, _bucketDetails.dailyLastTradedDayTime, dailyRestriction, _isDefault);
if (_isTransfer) {
_updateStorage(
_from,
_amount,
fromTimestamp,
sumOfLastPeriod,
daysCovered,
dailyTime,
_isDefault
);
}
return ((allowedDaily && allowedDefault) == true ? Result.NA : Result.INVALID);
}
/**
* @notice The function is used to check specific edge case where the user restriction type change from
* default to individual or vice versa. It will return true when last transaction traded by the user
* and the current txn timestamp lies in the same day.
* NB - Instead of comparing the current day transaction amount, we are comparing the total amount traded
* on the lastTradedDayTime that makes the restriction strict. The reason is not availability of amount
* that transacted on the current day (because of bucket desgin).
*/
function _isValidAmountAfterRestrictionChanges(
bool _isDefault,
address _from,
uint256 _amount,
uint256 _sumOfLastPeriod,
uint256 _allowedAmount
)
internal
view
returns(bool)
{
// Always use the alternate bucket details as per the current transaction restriction
BucketDetails storage bucketDetails = _isDefault ? userToBucket[_from] : defaultUserToBucket[_from];
uint256 amountTradedLastDay = _isDefault ? bucket[_from][bucketDetails.lastTradedDayTime]: defaultBucket[_from][bucketDetails.lastTradedDayTime];
return VolumeRestrictionLib.isValidAmountAfterRestrictionChanges(
amountTradedLastDay,
_amount,
_sumOfLastPeriod,
_allowedAmount,
bucketDetails.lastTradedTimestamp
);
}
function _checkValidAmountToTransact(
bool _isDefault,
address _from,
uint256 _sumOfLastPeriod,
uint256 _amountToTransact,
RestrictionType _typeOfRestriction,
uint256 _allowedTokens
)
internal
view
returns (bool)
{
uint256 allowedAmount;
if (_typeOfRestriction == RestrictionType.Percentage) {
allowedAmount = (_allowedTokens.mul(ISecurityToken(securityToken).totalSupply())) / uint256(10) ** 18;
} else {
allowedAmount = _allowedTokens;
}
// Validation on the amount to transact
bool allowed = allowedAmount >= _sumOfLastPeriod.add(_amountToTransact);
return (allowed && _isValidAmountAfterRestrictionChanges(_isDefault, _from, _amountToTransact, _sumOfLastPeriod, allowedAmount));
}
function _dailyTxCheck(
address _from,
uint256 _amount,
uint256 _dailyLastTradedDayTime,
VolumeRestriction memory _restriction,
bool _isDefault
)
internal
view
returns(bool, uint256)
{
// Checking whether the daily restriction is added or not if yes then calculate
// the total amount get traded on a particular day (~ _fromTime)
if ( now <= _restriction.endTime && now >= _restriction.startTime) {
uint256 txSumOfDay = 0;
// This if condition will be executed when the individual daily restriction executed first time
if (_dailyLastTradedDayTime == 0 || _dailyLastTradedDayTime < _restriction.startTime)
_dailyLastTradedDayTime = _restriction.startTime.add(BokkyPooBahsDateTimeLibrary.diffDays(_restriction.startTime, now).mul(1 days));
else if (now.sub(_dailyLastTradedDayTime) >= 1 days)
_dailyLastTradedDayTime = _dailyLastTradedDayTime.add(BokkyPooBahsDateTimeLibrary.diffDays(_dailyLastTradedDayTime, now).mul(1 days));
// Assgining total sum traded on dailyLastTradedDayTime timestamp
if (_isDefault)
txSumOfDay = defaultBucket[_from][_dailyLastTradedDayTime];
else
txSumOfDay = bucket[_from][_dailyLastTradedDayTime];
return (
_checkValidAmountToTransact(
_isDefault,
_from,
txSumOfDay,
_amount,
_restriction.typeOfRestriction,
_restriction.allowedTokens
),
_dailyLastTradedDayTime
);
}
return (true, _dailyLastTradedDayTime);
}
/// Internal function for the bucket check
function _bucketCheck(
uint256 _fromTime,
uint256 _diffDays,
address _from,
uint256 _rollingPeriodInDays,
BucketDetails memory _bucketDetails,
bool isDefault
)
internal
view
returns (uint256, uint256, uint256)
{
uint256 counter = _bucketDetails.daysCovered;
uint256 sumOfLastPeriod = _bucketDetails.sumOfLastPeriod;
uint256 i = 0;
if (_diffDays >= _rollingPeriodInDays) {
// If the difference of days is greater than the rollingPeriod then sumOfLastPeriod will always be zero
sumOfLastPeriod = 0;
counter = counter.add(_diffDays);
} else {
for (i = 0; i < _diffDays; i++) {
counter++;
// This condition is to check whether the first rolling period is covered or not
// if not then it continues and adding 0 value into sumOfLastPeriod without subtracting
// the earlier value at that index
if (counter >= _rollingPeriodInDays) {
// Subtracting the former value(Sum of all the txn amount of that day) from the sumOfLastPeriod
// The below line subtracts (the traded volume on days no longer covered by rolling period) from sumOfLastPeriod.
// Every loop execution subtracts one day's trade volume.
// Loop starts from the first day covered in sumOfLastPeriod upto the day that is covered by rolling period.
uint256 temp = _bucketDetails.daysCovered.sub(counter.sub(_rollingPeriodInDays));
temp = _bucketDetails.lastTradedDayTime.sub(temp.mul(1 days));
if (isDefault)
sumOfLastPeriod = sumOfLastPeriod.sub(defaultBucket[_from][temp]);
else
sumOfLastPeriod = sumOfLastPeriod.sub(bucket[_from][temp]);
}
// Adding the last amount that is transacted on the `_fromTime` not actually doing it but left written to understand
// the alogrithm
//_bucketDetails.sumOfLastPeriod = _bucketDetails.sumOfLastPeriod.add(uint256(0));
}
}
// calculating the timestamp that will used as an index of the next bucket
// i.e buckets period will be look like this T1 to T2-1, T2 to T3-1 ....
// where T1,T2,T3 are timestamps having 24 hrs difference
_fromTime = _fromTime.add(_diffDays.mul(1 days));
return (sumOfLastPeriod, _fromTime, counter);
}
function _updateStorage(
address _from,
uint256 _amount,
uint256 _lastTradedDayTime,
uint256 _sumOfLastPeriod,
uint256 _daysCovered,
uint256 _dailyLastTradedDayTime,
bool isDefault
)
internal
{
if (isDefault){
BucketDetails storage defaultUserToBucketDetails = defaultUserToBucket[_from];
_updateStorageActual(_from, _amount, _lastTradedDayTime, _sumOfLastPeriod, _daysCovered, _dailyLastTradedDayTime, defaultDailyRestriction.endTime, true, defaultUserToBucketDetails);
}
else {
BucketDetails storage userToBucketDetails = userToBucket[_from];
uint256 _endTime = individualDailyRestriction[_from].endTime;
_updateStorageActual(_from, _amount, _lastTradedDayTime, _sumOfLastPeriod, _daysCovered, _dailyLastTradedDayTime, _endTime, false, userToBucketDetails);
}
}
function _updateStorageActual(
address _from,
uint256 _amount,
uint256 _lastTradedDayTime,
uint256 _sumOfLastPeriod,
uint256 _daysCovered,
uint256 _dailyLastTradedDayTime,
uint256 _endTime,
bool isDefault,
BucketDetails storage details
)
internal
{
// Cheap storage technique
if (details.lastTradedDayTime != _lastTradedDayTime) {
// Assigning the latest transaction timestamp of the day
details.lastTradedDayTime = _lastTradedDayTime;
}
if (details.dailyLastTradedDayTime != _dailyLastTradedDayTime) {
// Assigning the latest transaction timestamp of the day
details.dailyLastTradedDayTime = _dailyLastTradedDayTime;
}
if (details.daysCovered != _daysCovered) {
details.daysCovered = _daysCovered;
}
// Assigning the latest transaction timestamp
details.lastTradedTimestamp = now;
if (_amount != 0) {
if (_lastTradedDayTime !=0) {
details.sumOfLastPeriod = _sumOfLastPeriod.add(_amount);
// Increasing the total amount of the day by `_amount`
if (isDefault)
defaultBucket[_from][_lastTradedDayTime] = defaultBucket[_from][_lastTradedDayTime].add(_amount);
else
bucket[_from][_lastTradedDayTime] = bucket[_from][_lastTradedDayTime].add(_amount);
}
if ((_dailyLastTradedDayTime != _lastTradedDayTime) && _dailyLastTradedDayTime != 0 && now <= _endTime) {
// Increasing the total amount of the day by `_amount`
if (isDefault)
defaultBucket[_from][_dailyLastTradedDayTime] = defaultBucket[_from][_dailyLastTradedDayTime].add(_amount);
else
bucket[_from][_dailyLastTradedDayTime] = bucket[_from][_dailyLastTradedDayTime].add(_amount);
}
}
}
function _checkInputParams(
uint256 _allowedTokens,
uint256 _startTime,
uint256 _rollingPeriodDays,
uint256 _endTime,
RestrictionType _restrictionType,
uint256 _earliestStartTime,
bool isModifyDaily
)
internal
pure
{
if (isModifyDaily)
require(_startTime >= _earliestStartTime, "Invalid startTime");
else
require(_startTime > _earliestStartTime, "Invalid startTime");
require(_allowedTokens > 0);
if (_restrictionType != RestrictionType.Fixed) {
require(_allowedTokens <= 100 * 10 ** 16, "Invalid value");
}
// Maximum limit for the rollingPeriod is 365 days
require(_rollingPeriodDays >= 1 && _rollingPeriodDays <= 365, "Invalid rollingperiod");
require(
BokkyPooBahsDateTimeLibrary.diffDays(_startTime, _endTime) >= _rollingPeriodDays,
"Invalid times"
);
}
function _isAllowedToModify(uint256 _startTime) internal view {
require(_startTime > now);
}
function _getValidStartTime(uint256 _startTime) internal view returns(uint256) {
if (_startTime == 0)
_startTime = now + 1;
return _startTime;
}
/**
* @notice Use to get the bucket details for a given address
* @param _user Address of the token holder for whom the bucket details has queried
* @return uint256 lastTradedDayTime
* @return uint256 sumOfLastPeriod
* @return uint256 days covered
* @return uint256 24h lastTradedDayTime
*/
function getIndividualBucketDetailsToUser(address _user) external view returns(uint256, uint256, uint256, uint256, uint256) {
return _getBucketDetails(userToBucket[_user]);
}
/**
* @notice Use to get the bucket details for a given address
* @param _user Address of the token holder for whom the bucket details has queried
* @return uint256 lastTradedDayTime
* @return uint256 sumOfLastPeriod
* @return uint256 days covered
* @return uint256 24h lastTradedDayTime
*/
function getDefaultBucketDetailsToUser(address _user) external view returns(uint256, uint256, uint256, uint256, uint256) {
return _getBucketDetails(defaultUserToBucket[_user]);
}
function _getBucketDetails(BucketDetails storage _bucket) internal view returns(
uint256,
uint256,
uint256,
uint256,
uint256
) {
return(
_bucket.lastTradedDayTime,
_bucket.sumOfLastPeriod,
_bucket.daysCovered,
_bucket.dailyLastTradedDayTime,
_bucket.lastTradedTimestamp
);
}
/**
* @notice Use to get the volume of token that being traded at a particular day (`_at` + 24 hours) for a given user
* @param _user Address of the token holder
* @param _at Timestamp
*/
function getTotalTradedByUser(address _user, uint256 _at) external view returns(uint256) {
return (bucket[_user][_at].add(defaultBucket[_user][_at]));
}
/**
* @notice This function returns the signature of configure function
*/
function getInitFunction() public view returns(bytes4) {
return bytes4(0);
}
/**
* @notice Use to return the list of exempted addresses
*/
function getExemptAddress() external view returns(address[]) {
return exemptAddresses;
}
/**
* @notice Provide the restriction details of all the restricted addresses
* @return address List of the restricted addresses
* @return uint256 List of the tokens allowed to the restricted addresses corresponds to restricted address
* @return uint256 List of the start time of the restriction corresponds to restricted address
* @return uint256 List of the rolling period in days for a restriction corresponds to restricted address.
* @return uint256 List of the end time of the restriction corresponds to restricted address.
* @return RestrictionType List of the type of restriction to validate the value of the `allowedTokens`
* of the restriction corresponds to restricted address
*/
function getRestrictedData() external view returns(
address[] memory allAddresses,
uint256[] memory allowedTokens,
uint256[] memory startTime,
uint256[] memory rollingPeriodInDays,
uint256[] memory endTime,
RestrictionType[] memory typeOfRestriction
) {
uint256 counter = 0;
uint256 i = 0;
for (i = 0; i < holderData.restrictedAddresses.length; i++) {
counter = counter + uint256(
holderData.restrictedHolders[holderData.restrictedAddresses[i]].typeOfPeriod == TypeOfPeriod.Both ? TypeOfPeriod.Both : TypeOfPeriod.OneDay
);
}
allAddresses = new address[](counter);
allowedTokens = new uint256[](counter);
startTime = new uint256[](counter);
rollingPeriodInDays = new uint256[](counter);
endTime = new uint256[](counter);
typeOfRestriction = new RestrictionType[](counter);
counter = 0;
for (i = 0; i < holderData.restrictedAddresses.length; i++) {
allAddresses[counter] = holderData.restrictedAddresses[i];
if (holderData.restrictedHolders[holderData.restrictedAddresses[i]].typeOfPeriod == TypeOfPeriod.MultipleDays) {
_setValues(individualRestriction[holderData.restrictedAddresses[i]], allowedTokens, startTime, rollingPeriodInDays, endTime, typeOfRestriction, counter);
}
else if (holderData.restrictedHolders[holderData.restrictedAddresses[i]].typeOfPeriod == TypeOfPeriod.OneDay) {
_setValues(individualDailyRestriction[holderData.restrictedAddresses[i]], allowedTokens, startTime, rollingPeriodInDays, endTime, typeOfRestriction, counter);
}
else if (holderData.restrictedHolders[holderData.restrictedAddresses[i]].typeOfPeriod == TypeOfPeriod.Both) {
_setValues(individualRestriction[holderData.restrictedAddresses[i]], allowedTokens, startTime, rollingPeriodInDays, endTime, typeOfRestriction, counter);
counter = counter + 1;
allAddresses[counter] = holderData.restrictedAddresses[i];
_setValues(individualDailyRestriction[holderData.restrictedAddresses[i]], allowedTokens, startTime, rollingPeriodInDays, endTime, typeOfRestriction, counter);
}
counter ++;
}
}
function _setValues(
VolumeRestriction memory _restriction,
uint256[] memory _allowedTokens,
uint256[] memory _startTime,
uint256[] memory _rollingPeriodInDays,
uint256[] memory _endTime,
RestrictionType[] memory _typeOfRestriction,
uint256 _index
)
internal
pure
{
_allowedTokens[_index] = _restriction.allowedTokens;
_startTime[_index] = _restriction.startTime;
_rollingPeriodInDays[_index] = _restriction.rollingPeriodInDays;
_endTime[_index] = _restriction.endTime;
_typeOfRestriction[_index] = _restriction.typeOfRestriction;
}
function _checkLengthOfArray(
address[] _holders,
uint256[] _allowedTokens,
uint256[] _startTimes,
uint256[] _rollingPeriodInDays,
uint256[] _endTimes,
VolumeRestrictionTMStorage.RestrictionType[] _restrictionTypes
)
internal
pure
{
require(
_holders.length == _allowedTokens.length &&
_allowedTokens.length == _startTimes.length &&
_startTimes.length == _rollingPeriodInDays.length &&
_rollingPeriodInDays.length == _endTimes.length &&
_endTimes.length == _restrictionTypes.length,
"Length mismatch"
);
}
/**
* @notice Returns the permissions flag that are associated with Percentage transfer Manager
*/
function getPermissions() public view returns(bytes32[] memory allPermissions) {
allPermissions = new bytes32[](1);
allPermissions[0] = ADMIN;
}
}
| This function returns the signature of configure function/ | function getInitFunction() public view returns(bytes4) {
return bytes4(0);
}
| 12,616,650 |
pragma solidity ^0.5.0;
import "../interfaces/ClientPhoenixAuthenticationInterface.sol";
import "../interfaces/PhoenixInterface.sol";
import "../interfaces/IdentityRegistryInterface.sol";
import "../zeppelin/math/SafeMath.sol";
import "../zeppelin/ownership/Ownable.sol";
import "./interfaces/PhoenixIdentityResolverInterface.sol";
import "./interfaces/PhoenixIdentityViaInterface.sol";
contract PhoenixIdentity is Ownable {
using SafeMath for uint;
// mapping of EIN to phoenix token deposits
mapping (uint => uint) public deposits;
// mapping from EIN to resolver to allowance
mapping (uint => mapping (address => uint)) public resolverAllowances;
// SC variables
address public identityRegistryAddress;
IdentityRegistryInterface private identityRegistry;
address public phoenixTokenAddress;
PhoenixInterface private phoenixToken;
address public clientPhoenixAuthenticationAddress;
ClientPhoenixAuthenticationInterface private clientPhoenixAuthentication;
// signature variables
uint public signatureTimeout = 1 days;
mapping (uint => uint) public signatureNonce;
constructor (address _identityRegistryAddress, address _phoenixTokenAddress) public {
setAddresses(_identityRegistryAddress, _phoenixTokenAddress);
}
// enforces that a particular EIN exists
modifier identityExists(uint ein, bool check) {
require(identityRegistry.identityExists(ein) == check, "The EIN does not exist.");
_;
}
// enforces signature timeouts
modifier ensureSignatureTimeValid(uint timestamp) {
require(
// solium-disable-next-line security/no-block-members
block.timestamp >= timestamp && block.timestamp < timestamp + signatureTimeout, "Timestamp is not valid."
);
_;
}
// set the phoenix token and identity registry addresses
function setAddresses(address _identityRegistryAddress, address _phoenixTokenAddress) public onlyOwner {
identityRegistryAddress = _identityRegistryAddress;
identityRegistry = IdentityRegistryInterface(identityRegistryAddress);
phoenixTokenAddress = _phoenixTokenAddress;
phoenixToken = PhoenixInterface(phoenixTokenAddress);
}
function setClientPhoenixAuthenticationAddress(address _clientPhoenixAuthenticationAddress) public onlyOwner {
clientPhoenixAuthenticationAddress = _clientPhoenixAuthenticationAddress;
clientPhoenixAuthentication = ClientPhoenixAuthenticationInterface(clientPhoenixAuthenticationAddress);
}
// wrap createIdentityDelegated and initialize the client phoenixAuthentication resolver
function createIdentityDelegated(
address recoveryAddress, address associatedAddress, address[] memory providers, string memory casedPhoenixId,
uint8 v, bytes32 r, bytes32 s, uint timestamp
)
public returns (uint ein)
{
address[] memory _providers = new address[](providers.length + 1);
_providers[0] = address(this);
for (uint i; i < providers.length; i++) {
_providers[i + 1] = providers[i];
}
uint _ein = identityRegistry.createIdentityDelegated(
recoveryAddress, associatedAddress, _providers, new address[](0), v, r, s, timestamp
);
_addResolver(_ein, clientPhoenixAuthenticationAddress, true, 0, abi.encode(associatedAddress, casedPhoenixId));
return _ein;
}
// permission addProvidersFor by signature
function addProvidersFor(
address approvingAddress, address[] memory providers, uint8 v, bytes32 r, bytes32 s, uint timestamp
)
public ensureSignatureTimeValid(timestamp)
{
uint ein = identityRegistry.getEIN(approvingAddress);
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize that these Providers be added to my Identity.",
ein, providers, timestamp
)
),
v, r, s
),
"Permission denied."
);
identityRegistry.addProvidersFor(ein, providers);
}
// permission removeProvidersFor by signature
function removeProvidersFor(
address approvingAddress, address[] memory providers, uint8 v, bytes32 r, bytes32 s, uint timestamp
)
public ensureSignatureTimeValid(timestamp)
{
uint ein = identityRegistry.getEIN(approvingAddress);
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize that these Providers be removed from my Identity.",
ein, providers, timestamp
)
),
v, r, s
),
"Permission denied."
);
identityRegistry.removeProvidersFor(ein, providers);
}
// permissioned addProvidersFor and removeProvidersFor by signature
function upgradeProvidersFor(
address approvingAddress, address[] memory newProviders, address[] memory oldProviders,
uint8[2] memory v, bytes32[2] memory r, bytes32[2] memory s, uint[2] memory timestamp
)
public
{
addProvidersFor(approvingAddress, newProviders, v[0], r[0], s[0], timestamp[0]);
removeProvidersFor(approvingAddress, oldProviders, v[1], r[1], s[1], timestamp[1]);
uint ein = identityRegistry.getEIN(approvingAddress);
emit PhoenixIdentityProvidersUpgraded(ein, newProviders, oldProviders, approvingAddress);
}
// permission adding a resolver for identity of msg.sender
function addResolver(address resolver, bool isPhoenixIdentity, uint withdrawAllowance, bytes memory extraData) public {
_addResolver(identityRegistry.getEIN(msg.sender), resolver, isPhoenixIdentity, withdrawAllowance, extraData);
}
// permission adding a resolver for identity passed by a provider
function addResolverAsProvider(
uint ein, address resolver, bool isPhoenixIdentity, uint withdrawAllowance, bytes memory extraData
)
public
{
require(identityRegistry.isProviderFor(ein, msg.sender), "The msg.sender is not a Provider for the passed EIN");
_addResolver(ein, resolver, isPhoenixIdentity, withdrawAllowance, extraData);
}
// permission addResolversFor by signature
function addResolverFor(
address approvingAddress, address resolver, bool isPhoenixIdentity, uint withdrawAllowance, bytes memory extraData,
uint8 v, bytes32 r, bytes32 s, uint timestamp
)
public
{
uint ein = identityRegistry.getEIN(approvingAddress);
validateAddResolverForSignature(
approvingAddress, ein, resolver, isPhoenixIdentity, withdrawAllowance, extraData, v, r, s, timestamp
);
_addResolver(ein, resolver, isPhoenixIdentity, withdrawAllowance, extraData);
}
function validateAddResolverForSignature(
address approvingAddress, uint ein,
address resolver, bool isPhoenixIdentity, uint withdrawAllowance, bytes memory extraData,
uint8 v, bytes32 r, bytes32 s, uint timestamp
)
private view ensureSignatureTimeValid(timestamp)
{
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize that this resolver be added to my Identity.",
ein, resolver, isPhoenixIdentity, withdrawAllowance, extraData, timestamp
)
),
v, r, s
),
"Permission denied."
);
}
// common logic for adding resolvers
function _addResolver(uint ein, address resolver, bool isPhoenixIdentity, uint withdrawAllowance, bytes memory extraData)
private
{
require(!identityRegistry.isResolverFor(ein, resolver), "Identity has already set this resolver.");
address[] memory resolvers = new address[](1);
resolvers[0] = resolver;
identityRegistry.addResolversFor(ein, resolvers);
if (isPhoenixIdentity) {
resolverAllowances[ein][resolver] = withdrawAllowance;
PhoenixIdentityResolverInterface phoenixIdentityResolver = PhoenixIdentityResolverInterface(resolver);
if (phoenixIdentityResolver.callOnAddition())
require(phoenixIdentityResolver.onAddition(ein, withdrawAllowance, extraData), "Sign up failure.");
emit PhoenixIdentityResolverAdded(ein, resolver, withdrawAllowance);
}
}
// permission changing resolver allowances for identity of msg.sender
function changeResolverAllowances(address[] memory resolvers, uint[] memory withdrawAllowances) public {
changeResolverAllowances(identityRegistry.getEIN(msg.sender), resolvers, withdrawAllowances);
}
// change resolver allowances delegated
function changeResolverAllowancesDelegated(
address approvingAddress, address[] memory resolvers, uint[] memory withdrawAllowances,
uint8 v, bytes32 r, bytes32 s
)
public
{
uint ein = identityRegistry.getEIN(approvingAddress);
uint nonce = signatureNonce[ein]++;
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize this change in Resolver allowances.",
ein, resolvers, withdrawAllowances, nonce
)
),
v, r, s
),
"Permission denied."
);
changeResolverAllowances(ein, resolvers, withdrawAllowances);
}
// common logic to change resolver allowances
function changeResolverAllowances(uint ein, address[] memory resolvers, uint[] memory withdrawAllowances) private {
require(resolvers.length == withdrawAllowances.length, "Malformed inputs.");
for (uint i; i < resolvers.length; i++) {
require(identityRegistry.isResolverFor(ein, resolvers[i]), "Identity has not set this resolver.");
resolverAllowances[ein][resolvers[i]] = withdrawAllowances[i];
emit PhoenixIdentityResolverAllowanceChanged(ein, resolvers[i], withdrawAllowances[i]);
}
}
// permission removing a resolver for identity of msg.sender
function removeResolver(address resolver, bool isPhoenixIdentity, bytes memory extraData) public {
removeResolver(identityRegistry.getEIN(msg.sender), resolver, isPhoenixIdentity, extraData);
}
// permission removeResolverFor by signature
function removeResolverFor(
address approvingAddress, address resolver, bool isPhoenixIdentity, bytes memory extraData,
uint8 v, bytes32 r, bytes32 s, uint timestamp
)
public ensureSignatureTimeValid(timestamp)
{
uint ein = identityRegistry.getEIN(approvingAddress);
validateRemoveResolverForSignature(approvingAddress, ein, resolver, isPhoenixIdentity, extraData, v, r, s, timestamp);
removeResolver(ein, resolver, isPhoenixIdentity, extraData);
}
function validateRemoveResolverForSignature(
address approvingAddress, uint ein, address resolver, bool isPhoenixIdentity, bytes memory extraData,
uint8 v, bytes32 r, bytes32 s, uint timestamp
)
private view
{
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize that these Resolvers be removed from my Identity.",
ein, resolver, isPhoenixIdentity, extraData, timestamp
)
),
v, r, s
),
"Permission denied."
);
}
// common logic to remove resolvers
function removeResolver(uint ein, address resolver, bool isPhoenixIdentity, bytes memory extraData) private {
require(identityRegistry.isResolverFor(ein, resolver), "Identity has not yet set this resolver.");
delete resolverAllowances[ein][resolver];
if (isPhoenixIdentity) {
PhoenixIdentityResolverInterface phoenixIdentityResolver = PhoenixIdentityResolverInterface(resolver);
if (phoenixIdentityResolver.callOnRemoval())
require(phoenixIdentityResolver.onRemoval(ein, extraData), "Removal failure.");
emit PhoenixIdentityResolverRemoved(ein, resolver);
}
address[] memory resolvers = new address[](1);
resolvers[0] = resolver;
identityRegistry.removeResolversFor(ein, resolvers);
}
function triggerRecoveryAddressChangeFor(
address approvingAddress, address newRecoveryAddress, uint8 v, bytes32 r, bytes32 s
)
public
{
uint ein = identityRegistry.getEIN(approvingAddress);
uint nonce = signatureNonce[ein]++;
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize this change of Recovery Address.",
ein, newRecoveryAddress, nonce
)
),
v, r, s
),
"Permission denied."
);
identityRegistry.triggerRecoveryAddressChangeFor(ein, newRecoveryAddress);
}
// allow contract to receive PHNX tokens
function receiveApproval(address sender, uint amount, address _tokenAddress, bytes memory _bytes) public {
require(msg.sender == _tokenAddress, "Malformed inputs.");
require(_tokenAddress == phoenixTokenAddress, "Sender is not the PHNX token smart contract.");
// depositing to an EIN
if (_bytes.length <= 32) {
require(phoenixToken.transferFrom(sender, address(this), amount), "Unable to transfer token ownership.");
uint recipient;
if (_bytes.length < 32) {
recipient = identityRegistry.getEIN(sender);
}
else {
recipient = abi.decode(_bytes, (uint));
require(identityRegistry.identityExists(recipient), "The recipient EIN does not exist.");
}
deposits[recipient] = deposits[recipient].add(amount);
emit PhoenixIdentityDeposit(sender, recipient, amount);
}
// transferring to a via
else {
(
bool isTransfer, address resolver, address via, uint to, bytes memory phoenixIdentityCallBytes
) = abi.decode(_bytes, (bool, address, address, uint, bytes));
require(phoenixToken.transferFrom(sender, via, amount), "Unable to transfer token ownership.");
PhoenixIdentityViaInterface viaContract = PhoenixIdentityViaInterface(via);
if (isTransfer) {
viaContract.phoenixIdentityCall(resolver, to, amount, phoenixIdentityCallBytes);
emit PhoenixIdentityTransferToVia(resolver, via, to, amount);
} else {
address payable payableTo = address(to);
viaContract.phoenixIdentityCall(resolver, payableTo, amount, phoenixIdentityCallBytes);
emit PhoenixIdentityWithdrawToVia(resolver, via, address(to), amount);
}
}
}
// transfer phoenixIdentity balance from one phoenixIdentity holder to another
function transferPhoenixIdentityBalance(uint einTo, uint amount) public {
_transfer(identityRegistry.getEIN(msg.sender), einTo, amount);
}
// withdraw PhoenixIdentity balance to an external address
function withdrawPhoenixIdentityBalance(address to, uint amount) public {
_withdraw(identityRegistry.getEIN(msg.sender), to, amount);
}
// allows resolvers to transfer allowance amounts to other phoenixIdentitys (throws if unsuccessful)
function transferPhoenixIdentityBalanceFrom(uint einFrom, uint einTo, uint amount) public {
handleAllowance(einFrom, amount);
_transfer(einFrom, einTo, amount);
emit PhoenixIdentityTransferFrom(msg.sender);
}
// allows resolvers to withdraw allowance amounts to external addresses (throws if unsuccessful)
function withdrawPhoenixIdentityBalanceFrom(uint einFrom, address to, uint amount) public {
handleAllowance(einFrom, amount);
_withdraw(einFrom, to, amount);
emit PhoenixIdentityWithdrawFrom(msg.sender);
}
// allows resolvers to send withdrawal amounts to arbitrary smart contracts 'to' identities (throws if unsuccessful)
function transferPhoenixIdentityBalanceFromVia(uint einFrom, address via, uint einTo, uint amount, bytes memory _bytes)
public
{
handleAllowance(einFrom, amount);
_withdraw(einFrom, via, amount);
PhoenixIdentityViaInterface viaContract = PhoenixIdentityViaInterface(via);
viaContract.phoenixIdentityCall(msg.sender, einFrom, einTo, amount, _bytes);
emit PhoenixIdentityTransferFromVia(msg.sender, einTo);
}
// allows resolvers to send withdrawal amounts 'to' addresses via arbitrary smart contracts
function withdrawPhoenixIdentityBalanceFromVia(
uint einFrom, address via, address payable to, uint amount, bytes memory _bytes
)
public
{
handleAllowance(einFrom, amount);
_withdraw(einFrom, via, amount);
PhoenixIdentityViaInterface viaContract = PhoenixIdentityViaInterface(via);
viaContract.phoenixIdentityCall(msg.sender, einFrom, to, amount, _bytes);
emit PhoenixIdentityWithdrawFromVia(msg.sender, to);
}
function _transfer(uint einFrom, uint einTo, uint amount) private identityExists(einTo, true) returns (bool) {
require(deposits[einFrom] >= amount, "Cannot withdraw more than the current deposit balance.");
deposits[einFrom] = deposits[einFrom].sub(amount);
deposits[einTo] = deposits[einTo].add(amount);
emit PhoenixIdentityTransfer(einFrom, einTo, amount);
}
function _withdraw(uint einFrom, address to, uint amount) internal {
require(to != address(this), "Cannot transfer to the PhoenixIdentity smart contract itself.");
require(deposits[einFrom] >= amount, "Cannot withdraw more than the current deposit balance.");
deposits[einFrom] = deposits[einFrom].sub(amount);
require(phoenixToken.transfer(to, amount), "Transfer was unsuccessful");
emit PhoenixIdentityWithdraw(einFrom, to, amount);
}
function handleAllowance(uint einFrom, uint amount) internal {
// check that resolver-related details are correct
require(identityRegistry.isResolverFor(einFrom, msg.sender), "Resolver has not been set by from tokenholder.");
if (resolverAllowances[einFrom][msg.sender] < amount) {
emit PhoenixIdentityInsufficientAllowance(einFrom, msg.sender, resolverAllowances[einFrom][msg.sender], amount);
revert("Insufficient Allowance");
}
resolverAllowances[einFrom][msg.sender] = resolverAllowances[einFrom][msg.sender].sub(amount);
}
// allowAndCall from msg.sender
function allowAndCall(address destination, uint amount, bytes memory data)
public returns (bytes memory returnData)
{
return allowAndCall(identityRegistry.getEIN(msg.sender), amount, destination, data);
}
// allowAndCall from approvingAddress with meta-transaction
function allowAndCallDelegated(
address destination, uint amount, bytes memory data, address approvingAddress, uint8 v, bytes32 r, bytes32 s
)
public returns (bytes memory returnData)
{
uint ein = identityRegistry.getEIN(approvingAddress);
uint nonce = signatureNonce[ein]++;
validateAllowAndCallDelegatedSignature(approvingAddress, ein, destination, amount, data, nonce, v, r, s);
return allowAndCall(ein, amount, destination, data);
}
function validateAllowAndCallDelegatedSignature(
address approvingAddress, uint ein, address destination, uint amount, bytes memory data, uint nonce,
uint8 v, bytes32 r, bytes32 s
)
private view
{
require(
identityRegistry.isSigned(
approvingAddress,
keccak256(
abi.encodePacked(
byte(0x19), byte(0), address(this),
"I authorize this allow and call.", ein, destination, amount, data, nonce
)
),
v, r, s
),
"Permission denied."
);
}
// internal logic for allowAndCall
function allowAndCall(uint ein, uint amount, address destination, bytes memory data)
private returns (bytes memory returnData)
{
// check that resolver-related details are correct
require(identityRegistry.isResolverFor(ein, destination), "Destination has not been set by from tokenholder.");
if (amount != 0) {
resolverAllowances[ein][destination] = resolverAllowances[ein][destination].add(amount);
}
// solium-disable-next-line security/no-low-level-calls
(bool success, bytes memory _returnData) = destination.call(data);
require(success, "Call was not successful.");
return _returnData;
}
// events
event PhoenixIdentityProvidersUpgraded(uint indexed ein, address[] newProviders, address[] oldProviders, address approvingAddress);
event PhoenixIdentityResolverAdded(uint indexed ein, address indexed resolver, uint withdrawAllowance);
event PhoenixIdentityResolverAllowanceChanged(uint indexed ein, address indexed resolver, uint withdrawAllowance);
event PhoenixIdentityResolverRemoved(uint indexed ein, address indexed resolver);
event PhoenixIdentityDeposit(address indexed from, uint indexed einTo, uint amount);
event PhoenixIdentityTransfer(uint indexed einFrom, uint indexed einTo, uint amount);
event PhoenixIdentityWithdraw(uint indexed einFrom, address indexed to, uint amount);
event PhoenixIdentityTransferFrom(address indexed resolverFrom);
event PhoenixIdentityWithdrawFrom(address indexed resolverFrom);
event PhoenixIdentityTransferFromVia(address indexed resolverFrom, uint indexed einTo);
event PhoenixIdentityWithdrawFromVia(address indexed resolverFrom, address indexed to);
event PhoenixIdentityTransferToVia(address indexed resolverFrom, address indexed via, uint indexed einTo, uint amount);
event PhoenixIdentityWithdrawToVia(address indexed resolverFrom, address indexed via, address indexed to, uint amount);
event PhoenixIdentityInsufficientAllowance(
uint indexed ein, address indexed resolver, uint currentAllowance, uint requestedWithdraw
);
}
| permission removeResolverFor by signature | function removeResolverFor(
address approvingAddress, address resolver, bool isPhoenixIdentity, bytes memory extraData,
uint8 v, bytes32 r, bytes32 s, uint timestamp
)
public ensureSignatureTimeValid(timestamp)
{
uint ein = identityRegistry.getEIN(approvingAddress);
validateRemoveResolverForSignature(approvingAddress, ein, resolver, isPhoenixIdentity, extraData, v, r, s, timestamp);
removeResolver(ein, resolver, isPhoenixIdentity, extraData);
}
| 13,045,012 |
// File: 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: 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: 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: 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: 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: 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: 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: 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: contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: 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: contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
"ERC721: balance query for the zero address"
);
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
address owner = _owners[tokenId];
require(
owner != address(0),
"ERC721: owner query for nonexistent token"
);
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. 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 {}
}
// File: contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(IERC165, ERC721)
returns (bool)
{
return
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
require(
index < ERC721.balanceOf(owner),
"ERC721Enumerable: owner index out of bounds"
);
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
require(
index < ERC721Enumerable.totalSupply(),
"ERC721Enumerable: global index out of bounds"
);
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId)
private
{
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: tests/CryptoHeartz.sol
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
contract CryptoHeartz is ERC721Enumerable, Ownable {
using Strings for uint256;
string public baseURI;
string public notRevealedURI;
string public baseExtension = ".json";
uint256 public cost = 0.00 ether;
uint256 public maxSupply = 4257;
uint256 public maxMintAmount = 20;
bool public paused = false;
bool private revealed = false;
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initNotRevealedURI
) ERC721(_name, _symbol) {
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedURI);
mint(msg.sender, 3);
}
// public
function mint(address _to, uint256 _mintAmount) public payable {
uint256 supply = totalSupply();
require(!paused);
require(_mintAmount > 0);
require(_mintAmount <= maxMintAmount);
require(supply + _mintAmount <= maxSupply);
if (msg.sender != owner()) {
//general public
require(msg.value >= cost * _mintAmount);
}
for (uint256 i = 1; i <= _mintAmount; i++) {
_safeMint(_to, supply + i);
}
}
function walletOfOwner(address _owner) public view returns (uint256[] memory) {
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return revealed == true ?
string(abi.encodePacked(baseURI, tokenId.toString(), baseExtension)) : notRevealedURI;
}
// set reveal to true
function revealCollection() public onlyOwner{
revealed = true;
}
//only owner
function setCost(uint256 _newCost) public onlyOwner {
cost = _newCost;
}
function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner {
maxMintAmount = _newmaxMintAmount;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedURI = _notRevealedURI;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{
value: address(this).balance
}("");
require(success);
}
} | Required interface of an ERC721 compliant contract./ | interface IERC721 is IERC165 {
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId)
external
view
returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
| 69,013 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/access/Ownable.sol";
import '@openzeppelin/contracts/token/ERC1155/ERC1155.sol';
import "@openzeppelin/contracts/utils/Counters.sol";
import './Utils.sol';
/**
* @title HappyRobotWhitelistToken
* HappyRobotWhitelistToken - ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin,
like _exists(), name(), symbol(), and totalSupply()
*/
contract HappyRobotWhitelistToken is ERC1155, Ownable {
using Counters for Counters.Counter;
uint8 constant TOKEN_ID = 1;
uint16 private tokenSupply = 0;
// Contract name
string public name;
// Contract symbol
string public symbol;
uint8 constant SALE_STATUS_NONE = 0;
uint8 saleStatus = SALE_STATUS_NONE;
address[] private minters;
mapping(address => uint8) mintsMap;
mapping(address => uint8) burnsMap;
uint16 private totalMints = 0;
uint16 private totalBurns = 0;
uint8 private maxPerWallet = 2;
uint16 private maxWLTokens = 300;
uint256 private mintFee = 0.075 ether;
address payable constant public walletMaster = payable(0x4846063Ec8b9A428fFEe1640E790b8F825D4AbF0);
address payable constant public walletDevTeam = payable(0x52BD82C6B851AdAC6A77BC0F9520e5A062CD9a78);
address payable constant public walletArtist = payable(0x22d57ccD4e05DD1592f52A4B0f909edBB82e8D26);
address proxyRegistryAddress;
event MintedWLToken(address _owner, uint16 _quantity, uint256 _totalOwned);
constructor(
string memory _uri, address _proxyRegistryAddress
) ERC1155(_uri) {
name = "HRF Token";
symbol = "HRFTOKEN";
proxyRegistryAddress = _proxyRegistryAddress;
}
/**
* Require msg.sender to be the master or dev team
*/
modifier onlyMaster() {
require(isMaster(msg.sender), "Happy Robot Whitelist Token: You are not a Master");
_;
}
/**
* require none sale status
*/
modifier onlyNonSaleStatus() {
require(saleStatus == SALE_STATUS_NONE, "Happy Robot Whitelist Token: It is sale period");
_;
}
/**
* get account is master or not
* @param _account address
* @return true or false
*/
function isMaster(address _account) public pure returns (bool) {
return walletMaster == payable(_account) || walletDevTeam == payable(_account);
}
/**
* get token amount
* @return token amount
*/
function totalSupply() public view returns (uint16) {
return tokenSupply;
}
/**
* get uri
* @return uri
*/
function tokenUri() public view returns (string memory) {
return ERC1155.uri(TOKEN_ID);
}
/**
* set token uri
* @param _uri token uri
*/
function setURI(string memory _uri) public onlyOwner {
_setURI(_uri);
}
/**
* get token quantity of account
* @param _account account
* @return token quantity of account
*/
function quantityOf(address _account) public view returns (uint256) {
return balanceOf(_account, TOKEN_ID);
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(address _owner, address _operator) public view override returns (bool isOperator) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* get max wl tokens per wallet
* @return max wl tokens per wallet
*/
function getMaxPerWallet() public view returns (uint8) {
return maxPerWallet;
}
/**
* set max wl tokens per wallet
* @param _maxPerWallet max wl tokens per wallet
*/
function setMaxPerWallet(uint8 _maxPerWallet) public onlyMaster {
maxPerWallet = _maxPerWallet;
}
/**
* get whitelist token mint fee
* @return whitelist token mint fee
*/
function getMintFee() public view returns (uint256) {
return mintFee;
}
/**
* set whitelist token mint fee
* @param _mintFee mint fee
*/
function setMintFee(uint256 _mintFee) public onlyMaster {
mintFee = _mintFee;
}
/**
* get sale status
* @return sale status
*/
function getSaleStatus() public view returns (uint8) {
return saleStatus;
}
/**
* set sale status
* @param _saleStatus sale status
*/
function setSaleStatus(uint8 _saleStatus) public onlyMaster {
saleStatus = _saleStatus;
}
/**
* get max wl tokens
* @return max wl tokens
*/
function getMaxWLTokens() public view returns (uint16) {
return maxWLTokens;
}
/**
* set max wl tokens
* @param _maxWLTokens max wl tokens
*/
function setMaxWLTokens(uint8 _maxWLTokens) public onlyMaster {
maxWLTokens = _maxWLTokens;
}
/**
* get whitelist token minters
*/
function getMinters() public view returns (address[] memory) {
return minters;
}
/**
* check if _account is in the whitelist token minters
* @param _account address
* @return
*/
function existInMinters(address _account) public view returns (bool) {
for (uint256 i = 0; i < minters.length; i++) {
if (minters[i] == _account)
return true;
}
return false;
}
/**
* add an address into the whitelist
* @param _account address
*/
function addToMinters(address _account) internal {
// if already registered, skip
for (uint16 i = 0; i < minters.length; i++) {
if (minters[i] == _account) return;
}
// add address to the list
minters.push(_account);
}
/**
* remove an address from the minter list
* @param _account address
*/
function removeFromMinters(address _account) internal {
// find index of _from
uint256 index = 0xFFFF;
uint256 len = minters.length;
for (uint256 i = 0; i < len; i++) {
if (minters[i] == _account) {
index = i;
break;
}
}
// remove it
if (index != 0xFFFF && len > 0) {
minters[index] = minters[len - 1];
minters.pop();
}
}
/**
* get number of total minted whitelist tokens
* @return number of total minted whitelist tokens
*/
function getTotalMinted() public view returns (uint16) {
return totalMints;
}
/**
* get number of total burned whitelist tokens
* @return number of total burned whitelist tokens
*/
function getTotalBurned() public view returns (uint16) {
return totalBurns;
}
/**
* get number of minted count for account
* @param _account address
* @return number of minted count for account
*/
function getMints(address _account) public view returns (uint8) {
return mintsMap[_account];
}
/**
* get number of burned count for account
* @param _account address
* @return number of burned count for account
*/
function getBurns(address _account) public view returns (uint8) {
return burnsMap[_account];
}
/**
* get number of owned whitelist token(including burned count) for account
* @param _account address
* @return number of owned whitelist token(including burned count) for account
*/
function getOwned(address _account) public view returns (uint8) {
unchecked {
return uint8(quantityOf(_account)) + burnsMap[_account];
}
}
/**
* check if mint is possible for account
* @param _account account
* @param _quantity quantity
* @return true or false
*/
function canMintForAccount(address _account, uint16 _quantity) internal view returns (bool) {
if (isMaster(_account)) return true;
unchecked {
uint8 balance = uint8(quantityOf(_account));
uint8 totalOwned = balance + burnsMap[_account];
return totalOwned + _quantity - 1 < maxPerWallet;
}
}
/**
* mint whitelist token
* @param _quantity token amount
*/
function mint(uint8 _quantity) external payable onlyNonSaleStatus {
require(canMintForAccount(msg.sender, _quantity) == true, "Happy Robot Whitelist Token: Maximum whitelist token mint already reached for the account");
require(totalSupply() + _quantity - 1 < maxWLTokens, "Happy Robot Whitelist Token: Maximum whitelist token already reached");
if (!isMaster(msg.sender)) {
require(msg.value > mintFee * _quantity - 1, "Happy Robot Whitelist Token: Not enough ETH sent");
// perform mint
mint(msg.sender, _quantity);
unchecked {
uint256 fee = mintFee * _quantity;
uint256 feeForDev = (uint256)(fee / 200); // 0.5% to the dev
walletDevTeam.transfer(feeForDev);
uint256 feeForArtist = (uint256)(fee / 40); // 2.5% to the dev
walletArtist.transfer(feeForArtist);
// return back remain value
uint256 remainVal = msg.value - fee;
address payable caller = payable(msg.sender);
caller.transfer(remainVal);
}
} else { // no price for master wallet
// perform mint
mint(msg.sender, _quantity);
// return back the ethers
address payable caller = payable(msg.sender);
caller.transfer(msg.value);
}
}
/**
* mint tokens
* @param _to address to mint
* @param _quantity token quantity
*/
function mint(address _to, uint8 _quantity) internal {
_mint(_to, TOKEN_ID, _quantity, '');
addToMinters(_to);
unchecked {
totalMints += _quantity;
mintsMap[_to] += _quantity; // add mints map
tokenSupply += _quantity;
}
// trigger whitelist token minted event
emit MintedWLToken(_to, _quantity, totalMints);
}
/**
* burn token
* @param _from address to burn
* @param _quantity token quantity
*/
function burn(address _from, uint8 _quantity) public onlyOwner {
_burn(_from, TOKEN_ID, _quantity);
unchecked {
totalBurns += _quantity;
burnsMap[_from] += _quantity; // add burns map
tokenSupply -= _quantity;
}
}
/**
* withdraw balance to only master wallet
*/
function withdrawAll() external onlyMaster {
address payable to = payable(msg.sender);
to.transfer(address(this).balance);
}
}
// 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/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `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 memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - 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[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
contract OwnableDelegateProxy { }
/**
* Used to delegate ownership of a contract to another address, to save on unneeded transactions to approve contract use for users
*/
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
// 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 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.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
// 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/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);
} | burn token _from address to burn _quantity token quantity/ | function burn(address _from, uint8 _quantity) public onlyOwner {
_burn(_from, TOKEN_ID, _quantity);
unchecked {
totalBurns += _quantity;
tokenSupply -= _quantity;
}
}
| 14,513,379 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
// dependencies
import {AggregatorV3Interface} from "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {Context} from "@openzeppelin/contracts/utils/Context.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// interfaces
import {IPerpetual} from "./interfaces/IPerpetual.sol";
import {IVault} from "./interfaces/IVault.sol";
// libraries
import {LibMath} from "./lib/LibMath.sol";
import {LibPerpetual} from "./lib/LibPerpetual.sol";
import {IncreOwnable} from "./utils/IncreOwnable.sol";
import {MockStableSwap} from "./mocks/MockStableSwap.sol";
import "hardhat/console.sol";
contract Perpetual is IPerpetual, Context, IncreOwnable {
using SafeCast for uint256;
using SafeCast for int256;
// parameterization
int256 constant MIN_MARGIN = 25e15; // 2.5%
int256 constant LIQUIDATION_FEE = 60e15; // 6%
int256 constant PRECISION = 10e18;
// global state
MockStableSwap private market;
LibPerpetual.GlobalPosition private globalPosition;
LibPerpetual.Price[] private prices;
mapping(IVault => bool) private vaultInitialized;
// user state
mapping(address => LibPerpetual.TraderPosition) private userPosition;
mapping(address => IVault) private vaultUsed;
constructor(uint256 _vQuote, uint256 _vBase) {
market = new MockStableSwap(_vQuote, _vBase);
}
// global getter
function getStableSwap() public view returns (address) {
return address(market);
}
function isVault(address vaultAddress) public view returns (bool) {
return vaultInitialized[IVault(vaultAddress)];
}
function getLatestPrice() public view override returns (LibPerpetual.Price memory) {
return getPrice(prices.length - 1);
}
function getPrice(uint256 period) public view override returns (LibPerpetual.Price memory) {
return prices[period];
}
function getGlobalPosition() public view override returns (LibPerpetual.GlobalPosition memory) {
return globalPosition;
}
// user getter
function getVault(address account) public view override returns (IVault) {
return vaultUsed[account];
}
function getUserPosition(address account) public view override returns (LibPerpetual.TraderPosition memory) {
return userPosition[account];
}
// functions
function setVault(address vaultAddress) public onlyOwner {
IVault vault = IVault(vaultAddress);
require(vaultInitialized[vault] == false, "Vault is already initialized");
vaultInitialized[vault] = true;
emit VaultRegistered(vaultAddress);
}
function setPrice(LibPerpetual.Price memory newPrice) external override {
prices.push(newPrice);
}
function _verifyAndSetVault(IVault vault) internal {
require(vaultInitialized[vault], "Vault is not initialized");
IVault oldVault = vaultUsed[_msgSender()];
if (address(oldVault) == address(0)) {
// create new vault
vaultUsed[_msgSender()] = vault;
emit VaultAssigned(_msgSender(), address(vault));
} else {
// check uses same vault
require(oldVault == vault, "Uses other vault");
}
}
/// @notice Deposits tokens into the vault. Note that a vault can support multiple collateral tokens.
function deposit(
uint256 amount,
IVault vault,
IERC20 token
) external override {
_verifyAndSetVault(vault);
vault.deposit(_msgSender(), amount, token);
emit Deposit(_msgSender(), address(token), amount);
}
/// @notice Withdraw tokens from the vault. Note that a vault can support multiple collateral tokens.
function withdraw(uint256 amount, IERC20 token) external override {
require(getUserPosition(_msgSender()).notional == 0, "Has open position");
IVault vault = vaultUsed[_msgSender()];
vault.withdraw(_msgSender(), amount, token);
emit Withdraw(_msgSender(), address(token), amount);
}
/// @notice Buys long Quote derivatives
/// @param amount Amount of Quote tokens to be bought
/// @dev No checks are done if bought amount exceeds allowance
function openPosition(uint256 amount, LibPerpetual.Side direction) external override returns (uint256) {
LibPerpetual.TraderPosition storage user = userPosition[_msgSender()];
LibPerpetual.GlobalPosition storage global = globalPosition;
require(user.notional == 0, "Trader position is not allowed to have position open");
uint256 quoteBought = _openPosition(user, global, direction, amount);
emit OpenPosition(_msgSender(), uint128(block.timestamp), direction, amount, quoteBought);
return quoteBought;
}
function _openPosition(
LibPerpetual.TraderPosition storage user,
LibPerpetual.GlobalPosition storage global,
LibPerpetual.Side direction,
uint256 amount
) internal returns (uint256) {
// buy derivative tokens
user.side = direction;
uint256 quoteBought = _openPositionOnMarket(amount, direction);
// set trader position
user.notional = amount.toInt256();
user.positionSize = quoteBought.toInt256();
user.profit = 0;
user.timeStamp = global.timeStamp;
user.cumFundingRate = global.cumFundingRate;
return quoteBought;
}
function _openPositionOnMarket(uint256 amount, LibPerpetual.Side direction) internal returns (uint256) {
uint256 quoteBought = 0;
if (direction == LibPerpetual.Side.Long) {
quoteBought = market.mintVBase(amount);
} else if (direction == LibPerpetual.Side.Short) {
quoteBought = market.burnVBase(amount);
}
return quoteBought;
}
/// @notice Closes position from account holder
function closePosition() external override {
LibPerpetual.TraderPosition storage user = userPosition[_msgSender()];
LibPerpetual.GlobalPosition storage global = globalPosition;
// get information about position
_closePosition(user, global);
// apply changes to collateral
IVault userVault = vaultUsed[_msgSender()];
userVault.settleProfit(_msgSender(), user.profit);
}
function _closePosition(LibPerpetual.TraderPosition storage user, LibPerpetual.GlobalPosition storage global)
internal
{
uint256 amount = (user.positionSize).toUint256();
LibPerpetual.Side direction = user.side;
// settle funding rate
_settle(user, global);
// sell derivative tokens
uint256 quoteSold = _closePositionOnMarket(amount, direction);
// set trader position
user.profit += _calculatePnL(user.notional, quoteSold.toInt256());
user.notional = 0;
user.positionSize = 0;
}
// get information about position
function _calculatePnL(int256 boughtPrice, int256 soldPrice) internal pure returns (int256) {
return soldPrice - boughtPrice;
}
/// notional sell derivative tokens on (external) market
function _closePositionOnMarket(uint256 amount, LibPerpetual.Side direction) internal returns (uint256) {
uint256 quoteSold = 0;
if (direction == LibPerpetual.Side.Long) {
quoteSold = market.mintVQuote(amount);
} else {
quoteSold = market.burnVQuote(amount);
}
return quoteSold;
}
/// @notice Settle funding rate
function settle(address account) public override {
LibPerpetual.TraderPosition storage user = userPosition[account];
LibPerpetual.GlobalPosition storage global = globalPosition;
_settle(user, global);
}
function _settle(LibPerpetual.TraderPosition storage user, LibPerpetual.GlobalPosition storage global) internal {
if (user.notional != 0 && user.timeStamp < global.timeStamp) {
// update user variables when position opened before last update
int256 upcomingFundingPayment = getFundingPayments(user, global);
_applyFundingPayment(user, upcomingFundingPayment);
emit Settlement(_msgSender(), user.timeStamp, upcomingFundingPayment);
}
// update user variables to global state
user.timeStamp = global.timeStamp;
user.cumFundingRate = global.cumFundingRate;
}
/// @notice Apply funding payments
function _applyFundingPayment(LibPerpetual.TraderPosition storage user, int256 payments) internal {
user.profit += payments;
}
/// @notice Calculate missed funing payments
function getFundingPayments(LibPerpetual.TraderPosition memory user, LibPerpetual.GlobalPosition memory global)
public
pure
returns (int256)
{
/* Funding rates (as defined in our protocol) are paid from shorts to longs
case 1: user is long => has missed receiving funding payments (positive or negative)
case 2: user is short => has missed making funding payments (positive or negative)
comment: Making an negative funding payment is equvalent to receiving a positive one.
*/
int256 upcomingFundingRate = 0;
int256 upcomingFundingPayment = 0;
if (user.cumFundingRate != global.cumFundingRate) {
if (user.side == LibPerpetual.Side.Long) {
upcomingFundingRate = global.cumFundingRate - user.cumFundingRate;
} else {
upcomingFundingRate = user.cumFundingRate - global.cumFundingRate;
}
upcomingFundingPayment = LibMath.mul(upcomingFundingRate, user.notional);
}
return upcomingFundingPayment;
}
function marginIsValid(address account) public view override returns (bool) {
return marginRatio(account) <= MIN_MARGIN;
}
/// @notice Calculate the margin Ratio of some account
function marginRatio(address account) public view override returns (int256) {
LibPerpetual.TraderPosition memory user = getUserPosition(account);
LibPerpetual.GlobalPosition memory global = getGlobalPosition();
IVault userVault = getVault(account);
// calcuate margin ratio = = (margin + pnl + fundingPayments) / position.getNotional()
int256 margin = userVault.getReserveValue(account);
int256 fundingPayments = getFundingPayments(user, global);
int256 unrealizedPnl = 0; /// toDO: requires implementation of curve pool;
int256 profit = getUserPosition(account).profit;
return LibMath.div(margin + unrealizedPnl + fundingPayments + profit, user.notional);
}
function liquidate(address account, IVault liquidatorVault) external {
require(!marginIsValid(account), "Margin is not valid");
address liquidator = _msgSender();
// load information about state
LibPerpetual.TraderPosition storage user = userPosition[account];
LibPerpetual.GlobalPosition storage global = globalPosition;
int256 notionalAmount = user.notional;
// get information about position
_closePosition(user, global);
// liquidation costs
int256 liquidationFee = (notionalAmount * LIQUIDATION_FEE) / PRECISION;
// profits - liquidationFee gets paid out
int256 reducedProfit = user.profit - liquidationFee;
// substract fee from user account
IVault userVault = vaultUsed[account];
userVault.settleProfit(account, reducedProfit);
// add fee to liquidator account
_verifyAndSetVault(liquidatorVault);
liquidatorVault.settleProfit(liquidator, liquidationFee);
emit LiquidationCall(account, _msgSender(), uint128(block.timestamp), notionalAmount);
}
}
| Withdraw tokens from the vault. Note that a vault can support multiple collateral tokens. | function withdraw(uint256 amount, IERC20 token) external override {
require(getUserPosition(_msgSender()).notional == 0, "Has open position");
IVault vault = vaultUsed[_msgSender()];
vault.withdraw(_msgSender(), amount, token);
emit Withdraw(_msgSender(), address(token), amount);
}
| 994,499 |
./full_match/1/0xccccB27BB46ffE01479248EDDFb75E300DE06879/sources/contracts/bridgeToken/adapters/ccip/CCIPBridgeAdapter.sol | Lock BIFI in lockbox and burn minted tokens. | function _bridge(address _user, uint256 _dstChainId, uint256 _amount, address _to) private {
if (!whitelistedChains[chainIdToCcipId[_dstChainId]]) revert InvalidChain();
if (address(lockbox) != address(0)) {
BIFI.safeTransferFrom(_user, address(this), _amount);
lockbox.deposit(_amount);
xBIFI.burn(address(this), _amount);
} else xBIFI.burn(_user, _amount);
abi.encode(address(this)),
abi.encode(_to, _amount),
new IRouterClient.EVMTokenAmount[](0),
address(0),
extraArgs
);
emit BridgedOut(_dstChainId, _user, _to, _amount);
}
| 4,843,225 |
/**
@title ERC-20 Fungible Token Standard basic implementation
Implementation of OpenZeppelin used. Changes made by Chaitanya-Konda
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity ^0.5.8;
import "./ERC20Interface.sol";
import "./SafeMath.sol";
contract ERC20 is ERC20Interface {
using SafeMath for uint256;
string public symbol;
string public name;
address payable public owner;
uint256 private _totalSupply;
mapping (address => uint256) private balances;
mapping (address => mapping (address => uint256)) private allowed;
mapping (address => mapping (address => uint)) private timeLock;
constructor() public {
symbol = "EG";
name = "ExampleCoin";
_totalSupply = 1000000;
owner = msg.sender;
balances[owner] = _totalSupply;
emit Transfer(address(0), owner, _totalSupply);
}
//only owner modifier
modifier onlyOwner () {
require(msg.sender == owner);
_;
}
/**
self destruct added by westlad
*/
function close() public onlyOwner {
selfdestruct(address(owner));
}
/**
* @dev Gets the balance of the specified address.
* @param _address The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _address) public view returns (uint256) {
return balances[_address];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param _account The account that will receive the created tokens.
* @param _amount The amount that will be created.
*/
function _mint(address _account, uint256 _amount) internal {
require(_account != address(0));
require(_amount > 0);
_totalSupply = _totalSupply.add(_amount);
balances[_account] = balances[_account].add(_amount);
emit Transfer(address(0), _account, _amount);
}
function mint(address _account, uint256 _amount) public {
_mint(_account, _amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param _account The account whose tokens will be burnt.
* @param _amount The amount that will be burnt.
*/
function _burn(address _account, uint256 _amount) internal {
require(_account != address(0));
require(_amount <= balances[_account]);
_totalSupply = _totalSupply.sub(_amount);
balances[_account] = balances[_account].sub(_amount);
emit Transfer(_account, address(0), _amount);
}
function burn(address _account, uint256 _amount) public {
_burn(_account, _amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param _account The account whose tokens will be burnt.
* @param _amount The amount that will be burnt.
*/
function _burnFrom(address _account, uint256 _amount) internal {
require(_amount <= allowed[_account][msg.sender]);
allowed[_account][msg.sender] = allowed[_account][msg.sender].sub(_amount);
emit Approval(_account, msg.sender, allowed[_account][msg.sender]);
_burn(_account, _amount);
}
function burnFrom(address _account, uint256 _amount) public {
_burnFrom(_account, _amount);
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function _transfer(address _to, uint256 _value) internal returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function transfer(address _to, uint256 _value) public returns (bool) {
return _transfer(_to, _value);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function _approve(address _spender, uint256 _value) internal returns (bool) {
require(_spender != address(0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
return _approve(_spender, _value);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens after a specfied amount of time on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
* @param _timeLockTill The time until when this amount cannot be withdrawn
*/
function approveAt(address _spender, uint256 _value, uint _timeLockTill) public returns (bool) {
require(_spender != address(0));
allowed[msg.sender][_spender] = _value;
timeLock[msg.sender][_spender] = _timeLockTill;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFromAt(address _from, address _to, uint256 _value) public returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
require(block.timestamp > timeLock[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool)
{
require(_spender != address(0));
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool)
{
require(_spender != address(0));
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].sub(_subtractedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
| Transfer tokens from one address to another _from address The address which you want to send tokens from _to address The address which you want to transfer to _value uint256 the amount of tokens to be transferred/ | function transferFromAt(address _from, address _to, uint256 _value) public returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
require(block.timestamp > timeLock[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
| 7,322,464 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "./GovernorBravoInterfaces.sol";
contract GovernorBravoDelegate is Initializable,UUPSUpgradeable,GovernorBravoDelegateStorageV2, GovernorBravoEvents {
/// @notice Address of Investee.
mapping (uint256 => address) public investeeDetails;
/// @notice Next investee to support
uint256 public nextInvestee;
/// @notice Next investee to fund
uint256 public nextInvesteeFund;
/// @notice Treasury contract address
address public treasury;
/// @notice The name of this contract
string public constant name = "Cult Governor Bravo";
/// @notice The minimum setable proposal threshold
uint public constant MIN_PROPOSAL_THRESHOLD = 50000e18; // 50,000 Cult
/// @notice The maximum setable proposal threshold
uint public constant MAX_PROPOSAL_THRESHOLD = 6000000000000e18; //6000000000000 Cult
/// @notice The minimum setable voting period
uint public constant MIN_VOTING_PERIOD = 1; // About 24 hours
/// @notice The max setable voting period
uint public constant MAX_VOTING_PERIOD = 80640; // About 2 weeks
/// @notice The min setable voting delay
uint public constant MIN_VOTING_DELAY = 1;
/// @notice The max setable voting delay
uint public constant MAX_VOTING_DELAY = 40320; // About 1 week
/// @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
uint public constant quorumVotes = 1000000000e18; // 1 Billion
/// @notice The maximum number of actions that can be included in a proposal
uint public constant proposalMaxOperations = 10; // 10 actions
/// @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,uint8 support)");
/**
* @notice Used to initialize the contract during delegator constructor
* @param timelock_ The address of the Timelock
* @param dCult_ The address of the dCULT token
* @param votingPeriod_ The initial voting period
* @param votingDelay_ The initial voting delay
* @param proposalThreshold_ The initial proposal threshold
*/
function initialize(address timelock_, address dCult_, uint votingPeriod_, uint votingDelay_, uint proposalThreshold_, address treasury_) public initializer{
require(address(timelock) == address(0), "GovernorBravo::initialize: can only initialize once");
require(timelock_ != address(0), "GovernorBravo::initialize: invalid timelock address");
require(dCult_ != address(0), "GovernorBravo::initialize: invalid dCult address");
require(votingPeriod_ >= MIN_VOTING_PERIOD && votingPeriod_ <= MAX_VOTING_PERIOD, "GovernorBravo::initialize: invalid voting period");
require(votingDelay_ >= MIN_VOTING_DELAY && votingDelay_ <= MAX_VOTING_DELAY, "GovernorBravo::initialize: invalid voting delay");
require(proposalThreshold_ >= MIN_PROPOSAL_THRESHOLD && proposalThreshold_ <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::initialize: invalid proposal threshold");
require(treasury_ != address(0), "GovernorBravo::initialize: invalid treasury address");
timelock = TimelockInterface(timelock_);
dCult = dCultInterface(dCult_);
votingPeriod = votingPeriod_;
votingDelay = votingDelay_;
proposalThreshold = proposalThreshold_;
admin = timelock_;
treasury = treasury_;
}
/**
* @notice Function used to propose a new proposal. Sender must have delegates above the proposal threshold
* @param targets Target addresses for proposal calls
* @param values Eth values for proposal calls
* @param signatures Function signatures for proposal calls
* @param calldatas Calldatas for proposal calls
* @param description String description of the proposal
* @return Proposal id of new proposal
*/
function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) {
// Allow addresses above proposal threshold and whitelisted addresses to propose
require(dCult.checkHighestStaker(0,msg.sender),"GovernorBravo::propose: only top staker");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorBravo::propose: proposal function information arity mismatch");
require(targets.length != 0, "GovernorBravo::propose: must provide actions");
require(targets.length <= proposalMaxOperations, "GovernorBravo::propose: too many actions");
uint latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active, "GovernorBravo::propose: one live proposal per proposer, found an already active proposal");
require(proposersLatestProposalState != ProposalState.Pending, "GovernorBravo::propose: one live proposal per proposer, found an already pending proposal");
}
uint startBlock = add256(block.number, votingDelay);
uint endBlock = add256(startBlock, votingPeriod);
proposalCount++;
Proposal storage newProposal = proposals[proposalCount];
newProposal.id = proposalCount;
newProposal.proposer= msg.sender;
newProposal.eta= 0;
newProposal.targets= targets;
newProposal.values= values;
newProposal.signatures= signatures;
newProposal.calldatas= calldatas;
newProposal.startBlock= startBlock;
newProposal.endBlock= endBlock;
newProposal.forVotes= 0;
newProposal.againstVotes= 0;
newProposal.abstainVotes= 0;
newProposal.canceled= false;
newProposal.executed= false;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description);
return newProposal.id;
}
/**
* @notice Queues a proposal of state succeeded
* @param proposalId The id of the proposal to queue
*/
function queue(uint proposalId) external {
require(state(proposalId) == ProposalState.Succeeded, "GovernorBravo::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++) {
queueOrRevertInternal(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
function queueOrRevertInternal(address target, uint value, string memory signature, bytes memory data, uint eta) internal {
require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorBravo::queueOrRevertInternal: identical proposal action already queued at eta");
timelock.queueTransaction(target, value, signature, data, eta);
}
/**
* @notice Executes a queued proposal if eta has passed
* @param proposalId The id of the proposal to execute
*/
function execute(uint proposalId) external payable {
require(state(proposalId) == ProposalState.Queued, "GovernorBravo::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);
}
/**
* @notice Cancels a proposal only if sender is the proposer
* @param proposalId The id of the proposal to cancel
*/
function cancel(uint proposalId) external {
require(state(proposalId) != ProposalState.Executed, "GovernorBravo::cancel: cannot cancel executed proposal");
Proposal storage proposal = proposals[proposalId];
require(msg.sender == proposal.proposer, "GovernorBravo::cancel: Other user cannot cancel proposal");
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);
}
/**
* @notice Gets actions of a proposal
* @param proposalId the id of the proposal
* @return targets , values, signatures, and calldatas of the proposal actions
*/
function getActions(uint proposalId) external 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);
}
/**
* @notice Gets the receipt for a voter on a given proposal
* @param proposalId the id of proposal
* @param voter The address of the voter
* @return The voting receipt
*/
function getReceipt(uint proposalId, address voter) external view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
/**
* @notice Gets the state of a proposal
* @param proposalId The id of the proposal
* @return Proposal state
*/
function state(uint proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > initialProposalId, "GovernorBravo::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;
}
}
/**
* @notice Cast a vote for a proposal
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
*/
function castVote(uint proposalId, uint8 support) external {
emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), "");
}
/**
* @notice Cast a vote for a proposal with a reason
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
* @param reason The reason given for the vote by the voter
*/
function castVoteWithReason(uint proposalId, uint8 support, string calldata reason) external {
emit VoteCast(msg.sender, proposalId, support, castVoteInternal(msg.sender, proposalId, support), reason);
}
/**
* @notice Cast a vote for a proposal by signature
* @dev External function that accepts EIP-712 signatures for voting on proposals.
*/
function castVoteBySig(uint proposalId, uint8 support, uint8 v, bytes32 r, bytes32 s) external {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainIdInternal(), 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), "GovernorBravo::castVoteBySig: invalid signature");
emit VoteCast(signatory, proposalId, support, castVoteInternal(signatory, proposalId, support), "");
}
/**
* @notice Internal function that caries out voting logic
* @param voter The voter that is casting their vote
* @param proposalId The id of the proposal to vote on
* @param support The support value for the vote. 0=against, 1=for, 2=abstain
* @return The number of votes cast
*/
function castVoteInternal(address voter, uint proposalId, uint8 support) internal returns (uint256) {
require(!dCult.checkHighestStaker(0,msg.sender),"GovernorBravo::castVoteInternal: Top staker cannot vote");
require(state(proposalId) == ProposalState.Active, "GovernorBravo::castVoteInternal: voting is closed");
require(support <= 2, "GovernorBravo::castVoteInternal: invalid vote type");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "GovernorBravo::castVoteInternal: voter already voted");
uint256 votes = dCult.getPastVotes(voter, proposal.startBlock);
if (support == 0) {
proposal.againstVotes = add256(proposal.againstVotes, votes);
} else if (support == 1) {
proposal.forVotes = add256(proposal.forVotes, votes);
} else if (support == 2) {
proposal.abstainVotes = add256(proposal.abstainVotes, votes);
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
return votes;
}
/**
* @notice View function which returns if an account is whitelisted
* @param account Account to check white list status of
* @return If the account is whitelisted
*/
function isWhitelisted(address account) public view returns (bool) {
return (whitelistAccountExpirations[account] > block.timestamp);
}
/**
* @notice Admin function for setting the voting delay
* @param newVotingDelay new voting delay, in blocks
*/
function _setVotingDelay(uint newVotingDelay) external {
require(msg.sender == admin, "GovernorBravo::_setVotingDelay: admin only");
require(newVotingDelay >= MIN_VOTING_DELAY && newVotingDelay <= MAX_VOTING_DELAY, "GovernorBravo::_setVotingDelay: invalid voting delay");
uint oldVotingDelay = votingDelay;
votingDelay = newVotingDelay;
emit VotingDelaySet(oldVotingDelay,votingDelay);
}
/**
* @notice Admin function for setting the new Investee
* @param _investee Investee address
*/
function _setInvesteeDetails(address _investee) external {
require(msg.sender == admin, "GovernorBravo::_setInvesteeDetails: admin only");
require(_investee != address(0), "GovernorBravo::_setInvesteeDetails: zero address");
investeeDetails[nextInvestee] = _investee;
nextInvestee =add256(nextInvestee,1);
emit InvesteeSet(_investee,sub256(nextInvestee,1));
}
/**
* @notice Treasury function for funding the new Investee
*/
function _fundInvestee() external returns(address){
require(msg.sender == treasury, "GovernorBravo::_fundInvestee: treasury only");
require(nextInvesteeFund <= nextInvestee, "GovernorBravo::_fundInvestee: No new investee");
nextInvesteeFund =add256(nextInvesteeFund,1);
emit InvesteeFunded(investeeDetails[sub256(nextInvesteeFund,1)],sub256(nextInvesteeFund,1));
return investeeDetails[sub256(nextInvesteeFund,1)];
}
/**
* @notice Admin function for setting the voting period
* @param newVotingPeriod new voting period, in blocks
*/
function _setVotingPeriod(uint newVotingPeriod) external {
require(msg.sender == admin, "GovernorBravo::_setVotingPeriod: admin only");
require(newVotingPeriod >= MIN_VOTING_PERIOD && newVotingPeriod <= MAX_VOTING_PERIOD, "GovernorBravo::_setVotingPeriod: invalid voting period");
uint oldVotingPeriod = votingPeriod;
votingPeriod = newVotingPeriod;
emit VotingPeriodSet(oldVotingPeriod, votingPeriod);
}
/**
* @notice Admin function for setting the proposal threshold
* @dev newProposalThreshold must be greater than the hardcoded min
* @param newProposalThreshold new proposal threshold
*/
function _setProposalThreshold(uint newProposalThreshold) external {
require(msg.sender == admin, "GovernorBravo::_setProposalThreshold: admin only");
require(newProposalThreshold >= MIN_PROPOSAL_THRESHOLD && newProposalThreshold <= MAX_PROPOSAL_THRESHOLD, "GovernorBravo::_setProposalThreshold: invalid proposal threshold");
uint oldProposalThreshold = proposalThreshold;
proposalThreshold = newProposalThreshold;
emit ProposalThresholdSet(oldProposalThreshold, proposalThreshold);
}
/**
* @notice Admin function for setting the whitelist expiration as a timestamp for an account. Whitelist status allows accounts to propose without meeting threshold
* @param account Account address to set whitelist expiration for
* @param expiration Expiration for account whitelist status as timestamp (if now < expiration, whitelisted)
*/
function _setWhitelistAccountExpiration(address account, uint expiration) external {
require(msg.sender == admin || msg.sender == whitelistGuardian, "GovernorBravo::_setWhitelistAccountExpiration: admin only");
whitelistAccountExpirations[account] = expiration;
emit WhitelistAccountExpirationSet(account, expiration);
}
/**
* @notice Admin function for setting the whitelistGuardian. WhitelistGuardian can cancel proposals from whitelisted addresses
* @param account Account to set whitelistGuardian to (0x0 to remove whitelistGuardian)
*/
function _setWhitelistGuardian(address account) external {
// Check address is not zero
require(account != address(0), "GovernorBravo:_setWhitelistGuardian: zero address");
require(msg.sender == admin, "GovernorBravo::_setWhitelistGuardian: admin only");
address oldGuardian = whitelistGuardian;
whitelistGuardian = account;
emit WhitelistGuardianSet(oldGuardian, whitelistGuardian);
}
/**
* @notice Initiate the GovernorBravo contract
* @dev Admin only. Sets initial proposal id which initiates the contract, ensuring a continuous proposal id count
* @param governorAlpha The address for the Governor to continue the proposal id count from
*/
function _initiate(address governorAlpha) external {
require(msg.sender == admin, "GovernorBravo::_initiate: admin only");
require(initialProposalId == 0, "GovernorBravo::_initiate: can only initiate once");
proposalCount = GovernorAlpha(governorAlpha).proposalCount();
initialProposalId = proposalCount;
timelock.acceptAdmin();
emit GovernanceInitiated(governorAlpha);
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
*/
function _setPendingAdmin(address newPendingAdmin) external {
// Check address is not zero
require(newPendingAdmin != address(0), "GovernorBravo:_setPendingAdmin: zero address");
// Check caller = admin
require(msg.sender == admin, "GovernorBravo:_setPendingAdmin: admin only");
// 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);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
*/
function _acceptAdmin() external {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
require(msg.sender == pendingAdmin && msg.sender != address(0), "GovernorBravo:_acceptAdmin: pending admin only");
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
}
/**
* @notice Accepts Admin for timelock of admin rights.
* @dev Admin function for transferring admin to accept role and update admin
*/
function _AcceptTimelockAdmin() external {
timelock.acceptAdmin();
}
function _authorizeUpgrade(address) internal view override {
require(admin == msg.sender, "Only admin can upgrade implementation");
}
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 getChainIdInternal() internal view returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.2;
pragma experimental ABIEncoderV2;
contract GovernorBravoEvents {
/// @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
/// @param voter The address which casted a vote
/// @param proposalId The proposal id which was voted on
/// @param support Support value for the vote. 0=against, 1=for, 2=abstain
/// @param votes Number of votes which were cast by the voter
/// @param reason The reason given for the vote by the voter
event VoteCast(address indexed voter, uint proposalId, uint8 support, uint votes, string reason);
/// @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);
/// @notice An event emitted when the voting delay is set
event VotingDelaySet(uint oldVotingDelay, uint newVotingDelay);
/// @notice An event emitted when the voting period is set
event VotingPeriodSet(uint oldVotingPeriod, uint newVotingPeriod);
/// @notice Emitted when implementation is changed
event NewImplementation(address oldImplementation, address newImplementation);
/// @notice Emitted when proposal threshold is set
event ProposalThresholdSet(uint oldProposalThreshold, uint newProposalThreshold);
/// @notice Emitted when pendingAdmin is changed
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/// @notice Emitted when pendingAdmin is accepted, which means admin is updated
event NewAdmin(address oldAdmin, address newAdmin);
/// @notice Emitted when whitelist account expiration is set
event WhitelistAccountExpirationSet(address account, uint expiration);
/// @notice Emitted when the whitelistGuardian is set
event WhitelistGuardianSet(address oldGuardian, address newGuardian);
/// @notice Emitted when the new Investee is added.
event InvesteeSet(address investee, uint256 id);
/// @notice Emitted when the Investee is funded
event InvesteeFunded(address investee, uint256 id);
/// @notice Alpha contract initiated. For initiating already deployed governance alpha
event GovernanceInitiated(address governanceAddress);
}
contract GovernorBravoDelegatorStorage {
/// @notice Administrator for this contract
address public admin;
/// @notice Pending administrator for this contract
address public pendingAdmin;
/// @notice Active brains of Governor
address public implementation;
}
/**
* @title Storage for Governor Bravo Delegate
* @notice For future upgrades, do not change GovernorBravoDelegateStorageV1. Create a new
* contract which implements GovernorBravoDelegateStorageV1 and following the naming convention
* GovernorBravoDelegateStorageVX.
*/
contract GovernorBravoDelegateStorageV1 is GovernorBravoDelegatorStorage {
/// @notice The delay before voting on a proposal may take place, once proposed, in blocks
uint public votingDelay;
/// @notice The duration of voting on a proposal, in blocks
uint public votingPeriod;
/// @notice The number of votes required in order for a voter to become a proposer
uint public proposalThreshold;
/// @notice Initial proposal id set at become
uint public initialProposalId;
/// @notice The total number of proposals
uint public proposalCount;
/// @notice The address of the cult Protocol Timelock
TimelockInterface public timelock;
/// @notice The address of the cult governance token
dCultInterface public dCult;
/// @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;
struct Proposal {
// Unique id for looking up a proposal
uint id;
// Creator of the proposal
address proposer;
// The timestamp that the proposal will be available for execution, set once the vote succeeds
uint eta;
// the ordered list of target addresses for calls to be made
address[] targets;
// The ordered list of values (i.e. msg.value) to be passed to the calls to be made
uint[] values;
// The ordered list of function signatures to be called
string[] signatures;
// The ordered list of calldata to be passed to each call
bytes[] calldatas;
// The block at which voting begins: holders must delegate their votes prior to this block
uint startBlock;
// The block at which voting ends: votes must be cast prior to this block
uint endBlock;
// Current number of votes in favor of this proposal
uint forVotes;
// Current number of votes in opposition to this proposal
uint againstVotes;
// Current number of votes for abstaining for this proposal
uint abstainVotes;
// Flag marking whether the proposal has been canceled
bool canceled;
// Flag marking whether the proposal has been executed
bool executed;
// Receipts of ballots for the entire set of voters
mapping (address => Receipt) receipts;
}
/// @notice Ballot receipt record for a voter
struct Receipt {
// Whether or not a vote has been cast
bool hasVoted;
// Whether or not the voter supports the proposal or abstains
uint8 support;
// The number of votes the voter had, which were cast
uint256 votes;
}
/// @notice Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
}
contract GovernorBravoDelegateStorageV2 is GovernorBravoDelegateStorageV1 {
/// @notice Stores the expiration of account whitelist status as a timestamp
mapping (address => uint) public whitelistAccountExpirations;
/// @notice Address which manages whitelisted proposals and whitelist accounts
address public whitelistGuardian;
}
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 dCultInterface {
/// @notice Get the past vote of the users
function getPastVotes(address account, uint blockNumber) external view returns (uint256);
/// @notice Top staker
function checkHighestStaker(uint256 _pid, address user) external returns (bool);
}
interface GovernorAlpha {
/// @notice The total number of proposals
function proposalCount() external returns (uint);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
} | Treasury function for funding the new Investee/ | function _fundInvestee() external returns(address){
require(msg.sender == treasury, "GovernorBravo::_fundInvestee: treasury only");
require(nextInvesteeFund <= nextInvestee, "GovernorBravo::_fundInvestee: No new investee");
nextInvesteeFund =add256(nextInvesteeFund,1);
emit InvesteeFunded(investeeDetails[sub256(nextInvesteeFund,1)],sub256(nextInvesteeFund,1));
return investeeDetails[sub256(nextInvesteeFund,1)];
}
| 13,651,924 |
./partial_match/1/0x43833f0C2025dFA80b5556574FAA11CBf7F3f4eB/sources/WUSDA.sol | Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}./ | function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
return toString(value);
return store;
}
}
| 2,589,416 |
// SPDX-License-Identifier: None
// HungryBunz Implementation V1
pragma solidity ^0.8.0;
import "./Ownable.sol";
import "./PaymentSplitter.sol";
import "./ERC721.sol";
import "./ECDSA.sol";
import "./Strings.sol";
import "./Initializable.sol";
contract OwnableDelegateProxy { }
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
interface ISnax {
function computeMultiplier(address requester, bytes16 targetStats, uint16[] memory team) external view returns (uint256);
function feed(bytes16 stats, uint256 wholeBurn) external view returns (bytes16);
}
interface IItem {
function applyProperties(bytes32 properties, uint16 item) external view returns (bytes32);
}
interface nom {
function burn(address account, uint256 amount) external;
function unstake(uint16[] memory tokenIds, address targetAccount) external;
}
interface IMetadataGen {
function generateStats(address requester, uint16 newTokenId, uint32 password) external view returns (bytes16);
function generateAttributes(address requester, uint16 newTokenId, uint32 password) external view returns (bytes16);
}
interface IMetadataRenderer {
function renderMetadata(uint16 tokenId, bytes16 atts, bytes16 stats) external view returns (string memory);
}
interface IEvolve {
function evolve(uint8 next1of1, uint16 burntId, address owner, bytes32 t1, bytes32 t2) external view returns(bytes32);
}
contract HungryBunz is Initializable, PaymentSplitter, Ownable, ERC721 {
//******************************************************
//CRITICAL CONTRACT PARAMETERS
//******************************************************
using ECDSA for bytes32;
using Strings for uint256;
bool _saleStarted;
bool _saleEnd;
bool _metadataRevealed;
bool _transferPaused;
bool _bypassMintAuth;
uint8 _season; //Defines rewards season
uint8 _1of1Index; //Next available 1 of 1
uint16 _totalSupply;
uint16 _maxSupply;
uint256 _maxPerWallet;
uint256 _baseMintPrice;
uint256 _nameTagPrice;
//Address rather than interface because this is used as an address
//for sender checks more often than used as interface.
address _nomContractAddress;
//Address rather than interface because this is used as an address
//for sender checks more often than used as interface.
address _xLayerGateway;
address _openSea;
address _signerAddress; //Public address for mint auth signature
IItem items;
ISnax snax;
IMetadataRenderer renderer;
IMetadataGen generator;
IEvolve _evolver;
ProxyRegistry _osProxies;
//******************************************************
//GAMEPLAY MECHANICS
//******************************************************
uint8 _maxRank; //Maximum rank setting to allow additional evolutions over time...
mapping(uint8 => mapping(uint8 => uint16)) _evolveThiccness; //Required thiccness total to evolve by current rank
mapping(uint8 => uint8) _1of1Allotted; //Allocated 1 of 1 pieces per season
mapping(uint8 => bool) _1of1sOnThisLayer; //Permit 1/1s on this layer and season.
mapping(uint8 => uint8) _maxStakeRankBySeason;
//******************************************************
//ANTI BOT AND FAIR LAUNCH HASH TABLES AND ARRAYS
//******************************************************
mapping(address => uint256) tokensMintedByAddress; //Tracks total NFTs minted to limit individual wallets.
//******************************************************
//METADATA HASH TABLES
//******************************************************
//Bools stored as uint256 to shave a few units off gas fees.
mapping(uint16 => bytes32) metadataById; //Stores critical metadata by ID
mapping(uint16 => bytes32) _lockedTokens; //Tracks tokens locked for staking
mapping(uint16 => uint256) _inactiveOnThisChain; //Tracks which tokens are active on current chain
mapping(bytes16 => uint256) _usedCombos; //Stores attribute combo hashes to guarantee uniqueness
mapping(uint16 => string) namedBunz; //Stores names for bunz
//******************************************************
//CONTRACT CONSTRUCTOR AND INITIALIZER FOR PROXY
//******************************************************
constructor() {
//Initialize ownable on implementation
//to prevent any misuse of implementation
//contract.
ownableInit();
}
function initHungryBunz (
address[] memory payees,
uint256[] memory paymentShares
) external initializer
{
//Require to prevent users from initializing
//implementation contract
require(owner() == address(0) || owner() == msg.sender,
"No.");
ownableInit();
initPaymentSplitter(payees, paymentShares);
initERC721("HungryBunz", "BUNZ");
_maxRank = 2;
_maxStakeRankBySeason[0] = 1;
_transferPaused = true;
_signerAddress = 0xF658480075BA1158f12524409066Ca495b54b0dD;
_baseMintPrice = 0.06 ether;
_maxSupply = 8888;
_maxPerWallet = 5;
_nameTagPrice = 200 * 10**18;
_evolveThiccness[0][1] = 5000;
_evolveThiccness[0][2] = 30000;
//Guesstimate on targets for season 1
_evolveThiccness[1][1] = 15000;
_evolveThiccness[1][2] = 30000;
_1of1Index = 1; //Initialize at 1
//WL Opensea Proxies for Cheaper Trading
_openSea = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
_osProxies = ProxyRegistry(_openSea);
}
//******************************************************
//OVERRIDES TO HANDLE CONFLICTS BETWEEN IMPORTS
//******************************************************
function _burn(uint256 tokenId) internal virtual override(ERC721) {
ERC721._burn(tokenId);
delete metadataById[uint16(tokenId)];
_totalSupply -= 1;
}
//Access to ERC721 implementation for use within app contracts.
function applicationOwnerOf(uint256 tokenId) public view returns (address) {
return ERC721.ownerOf(tokenId);
}
//Override ownerOf to accomplish lower cost alternative to lock tokens for staking.
function ownerOf(uint256 tokenId) public view virtual override(ERC721) returns (address) {
address owner = ERC721.ownerOf(tokenId);
if (lockedForStaking(tokenId)) {
owner = address(uint160(owner) - 1);
} else if (_inactiveOnThisChain[uint16(tokenId)] == 1) {
owner = address(0);
}
return owner;
}
//Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
function isApprovedForAll(
address owner,
address operator
)
public
view
override(ERC721)
returns (bool)
{
if (address(_osProxies.proxies(owner)) == operator) {
return true;
}
return ERC721.isApprovedForAll(owner, operator);
}
//Override for simulated transfers and burns.
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual override(ERC721) returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
//Transfers not allowed while inactive on this chain. Transfers
//potentially allowed when spender is foraging contract and
//token is locked for staking.
return ((spender == owner || getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender) || spender == address(this)) &&
(!lockedForStaking(tokenId) || spender == _nomContractAddress) &&
_inactiveOnThisChain[uint16(tokenId)] == 0 && !_transferPaused);
}
//******************************************************
//OWNER ONLY FUNCTIONS TO CONNECT CHILD CONTRACTS.
//******************************************************
function ccNom(address contractAddress) public onlyOwner {
//Not cast to interface as this will need to be cast to address
//more often than not.
_nomContractAddress = contractAddress;
}
function ccGateway(address contractAddress) public onlyOwner {
//Notably not cast to interface because this contract never calls
//functions on gateway.
_xLayerGateway = contractAddress;
}
function ccSnax(ISnax contractAddress) public onlyOwner {
snax = contractAddress;
}
function ccItems(IItem contractAddress) public onlyOwner {
items = contractAddress;
}
function ccGenerator(IMetadataGen contractAddress) public onlyOwner {
generator = contractAddress;
}
function ccRenderer(IMetadataRenderer newRenderer) public onlyOwner {
renderer = newRenderer;
}
function ccEvolution(IEvolve newEvolver) public onlyOwner {
_evolver = newEvolver;
}
function getInterfaces() external view returns (bytes memory) {
return abi.encodePacked(
_nomContractAddress,
_xLayerGateway,
address(snax),
address(items),
address(generator),
address(renderer),
address(_evolver)
);
}
//******************************************************
//OWNER ONLY FUNCTIONS TO MANAGE CRITICAL PARAMETERS
//******************************************************
function startSale() public onlyOwner {
require(_saleEnd == false, "Cannot restart sale.");
_saleStarted = true;
}
function endSale() public onlyOwner {
_saleStarted = false;
_saleEnd = true;
}
function enableTransfer() public onlyOwner {
_transferPaused = false;
}
//Emergency transfer pause to prevent innapropriate transfer of tokens.
function pauseTransfer() public onlyOwner {
_transferPaused = true;
}
function changeWalletLimit(uint16 newLimit) public onlyOwner {
//Set to 1 higher than limit for cheaper less than check!
_maxPerWallet = newLimit;
}
function reduceSupply(uint16 newSupply) public onlyOwner {
require (newSupply < _maxSupply,
"Can only reduce supply");
require (newSupply > _totalSupply,
"Cannot reduce below current!");
_maxSupply = newSupply;
}
function update1of1Index(uint8 oneOfOneIndex) public onlyOwner {
//This function is provided exclusively so that owner may
//update 1of1Index to facilitate creation of 1of1s on L2
//if this is deemed to be a feature of interest to community
_1of1Index = oneOfOneIndex;
}
function startNewSeason(uint8 oneOfOneCount, bool enabledOnThisLayer, uint8 maxStakeRank) public onlyOwner {
//Require all 1 of 1s for current season claimed before
//starting a new season. L2 seasons will require sync.
require(_1of1Index == _1of1Allotted[_season],
"No.");
_season++;
_1of1Allotted[_season] = oneOfOneCount + _1of1Index;
_1of1sOnThisLayer[_season] = enabledOnThisLayer;
_maxStakeRankBySeason[_season] = maxStakeRank;
}
function addRank(uint8 newRank) public onlyOwner { //Used to enable third, fourth, etc. evolution levels.
_maxRank = newRank;
}
function updateEvolveThiccness(uint8 rank, uint8 season, uint16 threshold) public onlyOwner {
//Rank as current. E.G. (1, 10000) sets threshold to evolve to rank 2
//to 10000 pounds or thiccness points
_evolveThiccness[season][rank] = threshold;
}
function setPriceToName(uint256 newPrice) public onlyOwner {
_nameTagPrice = newPrice;
}
function reveal() public onlyOwner {
_metadataRevealed = true;
}
function bypassMintAuth() public onlyOwner {
_bypassMintAuth = true;
}
//******************************************************
//VIEWS FOR CRITICAL INFORMATION
//******************************************************
function baseMintPrice() public view returns (uint256) {
return _baseMintPrice;
}
function totalMintPrice(uint8 numberOfTokens) public view returns (uint256) {
return _baseMintPrice * numberOfTokens;
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function maxSupply() public view returns (uint256) {
return _maxSupply;
}
//******************************************************
//ANTI-BOT PASSWORD HANDLERS
//******************************************************
function hashTransaction(address sender, uint256 qty, bytes8 salt) private pure returns(bytes32) {
bytes32 hash = keccak256(abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
keccak256(abi.encodePacked(sender, qty, salt)))
);
return hash;
}
function matchAddresSigner(bytes32 hash, bytes memory signature) public view returns(bool) {
return (_signerAddress == hash.recover(signature));
}
//******************************************************
//TOKENURI OVERRIDE RELOCATED TO BELOW UTILITY FUNCTIONS
//******************************************************
function tokenURI(uint256 tokenId) public view returns (string memory) {
require(_exists(tokenId), "Token Doesn't Exist");
//Heavy lifting is done by rendering contract.
bytes16 atts = serializeAtts(uint16(tokenId));
bytes16 stats = serializeStats(uint16(tokenId));
return renderer.renderMetadata(uint16(tokenId), atts, stats);
}
function _writeSerializedAtts(uint16 tokenId, bytes16 newAtts) internal {
bytes16 currentStats = serializeStats(tokenId);
metadataById[tokenId] = bytes32(abi.encodePacked(newAtts, currentStats));
}
function writeSerializedAtts(uint16 tokenId, bytes16 newAtts) external {
require(msg.sender == _xLayerGateway,
"Not Gateway!");
_writeSerializedAtts(tokenId, newAtts);
}
function serializeAtts(uint16 tokenId) public view returns (bytes16) {
return _metadataRevealed ? bytes16(metadataById[tokenId]) : bytes16(0);
}
function _writeSerializedStats(uint16 tokenId, bytes16 newStats) internal {
bytes16 currentAtts = serializeAtts(tokenId);
metadataById[tokenId] = bytes32(abi.encodePacked(currentAtts, newStats));
}
function writeSerializedStats(uint16 tokenId, bytes16 newStats) external {
require(msg.sender == _xLayerGateway,
"Not Gateway!");
_writeSerializedStats(tokenId, newStats);
}
function serializeStats(uint16 tokenId) public view returns (bytes16) {
return _metadataRevealed ? bytes16(metadataById[tokenId] << 128) : bytes16(0);
}
function propertiesBytes(uint16 tokenId) external view returns(bytes32) {
return metadataById[tokenId];
}
//******************************************************
//STAKING VIEWS
//******************************************************
function lockedForStaking (uint256 tokenId) public view returns(bool) {
return uint8(bytes1(_lockedTokens[uint16(tokenId)])) == 1;
}
//Check stake checks both staking status and ownership.
function checkStake (uint16 tokenId) external view returns (address) {
return lockedForStaking(tokenId) ? applicationOwnerOf(tokenId) : address(0);
}
//Returns staking timestamp
function stakeStart (uint16 tokenId) public view returns(uint248) {
return uint248(bytes31(_lockedTokens[tokenId] << 8));
}
//******************************************************
//STAKING LOCK / UNLOCK AND TIMESTAMP FUNCTION
//******************************************************
function updateStakeStart (uint16 tokenId, uint248 newTime) external {
uint8 stakeStatus = uint8(bytes1(_lockedTokens[tokenId]));
_lockedTokens[tokenId] = bytes32(abi.encodePacked(stakeStatus, newTime));
}
function lockForStaking (uint16 tokenId) external {
//Nom contract performs owner of check to prevent malicious locking
require(msg.sender == _nomContractAddress,
"Unauthorized");
require(!lockedForStaking(tokenId),
"Already locked!");
//Metadata byte 16 is rank, 17 is season.
require(_maxStakeRankBySeason[uint8(metadataById[tokenId][17])] >= uint8(metadataById[tokenId][16]),
"Cannot Stake");
bytes31 currentTimestamp = bytes31(_lockedTokens[tokenId] << 8);
//Food coma period will persist after token transfer.
uint248 stakeTimestamp = uint248(currentTimestamp) < block.timestamp ?
uint248(block.timestamp) : uint248(currentTimestamp);
_lockedTokens[tokenId] = bytes32(abi.encodePacked(uint8(1), stakeTimestamp));
//Event with ownerOf override clears secondary listings.
emit Transfer(applicationOwnerOf(tokenId),
address(uint160(applicationOwnerOf(tokenId)) - 1),
tokenId);
}
function unlock (uint16 tokenId, uint248 newTime) external {
//Nom contract performs owner of check to prevent malicious unlocking
require(msg.sender == _nomContractAddress,
"Unauthorized");
require(lockedForStaking(tokenId),
"Not locked!");
_lockedTokens[tokenId] = bytes32(abi.encodePacked(uint8(0), newTime));
//Event with ownerOf override restores token in marketplace accounts
emit Transfer(address(uint160(applicationOwnerOf(tokenId)) - 1),
applicationOwnerOf(tokenId),
tokenId);
}
//******************************************************
//L2 FUNCTIONALITY
//******************************************************
function setInactiveOnThisChain(uint16 tokenId) external {
//This can only be called by the gateway contract to prevent exploits.
//Gateway will check ownership, and setting inactive is a pre-requisite
//to issuing the message to mint token on the other chain. By verifying
//that we aren't trying to re-teleport here, we save back and forth to
//check the activity status of the token on the gateway contract.
require(msg.sender == _xLayerGateway,
"Not Gateway!");
require(_inactiveOnThisChain[tokenId] == 0,
"Already inactive!");
//Unstake token to mitigate very minimal exploit by staking then immediately
//bridging to another layer to accrue slightly more tokens in a given time.
uint16[] memory lockedTokens = new uint16[](1);
lockedTokens[0] = tokenId;
nom(_nomContractAddress).unstake(lockedTokens, applicationOwnerOf(tokenId));
_inactiveOnThisChain[tokenId] = 1;
//Event with ownerOf override clears secondary listings.
emit Transfer(applicationOwnerOf(tokenId), address(0), tokenId);
}
function setActiveOnThisChain(uint16 tokenId, bytes memory metadata, address sender) external {
require(msg.sender == _xLayerGateway,
"Not Gateway!");
if (_exists(uint256(tokenId))) {
require(_inactiveOnThisChain[tokenId] == 1,
"Already active");
}
_inactiveOnThisChain[tokenId] = 0;
if(!_exists(uint256(tokenId))) {
_safeMint(sender, tokenId);
} else {
address localOwner = applicationOwnerOf(tokenId);
if (localOwner != sender) {
//This indicates a transaction occurred
//on the other layer. Transfer.
safeTransferFrom(localOwner, sender, tokenId);
}
}
metadataById[tokenId] = bytes32(metadata);
uint16 burntId = uint16(bytes2(abi.encodePacked(metadata[14], metadata[15])));
if (_exists(uint256(burntId))) {
_burn(burntId);
}
//Event with ownerOf override restores token in marketplace accounts
emit Transfer(address(0), applicationOwnerOf(tokenId), tokenId);
}
//******************************************************
//MINT FUNCTIONS
//******************************************************
function _mintToken(address to, uint32 password, uint16 newId) internal {
//Generate data in mint function to reduce calls. Cost 40k.
//While loop and additional write operation is necessary
//evil to prevent duplicates.
bytes16 newAtts;
while(newAtts == 0 || _usedCombos[newAtts] == 1) {
newAtts = generator.generateAttributes(to, newId, password);
password++;
}
_usedCombos[newAtts] = 1;
bytes16 newStats = generator.generateStats(to, newId, password);
metadataById[newId] = bytes32(abi.encodePacked(newAtts, newStats));
//Cost 20k.
_safeMint(to, newId);
}
function publicAccessMint(uint8 numberOfTokens, bytes memory signature, bytes8 salt)
public
payable
{
//Between the use of msg.sender in the tx hash for purchase authorization,
//and the requirements for wallet limiter, saving the salt is an undesirable
//gas add. Users may re-use the same hash for multiple Txs if they prefer,
//instead of maxing out their mint the first time.
bytes32 txHash = hashTransaction(msg.sender, numberOfTokens, salt);
require(_saleStarted,
"Sale not live.");
if (!_bypassMintAuth) {
require(matchAddresSigner(txHash, signature),
"Unauthorized!");
}
require((numberOfTokens + tokensMintedByAddress[msg.sender] < _maxPerWallet),
"Exceeded max mint.");
require(_totalSupply + numberOfTokens <= _maxSupply,
"Not enough supply");
require(msg.value >= totalMintPrice(numberOfTokens),
"Insufficient funds.");
//Set tokens minted by address before calling internal mint
//to revert on attempted reentry to bypass wallet limit.
uint16 offset = _totalSupply;
tokensMintedByAddress[msg.sender] += numberOfTokens;
_totalSupply += numberOfTokens; //Set once to save a few k gas
for (uint i = 0; i < numberOfTokens; i++) {
offset++;
_mintToken(msg.sender, uint32(bytes4(signature)), offset);
}
}
//******************************************************
//BURN NOM FOR STAT BOOSTS
//******************************************************
//Team must be passed as an argument since gas fees to enumerate a
//user's collection with Enumerable or similar are too high to justify.
//Sanitization of the input array is done on the snax contract.
function consume(uint16 consumer, uint256 burn, uint16[] memory team) public {
//We only check that a token is active on this chain.
//You may burn NOM to boost friends' NFTs if you wish.
//You may also burn NOM to feed currently staked Bunz
require(_inactiveOnThisChain[consumer] == 0,
"Not active on this chain!");
//Attempt to burn requisite amount of NOM. Will revert if
//balance insufficient. This contract is approved burner
//on NOM contract by default.
nom(_nomContractAddress).burn(msg.sender, burn);
uint256 wholeBurnRaw = burn / 10 ** 18; //Convert to integer units.
bytes16 currentStats = serializeStats(consumer);
//Computation done in snax contract for upgradability. Stack depth
//limits require us to break the multiplier calc out into a separate
//call to the snax contract.
uint256 multiplier = snax.computeMultiplier(msg.sender, currentStats, team); //Returns BPS
uint256 wholeBurn = (wholeBurnRaw * multiplier) / 10000;
//Snax contract will take a tokenId, retrieve critical stats
//and then modify stats, primarily thiccness, based on total
//tokens burned. Output bytes are written back to struct.
bytes16 transformedStats = snax.feed(currentStats, wholeBurn);
_writeSerializedStats(consumer, transformedStats);
}
//******************************************************
//ATTACH ITEM
//******************************************************
function attach(uint16 base, uint16 consumableItem) public {
//This function will call another function on the item
//NFT contract which will burn an item, apply its properties
//to the base NFT, and return these values.
require(msg.sender == applicationOwnerOf(base),
"Don't own this token"); //Owner of check performed in item contract
require(_inactiveOnThisChain[base] == 0,
"Not active on this chain!");
bytes32 transformedProperties = items.applyProperties(metadataById[base], consumableItem);
metadataById[base] = transformedProperties;
}
//******************************************************
//NAME BUNZ
//******************************************************
function getNameTagPrice() public view returns(uint256) {
return _nameTagPrice;
}
function name(uint16 tokenId, string memory newName) public {
require(msg.sender == applicationOwnerOf(tokenId),
"Don't own this token"); //Owner of check performed in item contract
require(_inactiveOnThisChain[tokenId] == 0,
"Not active on this chain!");
//Attempt to burn requisite amount of NOM. Will revert if
//balance insufficient. This contract is approved burner
//on NOM contract by default.
nom(_nomContractAddress).burn(msg.sender, _nameTagPrice);
namedBunz[tokenId] = newName;
}
//Hook for name not presently used in metadata render contract.
//Provided for future use.
function getTokenName(uint16 tokenId) public view returns(string memory) {
return namedBunz[tokenId];
}
//******************************************************
//PRESTIGE SYSTEM
//******************************************************
function prestige(uint16[] memory tokenIds) public {
//This is ugly, but the gas savings elsewhere justify this spaghetti.
for(uint16 i = 0; i < tokenIds.length; i++) {
if (uint8(metadataById[tokenIds[i]][17]) != _season) {
bytes16 currentAtts = serializeAtts(tokenIds[i]);
bytes12 currentStats = bytes12(metadataById[tokenIds[i]] << 160);
//Atts and rank (byte 16) stay the same. Season (byte 17) and thiccness (bytes 18 and 19) change.
metadataById[tokenIds[i]] = bytes32(abi.encodePacked(
currentAtts, metadataById[tokenIds[i]][16], bytes1(_season), bytes2(0), currentStats
));
}
}
}
//******************************************************
//EVOLUTION MECHANISM
//******************************************************
function evolve(uint16 firstToken, uint16 secondToken) public {
uint8 rank = uint8(metadataById[firstToken][16]);
require((rank == uint8(metadataById[secondToken][16])) && (rank < _maxRank),
"Can't evolve these bunz");
uint8 season1 = uint8(metadataById[firstToken][17]);
uint8 season = uint8(metadataById[secondToken][17]) > season1 ? uint8(metadataById[secondToken][17]) : season1;
uint16 thiccness = uint16(bytes2(abi.encodePacked(metadataById[firstToken][18], metadataById[firstToken][19]))) +
uint16(bytes2(abi.encodePacked(metadataById[secondToken][18], metadataById[secondToken][19])));
//ownerOf will return the 0 address if tokens are on another layer, and address -1 if staked.
//Forcing unstake before evolve does not add enough to gas fees to justify the complex
//logic to gracefully handle token burn while staked without introducing possible attack
//vectors.
require(ownerOf(firstToken) == msg.sender && ownerOf(secondToken) == msg.sender,
"Not called by owner.");
require(ownerOf(firstToken) == applicationOwnerOf(firstToken),
"Unlucky");
require(thiccness >= _evolveThiccness[season][rank],
"Not thicc enough.");
//Below logic uses the higher season of the two tokens, since otherwise
//tying this to global _season would allow users to earn 1/1s without
//prestiging.
uint8 next1of1 = (_1of1Index <= _1of1Allotted[season]) && _1of1sOnThisLayer[season] ? _1of1Index : 0;
bytes32 evolvedToken = _evolver.evolve(next1of1, secondToken, msg.sender, metadataById[firstToken], metadataById[secondToken]);
if (uint8(evolvedToken[8]) != 0) {
_1of1Index++;
}
metadataById[firstToken] = evolvedToken;
_burn(secondToken);
}
} | Nom contract performs owner of check to prevent malicious unlockingEvent with ownerOf override restores token in marketplace accounts | function unlock (uint16 tokenId, uint248 newTime) external {
require(msg.sender == _nomContractAddress,
"Unauthorized");
require(lockedForStaking(tokenId),
"Not locked!");
_lockedTokens[tokenId] = bytes32(abi.encodePacked(uint8(0), newTime));
emit Transfer(address(uint160(applicationOwnerOf(tokenId)) - 1),
applicationOwnerOf(tokenId),
tokenId);
}
| 12,149,234 |
pragma solidity >=0.4.22 <0.7.0;
// pragma experimental ABIEncoderV2; enable experimental features (required for returning structs)
contract Lease {
uint public rent;
uint public deposit;
// uint public showingfee;
uint public showingfeepercent;
uint servicefeepercent;
/* Combination of zip code, building number, and apt number*/
string public apt;
address payable public landlord;
address payable public tenant;
address payable public us;
// address payable public next;
address payable public previous; // the CONTRACT address of the previous contract
enum State {Created, Started, Terminated}
State public state;
constructor(
uint _rent,
uint _deposit,
string memory _apt,
uint _servicefeepercent,
uint _showingfeepercent )
public {
// made into constructor
rent = _rent;
deposit = _deposit;
apt = _apt;
us = msg.sender;
servicefeepercent = _servicefeepercent;
showingfeepercent = _showingfeepercent;
}
// modifier require(bool _condition) {
// if (!_condition) throw;
// _;
// }
modifier onlyLandlord() {
require(landlord == msg.sender, "You must be the landlord to perform this function.");
_;
}
modifier onlyTenant() {
require(tenant == msg.sender, "You must be the tenant to perform this function.");
_;
}
modifier onlyUs() {
require(us == msg.sender, "You must be the service provider to perform this function.");
_;
}
modifier inState(State _state) {
require(state == _state, "This contract is not active.");
_;
}
/* We also have some getters so that we can read the values
from the blockchain at any time */
// added public to each function
/*
function getPaidRents() public returns (PaidRent[] memory) { // had to turn on experimental features to return struct
return paidrents;
}
function getApt() public view returns (string memory) {
return apt;
}
function getLandlord() public view returns (address) {
return landlord;
}
function getTenant() public view returns (address) {
return tenant;
}
function getRent() public view returns (uint) {
return rent;
}
function getContractCreated() public view returns (uint) {
return createdTimestamp;
}
function getContractAddress() public view returns (address) {
return address(this);
}
function getState() public returns (State) {
return state;
}
*/
/* Events for DApps to listen to */
event landlordConfirmed();
event tenantConfirmed();
event paidRent();
event paidDeposit();
event returnedDeposit();
event paidShowingFee();
event contractTerminated();
/* Confirm the lease agreement as tenant*/
function confirmAgreementlandlord() public
// inState(State.Created)
{
require(msg.sender != tenant || msg.sender != us); // moved into function
emit landlordConfirmed(); // added emit
landlord = msg.sender;
state = State.Started;
}
function confirmAgreementtenant() public
// inState(State.Created)
{
require(msg.sender != landlord || msg.sender != us); // moved into function
emit tenantConfirmed(); // added emit
tenant = msg.sender;
state = State.Started;
}
// State started should be when both parties agree to the confirm
function setPrevious(address payable _previous) public payable
onlyLandlord
inState(State.Started)
{
previous = _previous;
}
function payFirstRent() public payable
onlyTenant
inState(State.Started)
{
require(msg.value == rent); // moved into function
emit paidRent(); // added emit
previous.transfer(msg.value * showingfeepercent/100); // to previous contract to pay showingfee
landlord.transfer(msg.value - (msg.value * showingfeepercent/100) - (msg.value * servicefeepercent/100));
us.transfer(msg.value * servicefeepercent/100);
}
function payRent() public payable
onlyTenant
inState(State.Started)
{
require(msg.value == rent); // moved into function
emit paidRent(); // added emit
landlord.transfer(msg.value); // changed send to transfer
//uint total;
}
function payDeposit() public payable
onlyTenant
inState(State.Started)
/// need to make it so that it can only be paid once
{
require(msg.value == deposit);
emit paidDeposit();
}
function returnDeposit(uint amount) public
onlyLandlord
inState(State.Started)
{
require(amount == deposit, "Please return the full security deposit");
emit returnedDeposit();
tenant.transfer(amount);
}
/// require(unlock_time < now, "Account is locked");
///
/// if (amount > address(this).balance / 3) {
/// unlock_time = now + 24 hours;
/// }
/*
function payShowingFee() public payable
onlyLandlord
inState(State.Started)
{
require(msg.value == showingFee);
emit paidShowingFee();
tenant.transfer(msg.value);
}
*/
// OR
function requestShowingFee() public
onlyTenant
inState(State.Started) //make so that this refers to the next tenant's contract
{
emit paidShowingFee();
tenant.transfer(rent / 2);
}
/* Terminate the contract so the tenant can’t pay rent anymore,
and the contract is terminated */
function terminateContract() public
onlyLandlord
{
// require event: paidDeposit to be true and paidrents to = rent *12
emit contractTerminated();
landlord.transfer(address(this).balance); //changed to address.this -- changed to transfer
/* If there is any value on the
contract send it to the landlord*/
state = State.Terminated;
}
function getbalance() public view returns (uint) {
return address(this).balance;
}
function () payable external {} // required so that the next contract can pay this contract
} | required so that the next contract can pay this contract | function () payable external {} | 1,046,389 |
pragma solidity ^0.4.4;
contract Meetup {
/**
* NOTES
*
* "organizer" is the person creating meetup.
*/
/**
* Meetup Events
*/
event _MeetupCreated(uint indexed id);
event _MeetupUpdated(uint indexed id);
struct MeetupPost {
uint id;
address organizer;
string ipfsHash;
}
/**
* meetups map
*
* structure
* meetups[organizer][id] => ipfs hash
*
* example
* meetups[0x123...abc][1] => Qm123...abc
*/
mapping (uint => MeetupPost) meetups;
/**
* Latest sequential meetup ID
*/
uint public seqId = 0;
/**
* Contract owner
*/
address owner;
/**
* Constructor
*/
function Meetup() {
owner = msg.sender;
}
/**
* Change contract owner
*/
function changeOwner(address newOwner) external {
if (msg.sender == owner) {
owner = newOwner;
}
}
/**
* Create a new meetup post
*/
function createMeetup(
string ipfsHash
) external {
address organizer = msg.sender;
seqId = seqId + 1;
meetups[seqId] = MeetupPost(seqId, organizer, ipfsHash);
_MeetupCreated(seqId);
}
/**
* Edit ipfs hash of a post
*/
function editMeetup(
uint id,
string ipfsHash
) external {
address organizer = msg.sender;
MeetupPost storage meetup = meetups[id];
require(meetup.organizer == organizer);
meetups[id].ipfsHash = ipfsHash;
_MeetupUpdated(id);
}
/**
* Retrieve a meetup post by ID
*/
function getMeetup(uint id) external constant returns (uint, address, string) {
MeetupPost storage meetup = meetups[id];
return (meetup.id, meetup.organizer, meetup.ipfsHash);
}
}
| Edit ipfs hash of a post/ | function editMeetup(
uint id,
string ipfsHash
) external {
address organizer = msg.sender;
MeetupPost storage meetup = meetups[id];
require(meetup.organizer == organizer);
meetups[id].ipfsHash = ipfsHash;
_MeetupUpdated(id);
}
| 1,759,462 |
./full_match/43114/0xDFa3bCda5f954A1E6CEF247bDfA89F15702a7473/sources/contracts/strategies/MiniChefStrategy.sol | Harvest from Masterchef | function harvestPartially(address token) external override nonReentrant {
uint256 pid = viewPid(token);
chef.harvest(pid, address(this));
tallyReward(token);
}
| 4,542,749 |
pragma solidity ^0.5.1;
// PokerHandUtils
//
//
// Library for handling of poker hands consisting of cards numbered 0-51
// Ace = 0, King = 12 in the suits Clubs, Diamonds, Hearts, Spades
//
// Function: evaluateHand takes a list of 5 cards (0-51)
// Returns: enum of Hand type and up to 5 values of the cards sorted to break ties
//
// Notes: State of the art poker hand evals use data tables and hash to run fast.
// For in contract, wanted an old school analytic approach with low memory
//
// Next Steps: Test and Optimize. Potentially change tiebreaker list to a hash number to compare.
//
// Usage:
//
// int8[5] memory hand = [ int8(PokerHandUtils.CardId.Six_Clubs), int8(PokerHandUtils.CardId.Three_Clubs), int8(PokerHandUtils.CardId.Jack_Diamonds), int8(PokerHandUtils.CardId.Two_Clubs), int8(PokerHandUtils.CardId.Seven_Clubs)];
// PokerHandUtils.HandEnum handVal;
// int8[5] memory result;
// (handVal, result) = poker.evaluateHand(hand);
// Example returns (HandEnum.HighCard, [Jack, Eight, Six, Three, Two])
//
// Should be library but contract so I can run truffle tests
// library PokerHandUtils {
library PokerHandUtils {
// Enum for all Cards, 0-51
enum CardId {
Ace_Clubs, Two_Clubs, Three_Clubs, Four_Clubs, Five_Clubs, Six_Clubs, Seven_Clubs, Eight_Clubs, Nine_Clubs, Ten_Clubs, Jack_Clubs, Queen_Clubs, King_Clubs,
Ace_Diamonds, Two_Diamonds, Three_Diamonds, Four_Diamonds, Five_Diamonds, Six_Diamonds, Seven_Diamonds, Eight_Diamonds, Nine_Diamonds, Ten_Diamonds, Jack_Diamonds, Queen_Diamonds, King_Diamonds,
Ace_Hearts, Two_Hearts, Three_Hearts, Four_Hearts, Five_Hearts, Six_Hearts, Seven_Hearts, Eight_Hearts, Nine_Hearts, Ten_Hearts, Jack_Hearts, Queen_Hearts, King_Hearts,
Ace_Spades, Two_Spades, Three_Spades, Four_Spades, Five_Spades, Six_Spades, Seven_Spades, Eight_Spades, Nine_Spades, Ten_Spades, Jack_Spades, Queen_Spades, King_Spades
}
// Values of Cards
enum CardValue { Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King, Ace_High }
// Suits of Cards
enum CardSuit { Clubs, Diamonds, Hearts, Spades }
// Type of hand from High card to Royal flush
enum HandEnum { RoyalFlush, StraightFlush, FourOfAKind, FullHouse, Flush, Straight, ThreeOfAKind, TwoPair, Pair, HighCard }
// Convert a card to standard card name pair
function getCardName(int8 code) public pure returns (CardValue, CardSuit) {
require(code >= 0 && code < 52, "Invalid card code.");
return (CardValue(code % 13), CardSuit(code / 13));
}
// Convert a card name to card code
function getCardCode(CardValue value, CardSuit suit) public pure returns (int8) {
return int8(suit)*13 + int8(value);
}
// Helper to get the value for a card 1,12 plus Ace high can be 13.
// Used for judging relative strength
function getCardOrderValue(CardValue cardVal) public pure returns (int8)
{
// Ace values as High Ace in ranking
if (int8(cardVal) == 0) {
return int8(CardValue.Ace_High);
}
return int8(cardVal);
}
// Helper Sort function
// Modified from
// https://github.com/alice-si/array-booster
function sortHand(int8[5] memory data) public pure {
uint n = data.length;
int8[] memory arr = new int8[](n);
uint i;
for(i = 0; i<n; i++) {
arr[i] = data[i];
}
int8 key;
uint j;
for(i = 1; i < arr.length; i++ ) {
key = arr[i];
for(j = i; j > 0 && arr[j-1] < key; j-- ) {
arr[j] = arr[j-1];
}
arr[j] = key;
}
for(i = 0; i<n; i++) {
data[i] = arr[i];
}
}
// Hand evaluator - returns the type of hand and card values for a 5 card hand in order
// Will return the cards ranked by value order where -1 is something we don't care about
// E.G. Four of a kind will return HandEnum=FourOfAKind and ranks will be [FourOfAKind_Value, Extra card value, -1,-1,-1]
function evaluateHand(int8[5] memory cards) public pure returns (HandEnum, int8[5] memory)
{
// order of card values to return for evaluating
int8[5] memory retOrder = [-1, -1, -1, -1, -1];
int8[5] memory sortCards; // List of card values with Ace = 13
uint8 i;
HandEnum handVal = HandEnum.HighCard; // Assume high card
uint8[4] memory suits = [0, 0, 0, 0]; // Count suits to check for a flush
uint8[13] memory val_match = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // Array of values to check for pairs, ToaK, FoaK
uint8 testValue = 0;
CardValue cardValue;
CardSuit cardSuit;
int8[2] memory pairs = [-1, -1]; // Value of two pairs
// Initial pass through cards
for (i = 0; i < 5; i++)
{
(cardValue, cardSuit) = getCardName(cards[i]);
testValue = uint8(cardValue);
val_match[testValue]++; // Update val_match for card values
sortCards[i] = getCardOrderValue(cardValue);
// Test for 4 of a kind
if (val_match[testValue] == 4 && handVal > HandEnum.FourOfAKind)
{
handVal = HandEnum.FourOfAKind;
retOrder[0] = getCardOrderValue(cardValue);
}
else if (val_match[testValue] == 3 && handVal > HandEnum.ThreeOfAKind)
{
handVal = HandEnum.ThreeOfAKind;
retOrder[0] = getCardOrderValue(cardValue);
}
else if (val_match[testValue] == 2)
{
// Handle pairs by storing off for later
if (pairs[0] == -1)
pairs[0] = getCardOrderValue(cardValue);
else
pairs[1] = getCardOrderValue(cardValue);
}
suits[uint8(cardSuit)]++; // increment suits
// Handle flush situations
if (suits[uint8(cardSuit)] == 5) {
// flush of all five cards so we are going to return in here
sortHand(sortCards); // Sort the cards
if (sortCards[0] - sortCards[4] == 4)
{
if (sortCards[0] == 13) {
// Its a royal flush
handVal = HandEnum.RoyalFlush;
} else {
handVal = HandEnum.StraightFlush;
}
return (handVal, sortCards);
}
else if (sortCards[0] == 13 && sortCards[1] == 4 &&
sortCards[1] - sortCards[4] == 3) // Ace low straight flush
{
handVal = HandEnum.StraightFlush;
retOrder = [int8(4), 3, 2, 1, 0]; // Ace Low straight
return (handVal, retOrder);
}
else
{
// it is a flush
handVal = HandEnum.Flush;
return (handVal, sortCards);
}
}
}
// Check 4oaK and 3oaK
if (handVal == HandEnum.FourOfAKind) {
for (i = 0; i < 5; i++) {
// Find the only kicker
if (sortCards[i] != retOrder[0]) {
retOrder[1] = sortCards[i];
return (handVal, retOrder);
}
}
} else if (handVal == HandEnum.ThreeOfAKind) {
// Check for full house
if (pairs[1] > -1) {
handVal = HandEnum.FullHouse;
if (pairs[0] == retOrder[0])
retOrder[1] = pairs[1];
else
retOrder[1] = pairs[0];
return (handVal, retOrder);
}
// 3oaK, so check the last two cards
for (i = 0; i < 5; i++) {
// Find the kickers
if (sortCards[i] != retOrder[0]) {
if (sortCards[i] > retOrder[1]) {
retOrder[2] = retOrder[1];
retOrder[1] = sortCards[i];
} else {
retOrder[2] = sortCards[i];
}
}
}
// return 3oaK
return (handVal, retOrder);
}
// check for straights via sorted rank list if not 3 of a kind or pairs
if (handVal > HandEnum.ThreeOfAKind)
{
// no pair so could be a straight
if (pairs[0] == -1)
{
sortHand(sortCards); // Sort the cards
// Check the straights
if (sortCards[0] - sortCards[4] == 4) {
handVal = HandEnum.Straight;
return (handVal, sortCards);
}
else if (sortCards[0] == 13 && sortCards[1] == 4 &&
sortCards[1] - sortCards[4] == 3) // Ace low straight
{
handVal = HandEnum.Straight;
retOrder = [int8(4), 3, 2, 1, 0]; // Ace Low straight
return (handVal, retOrder);
}
else // High card only
{
handVal = HandEnum.HighCard;
return (handVal, sortCards);
}
}
else // pair or two pair
{
if (pairs[1] != -1) // two pair
{
handVal = HandEnum.TwoPair;
if (pairs[0] > pairs[1])
{
retOrder[0] = pairs[0];
retOrder[1] = pairs[1];
}
else
{
retOrder[0] = pairs[1];
retOrder[1] = pairs[0];
}
// find the final kicker
for (i = 0; i < 5; i++) {
if (sortCards[i] != pairs[0] && sortCards[i] != pairs[1]) {
retOrder[2] = sortCards[i];
}
}
return (handVal, retOrder);
}
else // just a pair
{
sortHand(sortCards); // Sort the cards
handVal = HandEnum.Pair;
retOrder[0] = pairs[0];
uint8 cnt = 1;
for (i = 0; i < 5; i++)
{
// not the pair add to list
if (sortCards[i] != pairs[0]) {
retOrder[cnt] = sortCards[i];
cnt++;
}
}
return (handVal, retOrder);
}
}
}
return (handVal, retOrder);
}
}
| Helper to get the value for a card 1,12 plus Ace high can be 13. Used for judging relative strength Ace values as High Ace in ranking | function getCardOrderValue(CardValue cardVal) public pure returns (int8)
{
if (int8(cardVal) == 0) {
return int8(CardValue.Ace_High);
}
return int8(cardVal);
}
| 12,990,233 |
/*
MIT License
Copyright (c) 2021 Reflexer Labs
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
pragma solidity 0.6.7;
import "./erc20/IERC20.sol";
import "./utils/PoolViewer.sol";
import "./utils/PeripheryPayments.sol";
import "./utils/ReentrancyGuard.sol";
import { IUniswapV3Pool } from "./uni/interfaces/IUniswapV3Pool.sol";
import { IUniswapV3MintCallback } from "./uni/interfaces/callback/IUniswapV3MintCallback.sol";
import { LiquidityAmounts } from "./uni/libraries/LiquidityAmounts.sol";
import { TickMath } from "./uni/libraries/TickMath.sol";
abstract contract OracleForUniswapLike {
function getResultsWithValidity() public virtual returns (uint256, uint256, bool);
}
/**
* @notice This contract is based on https://github.com/dmihal/uniswap-liquidity-dao/blob/master/contracts/MetaPool.sol
*/
abstract contract GebUniswapV3ManagerBase is ERC20, ReentrancyGuard, PeripheryPayments {
// --- Auth ---
mapping (address => uint256) public authorizedAccounts;
/**
* @notice Add auth to an account
* @param account Account to add auth to
*/
function addAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
/**
* @notice Remove auth from an account
* @param account Account to remove auth from
*/
function removeAuthorization(address account) external isAuthorized {
authorizedAccounts[account] = 0;
emit RemoveAuthorization(account);
}
/**
* @notice Checks whether msg.sender can call an authed function
**/
modifier isAuthorized {
require(authorizedAccounts[msg.sender] == 1, "GebUniswapV3ManagerBase/account-not-authorized");
_;
}
// --- Pool Variables ---
// The address of pool's token0
address public token0;
// The address of pool's token1
address public token1;
// The pool's fee
uint24 public fee;
// The pool's tickSpacing
int24 public tickSpacing;
// The pool's maximum liquidity per tick
uint128 public maxLiquidityPerTick;
// Flag to identify whether the system coin is token0 or token1. Needed for correct tick calculation
bool systemCoinIsT0;
// --- General Variables ---
// The minimum delay required to perform a rebalance. Bounded to be between MINIMUM_DELAY and MAXIMUM_DELAY
uint256 public delay;
// The timestamp of the last rebalance
uint256 public lastRebalance;
// The management fee retained from pool fees
uint256 public managementFee;
// Unclaimed token0 fees
uint256 public unclaimedToken0;
// Unclaimed token1 fees
uint256 public unclaimedToken1;
// --- External Contracts ---
// Address of the Uniswap v3 pool
IUniswapV3Pool public pool;
// Address of oracle relayer to get prices from
OracleForUniswapLike public oracle;
// Address of contract that allows simulating pool functions
PoolViewer public poolViewer;
// --- Constants ---
// One hundred
uint256 constant HUNDRED = 100;
// Used to get the max amount of tokens per liquidity burned
uint128 constant MAX_UINT128 = uint128(0 - 1);
// 100% - Not really achievable, because it'll reach max and min ticks
uint256 constant MAX_THRESHOLD = 10000000;
// 1% - Quite dangerous because the market price can easily move beyond the threshold
uint256 constant MIN_THRESHOLD = 10000; // 1%
// A week is the maximum time allowed without a rebalance
uint256 constant MAX_DELAY = 7 days;
// 1 hour is the absolute minimum delay for a rebalance. Could be less through deposits
uint256 constant MIN_DELAY = 60 minutes;
// Absolutes ticks, (MAX_TICK % tickSpacing == 0) and (MIN_TICK % tickSpacing == 0)
int24 public constant MAX_TICK = 887220;
int24 public constant MIN_TICK = -887220;
// The minimum swap threshold, so it's worthwhile the gas
uint256 constant SWAP_THRESHOLD = 1 finney; // 1e15 units.
// Constants for price ratio calculation
uint256 public constant PRICE_RATIO_SCALE = 1000000000;
uint256 public constant SHIFT_AMOUNT = 192;
// --- Struct ---
struct Position {
bytes32 id;
int24 lowerTick;
int24 upperTick;
uint128 uniLiquidity;
uint256 threshold;
uint256 tkn0Reserve;
uint256 tkn1Reserve;
}
// --- Events ---
event AddAuthorization(address account);
event RemoveAuthorization(address account);
event ModifyParameters(bytes32 parameter, uint256 val);
event ModifyParameters(bytes32 parameter, address val);
event Deposit(address sender, address recipient, uint256 liquidityAdded);
event Withdraw(address sender, address recipient, uint256 liquidityAdded);
event Rebalance(address sender, uint256 timestamp);
event ClaimManagementFees(address receiver);
/**
* @notice Constructor that sets initial parameters for this contract
* @param name_ The name of the ERC20 this contract will distribute
* @param symbol_ The symbol of the ERC20 this contract will distribute
* @param systemCoinAddress_ The address of the system coin
* @param delay_ The minimum required time before rebalance() can be called
* @param managementFee_ The initial management fee
* @param pool_ Address of the already deployed Uniswap v3 pool that this contract will manage
* @param oracle_ Address of the already deployed oracle that provides both prices
*/
constructor(
string memory name_,
string memory symbol_,
address systemCoinAddress_,
address pool_,
address weth9Address,
uint256 delay_,
uint256 managementFee_,
OracleForUniswapLike oracle_,
PoolViewer poolViewer_
) public ERC20(name_, symbol_) PeripheryPayments(weth9Address) {
require(both(delay_ >= MIN_DELAY, delay_ <= MAX_DELAY), "GebUniswapV3ManagerBase/invalid-delay");
require(managementFee_ < HUNDRED, "GebUniswapV3ManagerBase/invalid-management-fee");
authorizedAccounts[msg.sender] = 1;
// Getting pool information
pool = IUniswapV3Pool(pool_);
token0 = pool.token0();
token1 = pool.token1();
fee = pool.fee();
tickSpacing = pool.tickSpacing();
maxLiquidityPerTick = pool.maxLiquidityPerTick();
require(MIN_TICK % tickSpacing == 0, "GebUniswapV3ManagerBase/invalid-max-tick-for-spacing");
require(MAX_TICK % tickSpacing == 0, "GebUniswapV3ManagerBase/invalid-min-tick-for-spacing");
systemCoinIsT0 = token0 == systemCoinAddress_ ? true : false;
delay = delay_;
oracle = oracle_;
poolViewer = poolViewer_;
managementFee = managementFee_;
emit AddAuthorization(msg.sender);
}
// --- Math ---
/**
* @notice Calculates the sqrt of a number
* @param y The number to calculate the square root of
* @return z The result of the calculation
*/
function sqrt(uint256 y) public pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
// --- Boolean Logic ---
function both(bool x, bool y) internal pure returns (bool z) {
assembly{ z := and(x, y)}
}
function either(bool x, bool y) internal pure returns (bool z) {
assembly{ z := or(x, y)}
}
// --- SafeCast ---
function toUint160(uint256 value) internal pure returns (uint160) {
require(value < 2**160, "GebUniswapV3ManagerBase/toUint160_overflow");
return uint160(value);
}
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "GebUniswapV3ManagerBase/toUint128_overflow");
return uint128(value);
}
function toInt24(uint256 value) internal pure returns (int24) {
require(value < 2**23, "GebUniswapV3ManagerBase/toInt24_overflow");
return int24(value);
}
// --- Administration ---
/**
* @notice Modify the adjustable parameters
* @param parameter The variable to change
* @param data The value to set for the parameter
*/
function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized {
if (parameter == "delay") {
require(both(data >= MIN_DELAY, data <= MAX_DELAY), "GebUniswapV3ManagerBase/invalid-delay");
delay = data;
}
else if (parameter == "managementFee") {
require(data < HUNDRED, "GebUniswapV3ManagerBase/invalid-management-fee");
managementFee = data;
}
else revert("GebUniswapV3ManagerBase/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
/**
* @notice Modify adjustable parameters
* @param parameter The variable to change
* @param data The value to set for the parameter
*/
function modifyParameters(bytes32 parameter, address data) external isAuthorized {
require(data != address(0), "GebUniswapV3ManagerBase/null-data");
if (parameter == "oracle") {
// If it's an invalid address, this tx will revert
OracleForUniswapLike(data).getResultsWithValidity();
oracle = OracleForUniswapLike(data);
} else revert("GebUniswapV3ManagerBase/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
/**
* @notice Claim management fees and send them to a custom address
* @param receiver The fee receiver
*/
function claimManagementFees(address receiver) external nonReentrant isAuthorized {
if (unclaimedToken0 > 0) {
IERC20(token0).transfer(receiver, unclaimedToken0);
unclaimedToken0 = 0;
}
if (unclaimedToken1 > 0) {
IERC20(token1).transfer(receiver, unclaimedToken1);
unclaimedToken1 = 0;
}
emit ClaimManagementFees(receiver);
}
// --- Virtual functions ---
function deposit(uint256 newLiquidity, address recipient, uint256 minAm0, uint256 minAm1) external payable virtual returns (uint256 mintAmount);
function withdraw(uint256 liquidityAmount, address recipient) external virtual returns (uint256 amount0, uint256 amount1);
function rebalance() external virtual;
// --- Getters ---
/**
* @notice Public function to get both the redemption price for the system coin and the other token's price
* @return redemptionPrice The redemption price
* @return tokenPrice The other token's price
*/
function getPrices() public returns (uint256 redemptionPrice, uint256 tokenPrice) {
bool valid;
(redemptionPrice, tokenPrice, valid) = oracle.getResultsWithValidity();
require(valid, "GebUniswapV3ManagerBase/invalid-price");
}
/**
* @notice Function that returns the next target ticks based on the redemption price
* @return _nextLower The lower bound of the range
* @return _nextUpper The upper bound of the range
*/
function getNextTicks(uint256 _threshold) public returns (int24 _nextLower, int24 _nextUpper, int24 targetTick) {
targetTick = getTargetTick();
(_nextLower, _nextUpper) = getTicksWithThreshold(targetTick, _threshold);
}
/**
* @notice Function that returns the target ticks based on the redemption price
* @return targetTick The target tick that represents the redemption price
*/
function getTargetTick() public returns(int24 targetTick){
// 1. Get prices from the oracle relayer
(uint256 redemptionPrice, uint256 ethUsdPrice) = getPrices();
// 2. Calculate the price ratio
uint160 sqrtPriceX96;
if (systemCoinIsT0) {
sqrtPriceX96 = toUint160(sqrt((redemptionPrice.mul(PRICE_RATIO_SCALE).div(ethUsdPrice) << SHIFT_AMOUNT) / PRICE_RATIO_SCALE));
} else {
sqrtPriceX96 = toUint160(sqrt((ethUsdPrice.mul(PRICE_RATIO_SCALE).div(redemptionPrice) << SHIFT_AMOUNT) / PRICE_RATIO_SCALE));
}
// 3. Calculate the tick that the ratio is at
int24 approximatedTick = TickMath.getTickAtSqrtRatio(sqrtPriceX96);
// 4. Adjust to comply to tickSpacing
targetTick = approximatedTick - (approximatedTick % tickSpacing);
}
/**
* @notice Function that returns the next target ticks based on the target tick
* @param targetTick The tick representing the redemption price
* @param _threshold The threshold used to find ticks
* @return lowerTick The lower bound of the range
* @return upperTick The upper bound of the range
*/
function getTicksWithThreshold(int24 targetTick, uint256 _threshold) public pure returns(int24 lowerTick, int24 upperTick){
// 5. Find lower and upper bounds for the next position
lowerTick = targetTick - toInt24(_threshold) < MIN_TICK ? MIN_TICK : targetTick - toInt24(_threshold);
upperTick = targetTick + toInt24(_threshold) > MAX_TICK ? MAX_TICK : targetTick + toInt24(_threshold);
}
/**
* @notice An internal non state changing function that allows simulating a withdraw and returning the amount of each token received
* @param _position The position to perform the operation
* @param _liquidity The amount of liquidity to be withdrawn
* @return amount0 The amount of token0
* @return amount1 The amount of token1
*/
function _getTokenAmountsFromLiquidity(Position storage _position, uint128 _liquidity) internal returns (uint256 amount0, uint256 amount1) {
uint256 __supply = _totalSupply;
uint128 _liquidityBurned = toUint128(uint256(_liquidity).mul(_position.uniLiquidity).div(__supply));
(, bytes memory ret) =
address(poolViewer).delegatecall(
abi.encodeWithSignature("burnViewer(address,int24,int24,uint128)", address(pool), _position.lowerTick, _position.upperTick, _liquidityBurned)
);
(amount0, amount1) = abi.decode(ret, (uint256, uint256));
require(amount0 > 0 || amount1 > 0, "GebUniswapV3ManagerBase/invalid-burnViewer-amounts");
}
// --- Core user actions ---
/**
* @notice Add liquidity to this pool manager
* @param _position The position to perform the operation
* @param _newLiquidity The amount of liquidity to add
* @param _targetTick The price to center the position around
*/
function _deposit(Position storage _position, uint128 _newLiquidity, int24 _targetTick ) internal returns(uint256 amount0,uint256 amount1){
(int24 _nextLowerTick,int24 _nextUpperTick) = getTicksWithThreshold(_targetTick,_position.threshold);
{ // Scope to avoid stack too deep
uint128 compoundLiquidity = 0;
uint256 used0 = 0;
uint256 used1 = 0;
if (both(_position.uniLiquidity > 0, either(_position.lowerTick != _nextLowerTick, _position.upperTick != _nextUpperTick))) {
(compoundLiquidity, used0, used1) = maxLiquidity(_position,_nextLowerTick,_nextUpperTick);
require(_newLiquidity + compoundLiquidity >= _newLiquidity, "GebUniswapV3ManagerBase/liquidity-overflow");
emit Rebalance(msg.sender, block.timestamp);
}
// 3. Mint our new position on Uniswap
lastRebalance = block.timestamp;
(uint256 amount0Minted, uint256 amount1Minted) = _mintOnUniswap(_position, _nextLowerTick, _nextUpperTick, _newLiquidity+compoundLiquidity, abi.encode(msg.sender, used0 , used1));
(amount0, amount1) = (amount0Minted - used0, amount1Minted - used1);
}
}
/**
* @notice Remove liquidity and withdraw the underlying assets
* @param _position The position to perform the operation
* @param _liquidityBurned The amount of liquidity to withdraw
* @param _recipient The address that will receive token0 and token1 tokens
* @return amount0 The amount of token0 requested from the pool
* @return amount1 The amount of token1 requested from the pool
*/
function _withdraw(
Position storage _position,
uint128 _liquidityBurned,
address _recipient
) internal returns (uint256 amount0, uint256 amount1) {
(amount0, amount1) = _burnOnUniswap(_position, _position.lowerTick, _position.upperTick, _liquidityBurned, _recipient);
emit Withdraw(msg.sender, _recipient, _liquidityBurned);
}
/**
* @notice Rebalance by burning and then minting the position
* @param _position The position to perform the operation
* @param _targetTick The desired price to center the liquidity around
*/
function _rebalance(Position storage _position, int24 _targetTick) internal {
(int24 _nextLowerTick, int24 _nextUpperTick) = getTicksWithThreshold(_targetTick,_position.threshold);
(int24 _currentLowerTick, int24 _currentUpperTick) = (_position.lowerTick, _position.upperTick);
if (_currentLowerTick != _nextLowerTick || _currentUpperTick != _nextUpperTick) {
(uint128 compoundLiquidity, uint256 used0, uint256 used1) = maxLiquidity(_position,_nextLowerTick,_nextUpperTick);
_mintOnUniswap(_position, _nextLowerTick, _nextUpperTick, compoundLiquidity, abi.encode(msg.sender, used0, used1));
}
emit Rebalance(msg.sender, block.timestamp);
}
// --- Internal helpers ---
/**
* @notice Helper function to mint a position
* @param _nextLowerTick The lower bound of the range to deposit the liquidity to
* @param _nextUpperTick The upper bound of the range to deposit the liquidity to
* @param _amount0 The total amount of token0 to use in the calculations
* @param _amount1 The total amount of token1 to use in the calculations
* @return compoundLiquidity The amount of total liquidity to be minted
* @return tkn0Amount The amount of token0 that will be used
* @return tkn1Amount The amount of token1 that will be used
*/
function _getCompoundLiquidity(int24 _nextLowerTick, int24 _nextUpperTick, uint256 _amount0, uint256 _amount1) internal view returns(uint128 compoundLiquidity, uint256 tkn0Amount, uint256 tkn1Amount){
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
uint160 lowerSqrtRatio = TickMath.getSqrtRatioAtTick(_nextLowerTick);
uint160 upperSqrtRatio = TickMath.getSqrtRatioAtTick(_nextUpperTick);
compoundLiquidity = LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
lowerSqrtRatio,
upperSqrtRatio,
_amount0,
_amount1
);
// Token amounts aren't precise from the calculation above, so we do the reverse operation to get the precise amount
(tkn0Amount,tkn1Amount) = LiquidityAmounts.getAmountsForLiquidity(sqrtRatioX96,lowerSqrtRatio,upperSqrtRatio,compoundLiquidity);
}
/**
* @notice This functions perform actions to optimize the liquidity received
* @param _position The position to perform operations on
* @param _nextLowerTick The lower bound of the range to deposit the liquidity to
* @param _nextUpperTick The upper bound of the range to deposit the liquidity to
* @return compoundLiquidity The amount of total liquidity to be minted
* @return tkn0Amount The amount of token0 that will be used
* @return tkn1Amount The amount of token1 that will be used
*/
function maxLiquidity(Position storage _position, int24 _nextLowerTick, int24 _nextUpperTick) internal returns(uint128 compoundLiquidity, uint256 tkn0Amount, uint256 tkn1Amount){
// Burn the existing position and get the fees
(uint256 collected0, uint256 collected1) = _burnOnUniswap(_position, _position.lowerTick, _position.upperTick, _position.uniLiquidity, address(this));
uint256 partialAmount0 = collected0.add(_position.tkn0Reserve);
uint256 partialAmount1 = collected1.add(_position.tkn1Reserve);
(uint256 used0, uint256 used1) = (0,0);
(uint256 newAmount0, uint256 newAmount1) = (0,0);
// Calculate how much liquidity we can get from what's been collect + what we have in the reserves
(compoundLiquidity, used0, used1) = _getCompoundLiquidity(_nextLowerTick,_nextUpperTick,partialAmount0,partialAmount1);
if(both(partialAmount0.sub(used0) >= SWAP_THRESHOLD, partialAmount1.sub(used1) >= SWAP_THRESHOLD)) {
// Take the leftover amounts and do a swap to get a bit more liquidity
(newAmount0, newAmount1) = _swapOutstanding(_position, partialAmount0.sub(used0), partialAmount1.sub(used1));
// With new amounts, calculate again how much liquidity we can get
(compoundLiquidity, used0, used1) = _getCompoundLiquidity(_nextLowerTick,_nextUpperTick,partialAmount0.add(newAmount0).sub(used0),partialAmount1.add(newAmount1).sub(used1));
}
// Update our reserves
_position.tkn0Reserve = partialAmount0.add(newAmount0).sub(used0);
_position.tkn1Reserve = partialAmount1.add(newAmount1).sub(used1);
tkn0Amount = used0;
tkn1Amount = used1;
}
/**
* @notice Perform a swap on the uni pool to have a balanced position
* @param _position The position to perform operations on
* @param swapAmount0 The amount of token0 that will be used
* @param swapAmount1 The amount of token1 that will be used
* @return newAmount0 The new amount of token0 received
* @return newAmount1 The new amount of token1 received
*/
function _swapOutstanding(Position storage _position, uint256 swapAmount0, uint256 swapAmount1) internal returns (uint256 newAmount0,uint256 newAmount1) {
// The swap is not the optimal trade, but it's a simpler calculation that will be enough to keep everything more or less balanced
if (swapAmount0 > 0 || swapAmount1 > 0) {
bool zeroForOne = swapAmount0 > swapAmount1;
(int256 amount0Delta, int256 amount1Delta) = pool.swap(
address(this),
zeroForOne,
int256(zeroForOne ? swapAmount0 : swapAmount1) / 2,
TickMath.getSqrtRatioAtTick(zeroForOne ? _position.lowerTick : _position.upperTick),
abi.encode(address(this))
);
newAmount0 = uint256(int256(swapAmount0) - amount0Delta);
newAmount1 = uint256(int256(swapAmount1) - amount1Delta);
}
}
// --- Uniswap Related Functions ---
/**
* @notice Helper function to mint a position
* @param _lowerTick The lower bound of the range to deposit the liquidity to
* @param _upperTick The upper bound of the range to deposit the liquidity to
* @param _totalLiquidity The total amount of liquidity to mint
* @param _callbackData The data to pass on to the callback function
*/
function _mintOnUniswap(
Position storage _position,
int24 _lowerTick,
int24 _upperTick,
uint128 _totalLiquidity,
bytes memory _callbackData
) internal returns(uint256 amount0, uint256 amount1) {
pool.positions(_position.id);
(amount0, amount1) = pool.mint(address(this), _lowerTick, _upperTick, _totalLiquidity, _callbackData);
_position.lowerTick = _lowerTick;
_position.upperTick = _upperTick;
bytes32 id = keccak256(abi.encodePacked(address(this), _lowerTick, _upperTick));
(uint128 _liquidity, , , , ) = pool.positions(id);
_position.id = id;
_position.uniLiquidity = _liquidity;
}
/**
* @notice Helper function to burn a position
* @param _lowerTick The lower bound of the range to deposit the liquidity to
* @param _upperTick The upper bound of the range to deposit the liquidity to
* @param _burnedLiquidity The amount of liquidity to burn
* @param _recipient The address to send the tokens to
* @return collected0 The amount of token0 requested from the pool
* @return collected1 The amount of token1 requested from the pool
*/
function _burnOnUniswap(
Position storage _position,
int24 _lowerTick,
int24 _upperTick,
uint128 _burnedLiquidity,
address _recipient
) internal returns (uint256 collected0, uint256 collected1) {
(uint256 fee0, uint256 fee1) = _collectFees(_position, _lowerTick, _upperTick);
pool.burn(_lowerTick, _upperTick, _burnedLiquidity);
// Collect all owed
(collected0, collected1) = pool.collect(_recipient, _lowerTick, _upperTick, MAX_UINT128, MAX_UINT128);
collected0 = collected0.add(fee0);
collected1 = collected1.add(fee1);
// Update position. All other factors are still the same
(uint128 _liquidity, , , , ) = pool.positions(_position.id);
_position.uniLiquidity = _liquidity;
}
/**
* @notice Helper function to collect fees
* @param _lowerTick The lower bound of the range to deposit the liquidity to
* @param _upperTick The upper bound of the range to deposit the liquidity to
* @return collected0 The amount of token0 fees to be reinvested when balancing
* @return collected1 The amount of token1 fees to be reinvested when balancing
*/
function _collectFees(
Position storage _position,
int24 _lowerTick,
int24 _upperTick
) internal returns (uint256 collected0, uint256 collected1) {
pool.burn(_lowerTick, _upperTick, 0);
// collecting fees
(collected0, collected1) = pool.collect(address(this), _lowerTick, _upperTick, MAX_UINT128, MAX_UINT128);
uint managementFee0 = collected0.mul(managementFee).div(HUNDRED);
uint managementFee1 = collected1.mul(managementFee).div(HUNDRED);
unclaimedToken0 = unclaimedToken0.add(managementFee0);
unclaimedToken1 = unclaimedToken1.add(managementFee1);
collected0 = collected0.sub(managementFee0);
collected1 = collected1.sub(managementFee1);
}
/**
* @notice Callback used to transfer tokens to the pool. Tokens need to be approved before calling mint or deposit.
* @param amount0Owed The amount of token0 necessary to send to pool
* @param amount1Owed The amount of token1 necessary to send to pool
* @param data Arbitrary data to use in the function
*/
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external {
require(msg.sender == address(pool));
(address sender, uint256 amt0FromThis, uint256 amt1FromThis) = abi.decode(data, (address, uint256, uint256));
// Pay what this contract owes
if (amt0FromThis > 0) {
TransferHelper.safeTransfer(token0, msg.sender, amt0FromThis);
}
if (amt1FromThis > 0) {
TransferHelper.safeTransfer(token1, msg.sender, amt1FromThis);
}
// Pay what the sender owes
if (amount0Owed > amt0FromThis) {
pay(token0, sender, msg.sender, amount0Owed - amt0FromThis);
}
if (amount1Owed > amt1FromThis) {
pay(token1, sender, msg.sender, amount1Owed - amt1FromThis);
}
}
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata /*data*/
) external {
require(msg.sender == address(pool));
if (amount0Delta > 0) {
TransferHelper.safeTransfer(token0, msg.sender, uint256(amount0Delta));
} else if (amount1Delta > 0) {
TransferHelper.safeTransfer(token1, msg.sender, uint256(amount1Delta));
}
}
}
| Function that returns the target ticks based on the redemption price return targetTick The target tick that represents the redemption price/ 1. Get prices from the oracle relayer 2. Calculate the price ratio | function getTargetTick() public returns(int24 targetTick){
(uint256 redemptionPrice, uint256 ethUsdPrice) = getPrices();
uint160 sqrtPriceX96;
if (systemCoinIsT0) {
sqrtPriceX96 = toUint160(sqrt((redemptionPrice.mul(PRICE_RATIO_SCALE).div(ethUsdPrice) << SHIFT_AMOUNT) / PRICE_RATIO_SCALE));
sqrtPriceX96 = toUint160(sqrt((ethUsdPrice.mul(PRICE_RATIO_SCALE).div(redemptionPrice) << SHIFT_AMOUNT) / PRICE_RATIO_SCALE));
}
}
| 14,064,078 |
./full_match/1/0xf1409a2f1F5f53e46BbAfd334311c80e675a410D/sources/contracts/moneymarkets/aave/imports/ILendingPool.sol | Aave lending pool interface | interface ILendingPool {
function deposit(address _reserve, uint256 _amount, uint16 _referralCode)
external;
function getReserveData(address _reserve)
external
view
returns (
uint256 totalLiquidity,
uint256 availableLiquidity,
uint256 totalBorrowsStable,
uint256 totalBorrowsVariable,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 utilizationRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
address aTokenAddress,
uint40 lastUpdateTimestamp
);
}
| 8,435,106 |
./full_match/1/0x489dC359F9f1799FBf388abf91cFe7cb37736D6a/sources/contracts/PPIE.sol | Sender redeems pTokens in exchange for the underlying asset Accrues interest whether or not the operation succeeds, unless reverted redeemTokens The number of pTokens to redeem into underlying return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ | function redeem(uint redeemTokens) external override returns (uint) {
(uint err, uint amount) = redeemInternal(redeemTokens);
if (err == 0) {
_moveDelegates(delegates[msg.sender], address(0), uint96(amount));
}
return err;
}
| 8,387,359 |
/**
*Submitted for verification at Etherscan.io on 2021-03-08
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
// File: BusStation.sol
contract BusStation {
/* ==== Variables ===== */
mapping(address => uint256) public _seats;
bool public _hasBusLeft;
uint256 public _ticketTotalValue;
uint256 public _minTicketValue = 0;
uint256 public _maxTicketValue;
uint256 public _minWeiToLeave;
address payable private _destination;
uint256 public _timelockDuration;
uint256 public _endOfTimelock;
/* ==== Events ===== */
/*
Removed for not being necessary and inflating gas costs
event TicketPurchased(address indexed _from, uint256 _value);
event Withdrawal(address indexed _from, uint256 _value);
event BusDeparts(uint256 _value);
*/
/* ==== Constructor ===== */
// Set up a one-way bus ride to a destination, with reserve price, time of departure, and cap on ticket prices for fairness
constructor(
address payable destination,
uint256 minWeiToLeave,
uint256 timelockSeconds,
uint256 maxTicketValue
) {
_hasBusLeft = false;
_minWeiToLeave = minWeiToLeave;
_maxTicketValue = maxTicketValue;
_destination = destination;
_timelockDuration = timelockSeconds;
_endOfTimelock = block.timestamp + _timelockDuration;
}
/* ==== Functions ===== */
// Purchase a bus ticket if eligible
function buyBusTicket() external payable canPurchaseTicket {
uint256 seatvalue = _seats[msg.sender];
require(
msg.value + seatvalue <= _maxTicketValue,
"Cannot exceed max ticket value."
);
_seats[msg.sender] = msg.value + seatvalue;
_ticketTotalValue += msg.value;
/* emit TicketPurchased(msg.sender, msg.value); */
}
// If bus is eligible, anybody can trigger the bus ride
function triggerBusRide() external isReadyToRide {
uint256 amount = _ticketTotalValue;
_ticketTotalValue = 0;
_hasBusLeft = true;
_destination.transfer(amount);
/* emit BusDeparts(amount); */
}
// If eligible to withdraw, then pull money out
function withdraw() external {
// Cannot withdraw after bus departs
require(_hasBusLeft == false, "Bus has already left.");
// Retrieve user balance
uint256 amount = _seats[msg.sender];
require(amount > 0, "Address does not have a ticket.");
// Write data before transfer to guard against re-entrancy
_seats[msg.sender] = 0;
_ticketTotalValue -= amount;
payable(msg.sender).transfer(amount);
/* emit Withdrawal(msg.sender, amount); */
}
/* === Modifiers === */
// Can only purchase ticket if bus has not left and ticket purchase amount is small
modifier canPurchaseTicket() {
require(_hasBusLeft == false, "The bus already left.");
require(msg.value > _minTicketValue, "Need to pay more for ticket.");
_;
}
// Bus can ride if timelock is passed and tickets exceed reserve price
modifier isReadyToRide() {
require(_endOfTimelock <= block.timestamp, "Function is timelocked.");
require(_hasBusLeft == false, "Bus is already gone.");
require(_ticketTotalValue >= _minWeiToLeave, "Not enough wei to leave.");
_;
}
} | If bus is eligible, anybody can trigger the bus ride | function triggerBusRide() external isReadyToRide {
uint256 amount = _ticketTotalValue;
_ticketTotalValue = 0;
_hasBusLeft = true;
_destination.transfer(amount);
| 2,128,617 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.3 <0.9.0;
//assertions check for things like equality, inequality or emptiness
// in order to return a pass/fail for the test
import "truffle/Assert.sol";
// helps deploy a fresh instance of the contract to the blockchain for testing
import "truffle/DeployedAddresses.sol";
// the smart contract we wish to test
import "../contracts/BookArbiter.sol";
import "../contracts/Book.sol";
contract TestBookArbiter {
// the smart contract we wish to test
BookArbiter store;
Book tome; // get book contracts from address list
uint index;
function beforeAll() public {
// initialize for testing
store = BookArbiter(DeployedAddresses.BookArbiter());
}
address payable temp = payable(address(this));
// fake hash strings for testing
string hashA = "0F934A56E45343GH4";
string hashB = "06B5FD34EA482B31A";
string hashC = "04B5FA56E4582B313";
string hashD = "0B934A34B5FA56E16";
/////////////////////0xC6bae7b84BE3916F298dB197fc7011a78fc6065C
// Ropsten address for testing: 0x2ad617ac13A61B251f340Fc5fBa9809D131ddf69
///////////////////////
// create book test phrase: 0x2ad617ac13A61B251f340Fc5fBa9809D131ddf69, "Siddhartha", true,0F934A56E45343GH4 , 0
/// Test common functions of Book Arbiter contract
function testAddBook() public {
store.addBook(temp, "little red riding hood", true, hashA, 2); // add book to test contract
index = store.getCount() - 1; // get current index if contract is still deployed
tome = Book(store.getBook(index)); // get contract from address list
Assert.equal(tome.getHash(), hashA, "hash should be equal and book is created"); // assert that the added book hash equals original hash
}
function testHashTransfer() public {
tome.setHash(hashB); // change hash to new value
Assert.equal(tome.getHash(), hashB, "the hash should be valid after transfer to new value"); // assert that the added book hash equals original hash
}
// use preset address for local testnet
// ganache address used above: 0x851763A06A4f53f2f900C274208688Ed7112ef71
function testTransferOwner() public {
address payable reset = payable(msg.sender);
tome.setSeller(reset);
// assert and check that ownership has changed hands
Assert.equal(tome.getSeller(), reset, "the new address should be the new owner of the book"); // assert that the seller has transferred
}
function testMultipleBooks() public { // test that ultiple books can be added
store.addBook(temp, "Siddhartha", true, hashA, 10); // add book to test contract
store.addBook(temp, "Idiocracy", false, hashB, 15); // add book to test contract
store.addBook(temp, "Just Friends", true, hashD, 12); // add book to test contract
uint count = store.getCount();
// test that the books were successfully added to the mapping
tome = Book(store.getBook(count - 3)); // get contract for first book
Assert.equal(tome.getHash(), hashA, "second book added correctly");
tome = Book(store.getBook(count - 2)); // get contract for second book
Assert.equal(tome.getHash(), hashB, "third book added correctly");
tome = Book(store.getBook(count - 1)); // get contract for third book
Assert.equal(tome.getHash(), hashD, "fourth book added correctly");
}
function testRemoveBook() public { // test functional book removal
store.removeBook(0);
//tome = Book(store.getBook(0)); // get contract for third book
// tests that two of the values are zeroed out, due to removal
address addr = store.getBook(0);
Assert.isZero(addr, "book removed correctly");
}
function testBook() public { // test that books will be added to empty indexes
store.addBook(temp, "Atisha's Lamp", true, hashC, 0); // add book to test contract
tome = Book(store.getBook(0)); // get contract for third book
Assert.equal(tome.getHash(), hashC, "book added correctly");
}
/////////////////////////
///////////////////////
////////////////////////
// Test Common functions of Escrow fxns
event VariablesCreated(uint _timestamp);
event TransactionCompleted(uint _timestamp);
// TEST IN JAVASCRIPT
/*
// test escrow and transaction procedure
// will use the last added book from earlier so that the price is 0
// will need to be partly done in javscript to test actual eth transfer
function testEscrowCreate() public {
// temporary variables to test escrow
uint count = store.getCount();
tome = Book(store.getBook(count - 1)); // get contract for third book
// ganache account
address buyer = 0xC6bae7b84BE3916F298dB197fc7011a78fc6065C;
emit VariablesCreated(block.timestamp);
// run escrow transaction
store.createTxn(count - 1, buyer);
emit TransactionCompleted(block.timestamp);
// Assert.isTrue((uint(buyer.balance) + priceGwei) <= (balance), "correct balance transferred");
}
function testTransactionFunded() public {
uint count = store.getCount();
tome = Book(store.getBook(count - 1)); // get contract for third book
// ganache account
address buyer = 0xC6bae7b84BE3916F298dB197fc7011a78fc6065C;
address seller = tome.getSeller();
uint priceGwei = tome.getPrice();
uint balance = buyer.balance;
// run escrow transaction
store.fundTxn(count - 1);
Assert.isTrue(uint(buyer.balance) <= balance, "correct balance transferred");
}
function testTransactionCompleted() public {
uint count = store.getCount();
tome = Book(store.getBook(count - 1)); // get contract for third book
address payable seller = payable(tome.getSeller());
uint balance = seller.balance;
store.validateTxn(count - 1);
Assert.isTrue(tome.getSeller() == 0xC6bae7b84BE3916F298dB197fc7011a78fc6065C, "ownership transferred");
Assert.isTrue(uint(seller.balance) >= balance, "correct balance transferred");
}
////////////////////////
/////////////////////
*/
} | test escrow and transaction procedure will use the last added book from earlier so that the price is 0 will need to be partly done in javscript to test actual eth transfer temporary variables to test escrow ganache account run escrow transaction Assert.isTrue((uint(buyer.balance) + priceGwei) <= (balance), "correct balance transferred"); | function testEscrowCreate() public {
uint count = store.getCount();
address buyer = 0xC6bae7b84BE3916F298dB197fc7011a78fc6065C;
emit VariablesCreated(block.timestamp);
store.createTxn(count - 1, buyer);
emit TransactionCompleted(block.timestamp);
address addr = store.getBook(0);
event VariablesCreated(uint _timestamp);
}
| 12,912,579 |
./full_match/42/0xac3656770C6053A28faF0842D7447A6A616D7944/sources/UnitTest/PreachersCompFiLqdtKyberSwapKovanAM.sol | KyberSwap functions/ Swap from srcToken to destToken (including ether) If the source token is not ETH (ie. an ERC20 token), the user is required to first call the ERC20 approve function to give an allowance to the smart contract executing the transferFrom function. mitigate ERC20 Approve front-running attack, by initially setting allowance to 0 set the spender's token allowance to srcQty | function executeKyberSwap( address SrcToken, uint256 srcQty, address DestToken,
address payable destAddress )
public returns ( uint256 ) {
ISimpleKyberProxy cSimpleKyberProxy = ISimpleKyberProxy( kKyberNetworkProxy );
IKyberNetworkProxy cKyberProxy = IKyberNetworkProxy( kKyberNetworkProxy );
ERC20 cSrcToken = ERC20(SrcToken);
ERC20 cDestToken = ERC20(DestToken);
uint256 destAmount = 0;
uint256 minConversionRate = 0;
( minConversionRate, ) =
cKyberProxy.getExpectedRate( cSrcToken, cDestToken, srcQty );
if (SrcToken == kETH) {
require(cSrcToken.approve(destAddress, 0), "approval to 0 failed");
require(cSrcToken.approve(destAddress, srcQty), "approval to srcQty failed");
emit ApprovedSrcSwap( SrcToken, srcQty );
if (DestToken == kETH) {
destAmount = cSimpleKyberProxy.swapTokenToEther(cSrcToken, srcQty, minConversionRate);
destAmount = cSimpleKyberProxy.swapTokenToToken( cSrcToken, srcQty, cDestToken, minConversionRate);
}
}
emit KyberSwapped( address(cSrcToken), srcQty, address(cDestToken), destAmount, minConversionRate );
return destAmount;
}
event ChangedOwner( address payable owner, address payable newOwner );
event Liquidated( address account, address token, uint256 amount );
event PassThru( uint256 liquidateampount );
event Withdrawn( address token, uint256 amount );
event Borrowed( address tokenborrowed, uint256 amount );
event Received( address, uint );
event KyberSwapped( address fromtoken, uint256 fromamount, address totoken, uint256 toamount, uint256 minConversionRate );
event MinKyberConversionRate(uint256 srcQty, uint256 minConversionRate );
event ApprovedSrcSwap( address SrcToken, uint256 srcQty );
event ExpectedRate( uint256 minConversionRate );
event DebugLineNo( uint uiLineNo );
| 16,230,000 |
./full_match/1/0x95D2e9aced656f4dE01f9f54B4A2a1B2787A074C/sources/src/Token.sol | 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 `requestedDecrease`. NOTE: Although this function is designed to avoid double spending with {approval}, it can still be frontrunned, preventing any attempt of allowance reduction./ | function decreaseAllowance(address spender, uint256 requestedDecrease) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < requestedDecrease) {
revert("ERC20: decreased allowance below zero");
}
unchecked {
_approve(owner, spender, currentAllowance - requestedDecrease);
}
return true;
}
| 3,122,728 |
./full_match/1/0x6cE532764F3c7700cdA0967a6aC5B4f636201491/sources/contracts/PreSaleDop.sol | Creates a new Round startTime The startTime of the round endTime The endTime of the round price The dopToken price in the round | function createNewRound(
uint256 startTime,
uint256 endTime,
uint256 price
) external onlyOwner {
RoundData memory roundData = rounds[_roundIndex];
uint8 newRound = ++_roundIndex;
if (price < roundData.price) {
revert PriceLessThanOldRound();
}
if (startTime < roundData.endTime) {
revert InvalidStartTime();
}
_verifyRound(startTime, endTime, price);
roundData = RoundData({
startTime: startTime,
endTime: endTime,
price: price
});
rounds[newRound] = roundData;
}
| 2,940,971 |
./partial_match/42220/0x553a2a1B70725C1042A0D76e16f4f5a683648dEB/sources/src/shared/UsesCore.sol | Contract is already init, and cannot be initialized again. Selector 0xef34ca5c. Attempting to set Core address to zero. Selector 0xf71b2b01. The slot at which the core contract address is stored. 0xc6a342a8a7e6992aa2a41ce922cb4520fcb72f46fb4f9e41cdd65930adc9ca4c. Read the core contract address. return _core The Wormhole core contract. | function core() public view returns (IWormhole _core) {
uint256 slot = uint256(CORE_SLOT);
assembly ("memory-safe") {
_core := sload(slot)
}
}
| 3,498,031 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
import "../strategy-qi-farm-base.sol";
contract StrategyBenqiWavax is StrategyQiFarmBase {
address public constant qiavax = 0x5C0401e81Bc07Ca70fAD469b451682c0d747Ef1c; //lending receipt token
constructor(
address _governance,
address _strategist,
address _controller,
address _timelock
)
public
StrategyQiFarmBase(
wavax,
qiavax,
_governance,
_strategist,
_controller,
_timelock
)
{}
function deposit() public override {
uint256 _want = IERC20(want).balanceOf(address(this));
// get the value of Native Avax in the contract
uint256 _avax = address(this).balance;
if (_want > 0) {
// unwrap wavax to avax for benqi
WAVAX(want).withdraw(_want);
// confirm that msg.sender received avax
require(address(this).balance >= _want, "!unwrap unsuccessful");
// mint qiTokens external payable
IQiAvax(qiavax).mint{value: _want}();
// confirm that qiTokens is received in exchange
require( IQiToken(qiavax).balanceOf(address(this)) > 0 , "qitokens not received" );
//check if there is a balance of Native Avax Outstanding
if (_avax > 0) {
// confirm that msg.sender received avax
require(address(this).balance >= _avax, "!unwrap unsuccessful");
// mint qiTokens external payable
IQiAvax(qiavax).mint{value: _avax}();
// confirm that qiTokens is received in exchange
require( IQiToken(qiavax).balanceOf(address(this)) > 0 , "qitokens not received" );
}
}
}
function _withdrawSome(uint256 _amount) internal override returns (uint256) {
uint256 _want = balanceOfWant();
if (_want < _amount) {
uint256 _redeem = _amount.sub(_want);
// Make sure market can cover liquidity
require(IQiToken(qiavax).getCash() >= _redeem, "!cash-liquidity");
// How much borrowed amount do we need to free?
uint256 borrowed = getBorrowed();
uint256 supplied = getSupplied();
uint256 curLeverage = getCurrentLeverage();
uint256 borrowedToBeFree = _redeem.mul(curLeverage).div(1e18);
// If the amount we need to free is > borrowed
// Just free up all the borrowed amount
if (borrowed > 0) {
if (borrowedToBeFree > borrowed) {
this.deleverageToMin();
} else {
// Otherwise just keep freeing up borrowed amounts until
// we hit a safe number to redeem our underlying
this.deleverageUntil(supplied.sub(borrowedToBeFree));
}
}
// Redeems underlying
require(IQiToken(qiavax).redeemUnderlying(_redeem) == 0, "!redeem");
// wrap avax to wavax
WAVAX(wavax).deposit{value: _redeem}();
// confirm contract address now holds enough wavax;
require(IERC20(want).balanceOf(address(this)) >= _amount, "!NotEnoughWavax");
}
return _amount;
}
// **** Views **** //
function getName() external override pure returns (string memory) {
return "StrategyBenqiAvax";
}
} | get the value of Native Avax in the contract unwrap wavax to avax for benqi confirm that msg.sender received avax mint qiTokens external payable confirm that qiTokens is received in exchangecheck if there is a balance of Native Avax Outstanding confirm that msg.sender received avax mint qiTokens external payable confirm that qiTokens is received in exchange | function deposit() public override {
uint256 _want = IERC20(want).balanceOf(address(this));
uint256 _avax = address(this).balance;
if (_want > 0) {
WAVAX(want).withdraw(_want);
require(address(this).balance >= _want, "!unwrap unsuccessful");
require( IQiToken(qiavax).balanceOf(address(this)) > 0 , "qitokens not received" );
if (_avax > 0) {
require(address(this).balance >= _avax, "!unwrap unsuccessful");
require( IQiToken(qiavax).balanceOf(address(this)) > 0 , "qitokens not received" );
}
}
}
| 12,872,452 |
./full_match/84531/0x9eb38079e6AA48C3A5F4896DBAFd78F9Dd3D0822/sources/Payable.sol | Function to transfer Ether from this contract to address from input | function transfer(address payable _to, uint _amount) view external {
}
| 11,499,557 |
/**
*Submitted for verification at Etherscan.io on 2019-06-06
*/
/**
* Source Code first verified at https://etherscan.io on Wednesday, April 24, 2019
(UTC) */
pragma solidity ^0.4.25;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title math operations that returns specific size reults (32, 64 and 256
* bits)
*/
library SafeMath {
/**
* @dev Multiplies two numbers and returns a uint64
* @param a A number
* @param b A number
* @return a * b as a uint64
*/
function mul64(uint256 a, uint256 b) internal pure returns (uint64) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
require(c < 2**64);
return uint64(c);
}
/**
* @dev Divides two numbers and returns a uint64
* @param a A number
* @param b A number
* @return a / b as a uint64
*/
function div64(uint256 a, uint256 b) internal pure returns (uint64) {
uint256 c = a / b;
require(c < 2**64);
/* solcov ignore next */
return uint64(c);
}
/**
* @dev Substracts two numbers and returns a uint64
* @param a A number
* @param b A number
* @return a - b as a uint64
*/
function sub64(uint256 a, uint256 b) internal pure returns (uint64) {
require(b <= a);
uint256 c = a - b;
require(c < 2**64);
/* solcov ignore next */
return uint64(c);
}
/**
* @dev Adds two numbers and returns a uint64
* @param a A number
* @param b A number
* @return a + b as a uint64
*/
function add64(uint256 a, uint256 b) internal pure returns (uint64) {
uint256 c = a + b;
require(c >= a && c < 2**64);
/* solcov ignore next */
return uint64(c);
}
/**
* @dev Multiplies two numbers and returns a uint32
* @param a A number
* @param b A number
* @return a * b as a uint32
*/
function mul32(uint256 a, uint256 b) internal pure returns (uint32) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
require(c < 2**32);
/* solcov ignore next */
return uint32(c);
}
/**
* @dev Divides two numbers and returns a uint32
* @param a A number
* @param b A number
* @return a / b as a uint32
*/
function div32(uint256 a, uint256 b) internal pure returns (uint32) {
uint256 c = a / b;
require(c < 2**32);
/* solcov ignore next */
return uint32(c);
}
/**
* @dev Substracts two numbers and returns a uint32
* @param a A number
* @param b A number
* @return a - b as a uint32
*/
function sub32(uint256 a, uint256 b) internal pure returns (uint32) {
require(b <= a);
uint256 c = a - b;
require(c < 2**32);
/* solcov ignore next */
return uint32(c);
}
/**
* @dev Adds two numbers and returns a uint32
* @param a A number
* @param b A number
* @return a + b as a uint32
*/
function add32(uint256 a, uint256 b) internal pure returns (uint32) {
uint256 c = a + b;
require(c >= a && c < 2**32);
return uint32(c);
}
/**
* @dev Multiplies two numbers and returns a uint256
* @param a A number
* @param b A number
* @return a * b as a uint256
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
/* solcov ignore next */
return c;
}
/**
* @dev Divides two numbers and returns a uint256
* @param a A number
* @param b A number
* @return a / b as a uint256
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
/* solcov ignore next */
return c;
}
/**
* @dev Substracts two numbers and returns a uint256
* @param a A number
* @param b A number
* @return a - b as a uint256
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
return a - b;
}
/**
* @dev Adds two numbers and returns a uint256
* @param a A number
* @param b A number
* @return a + b as a uint256
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
}
/**
* @title Merkle Tree's proof helper contract
*/
library Merkle {
/**
* @dev calculates the hash of two child nodes on the merkle tree.
* @param a Hash of the left child node.
* @param b Hash of the right child node.
* @return sha3 hash of the resulting node.
*/
function combinedHash(bytes32 a, bytes32 b) public pure returns(bytes32) {
return keccak256(abi.encodePacked(a, b));
}
/**
* @dev calculates a root hash associated with a Merkle proof
* @param proof array of proof hashes
* @param key index of the leaf element list.
* this key indicates the specific position of the leaf
* in the merkle tree. It will be used to know if the
* node that will be hashed along with the proof node
* is placed on the right or the left of the current
* tree level. That is achieved by doing the modulo of
* the current key/position. A new level of nodes will
* be evaluated after that, and the new left or right
* position is obtained by doing the same operation,
* after dividing the key/position by two.
* @param leaf the leaf element to verify on the set.
* @return the hash of the Merkle proof. Should match the Merkle root
* if the proof is valid
*/
function getProofRootHash(bytes32[] memory proof, uint256 key, bytes32 leaf) public pure returns(bytes32) {
bytes32 hash = keccak256(abi.encodePacked(leaf));
uint256 k = key;
for(uint i = 0; i<proof.length; i++) {
uint256 bit = k % 2;
k = k / 2;
if (bit == 0)
hash = combinedHash(hash, proof[i]);
else
hash = combinedHash(proof[i], hash);
}
return hash;
}
}
/**
* @title Data Structures for BatPay: Accounts, Payments & Challenge
*/
contract Data {
struct Account {
address owner;
uint64 balance;
uint32 lastCollectedPaymentId;
}
struct BulkRegistration {
bytes32 rootHash;
uint32 recordCount;
uint32 smallestRecordId;
}
struct Payment {
uint32 fromAccountId;
uint64 amount;
uint64 fee;
uint32 smallestAccountId;
uint32 greatestAccountId;
uint32 totalNumberOfPayees;
uint64 lockTimeoutBlockNumber;
bytes32 paymentDataHash;
bytes32 lockingKeyHash;
bytes32 metadata;
}
struct CollectSlot {
uint32 minPayIndex;
uint32 maxPayIndex;
uint64 amount;
uint64 delegateAmount;
uint32 to;
uint64 block;
uint32 delegate;
uint32 challenger;
uint32 index;
uint64 challengeAmount;
uint8 status;
address addr;
bytes32 data;
}
struct Config {
uint32 maxBulk;
uint32 maxTransfer;
uint32 challengeBlocks;
uint32 challengeStepBlocks;
uint64 collectStake;
uint64 challengeStake;
uint32 unlockBlocks;
uint32 massExitIdBlocks;
uint32 massExitIdStepBlocks;
uint32 massExitBalanceBlocks;
uint32 massExitBalanceStepBlocks;
uint64 massExitStake;
uint64 massExitChallengeStake;
uint64 maxCollectAmount;
}
Config public params;
address public owner;
uint public constant MAX_ACCOUNT_ID = 2**32-1; // Maximum account id (32-bits)
uint public constant NEW_ACCOUNT_FLAG = 2**256-1; // Request registration of new account
uint public constant INSTANT_SLOT = 32768;
}
/**
* @title Accounts, methods to manage accounts and balances
*/
contract Accounts is Data {
event BulkRegister(uint bulkSize, uint smallestAccountId, uint bulkId );
event AccountRegistered(uint accountId, address accountAddress);
IERC20 public token;
Account[] public accounts;
BulkRegistration[] public bulkRegistrations;
/**
* @dev determines whether accountId is valid
* @param accountId an account id
* @return boolean
*/
function isValidId(uint accountId) public view returns (bool) {
return (accountId < accounts.length);
}
/**
* @dev determines whether accountId is the owner of the account
* @param accountId an account id
* @return boolean
*/
function isAccountOwner(uint accountId) public view returns (bool) {
return isValidId(accountId) && msg.sender == accounts[accountId].owner;
}
/**
* @dev modifier to restrict that accountId is valid
* @param accountId an account id
*/
modifier validId(uint accountId) {
require(isValidId(accountId), "accountId is not valid");
_;
}
/**
* @dev modifier to restrict that accountId is owner
* @param accountId an account ID
*/
modifier onlyAccountOwner(uint accountId) {
require(isAccountOwner(accountId), "Only account owner can invoke this method");
_;
}
/**
* @dev Reserve accounts but delay assigning addresses.
* Accounts will be claimed later using MerkleTree's rootHash.
* @param bulkSize Number of accounts to reserve.
* @param rootHash Hash of the root node of the Merkle Tree referencing the list of addresses.
*/
function bulkRegister(uint256 bulkSize, bytes32 rootHash) public {
require(bulkSize > 0, "Bulk size can't be zero");
require(bulkSize < params.maxBulk, "Cannot register this number of ids simultaneously");
require(SafeMath.add(accounts.length, bulkSize) <= MAX_ACCOUNT_ID, "Cannot register: ran out of ids");
require(rootHash > 0, "Root hash can't be zero");
emit BulkRegister(bulkSize, accounts.length, bulkRegistrations.length);
bulkRegistrations.push(BulkRegistration(rootHash, uint32(bulkSize), uint32(accounts.length)));
accounts.length = SafeMath.add(accounts.length, bulkSize);
}
/** @dev Complete registration for a reserved account by showing the
* bulkRegistration-id and Merkle proof associated with this address
* @param addr Address claiming this account
* @param proof Merkle proof for address and id
* @param accountId Id of the account to be registered.
* @param bulkId BulkRegistration id for the transaction reserving this account
*/
function claimBulkRegistrationId(address addr, bytes32[] memory proof, uint accountId, uint bulkId) public {
require(bulkId < bulkRegistrations.length, "the bulkId referenced is invalid");
uint smallestAccountId = bulkRegistrations[bulkId].smallestRecordId;
uint n = bulkRegistrations[bulkId].recordCount;
bytes32 rootHash = bulkRegistrations[bulkId].rootHash;
bytes32 hash = Merkle.getProofRootHash(proof, SafeMath.sub(accountId, smallestAccountId), bytes32(addr));
require(accountId >= smallestAccountId && accountId < smallestAccountId + n,
"the accountId specified is not part of that bulk registration slot");
require(hash == rootHash, "invalid Merkle proof");
emit AccountRegistered(accountId, addr);
accounts[accountId].owner = addr;
}
/**
* @dev Register a new account
* @return the id of the new account
*/
function register() public returns (uint32 ret) {
require(accounts.length < MAX_ACCOUNT_ID, "no more accounts left");
ret = (uint32)(accounts.length);
accounts.push(Account(msg.sender, 0, 0));
emit AccountRegistered(ret, msg.sender);
return ret;
}
/**
* @dev withdraw tokens from the BatchPayment contract into the original address.
* @param amount Amount of tokens to withdraw.
* @param accountId Id of the user requesting the withdraw.
*/
function withdraw(uint64 amount, uint256 accountId)
external
onlyAccountOwner(accountId)
{
uint64 balance = accounts[accountId].balance;
require(balance >= amount, "insufficient funds");
require(amount > 0, "amount should be nonzero");
balanceSub(accountId, amount);
require(token.transfer(msg.sender, amount), "transfer failed");
}
/**
* @dev Deposit tokens into the BatchPayment contract to enable scalable payments
* @param amount Amount of tokens to deposit on `accountId`. User should have
* enough balance and issue an `approve()` method prior to calling this.
* @param accountId The id of the user account. In case `NEW_ACCOUNT_FLAG` is used,
* a new account will be registered and the requested amount will be
* deposited in a single operation.
*/
function deposit(uint64 amount, uint256 accountId) external {
require(accountId < accounts.length || accountId == NEW_ACCOUNT_FLAG, "invalid accountId");
require(amount > 0, "amount should be positive");
if (accountId == NEW_ACCOUNT_FLAG) {
// new account
uint newId = register();
accounts[newId].balance = amount;
} else {
// existing account
balanceAdd(accountId, amount);
}
require(token.transferFrom(msg.sender, address(this), amount), "transfer failed");
}
/**
* @dev Increase the specified account balance by `amount` tokens.
* @param accountId An account id
* @param amount number of tokens
*/
function balanceAdd(uint accountId, uint64 amount)
internal
validId(accountId)
{
accounts[accountId].balance = SafeMath.add64(accounts[accountId].balance, amount);
}
/**
* @dev Substract `amount` tokens from the specified account's balance
* @param accountId An account id
* @param amount number of tokens
*/
function balanceSub(uint accountId, uint64 amount)
internal
validId(accountId)
{
uint64 balance = accounts[accountId].balance;
require(balance >= amount, "not enough funds");
accounts[accountId].balance = SafeMath.sub64(balance, amount);
}
/**
* @dev returns the balance associated with the account in tokens
* @param accountId account requested.
*/
function balanceOf(uint accountId)
external
view
validId(accountId)
returns (uint64)
{
return accounts[accountId].balance;
}
/**
* @dev gets number of accounts registered and reserved.
* @return returns the size of the accounts array.
*/
function getAccountsLength() external view returns (uint) {
return accounts.length;
}
/**
* @dev gets the number of bulk registrations performed
* @return the size of the bulkRegistrations array.
*/
function getBulkLength() external view returns (uint) {
return bulkRegistrations.length;
}
}
/**
* @title Challenge helper library
*/
library Challenge {
uint8 public constant PAY_DATA_HEADER_MARKER = 0xff; // marker in payData header
/**
* @dev Reverts if challenge period has expired or Collect Slot status is
* not a valid one.
*/
modifier onlyValidCollectSlot(Data.CollectSlot storage collectSlot, uint8 validStatus) {
require(!challengeHasExpired(collectSlot), "Challenge has expired");
require(isSlotStatusValid(collectSlot, validStatus), "Wrong Collect Slot status");
_;
}
/**
* @return true if the current block number is greater or equal than the
* allowed block for this challenge.
*/
function challengeHasExpired(Data.CollectSlot storage collectSlot) public view returns (bool) {
return collectSlot.block <= block.number;
}
/**
* @return true if the Slot status is valid.
*/
function isSlotStatusValid(Data.CollectSlot storage collectSlot, uint8 validStatus) public view returns (bool) {
return collectSlot.status == validStatus;
}
/** @dev calculates new block numbers based on the current block and a
* delta constant specified by the protocol policy.
* @param delta number of blocks into the future to calculate.
* @return future block number.
*/
function getFutureBlock(uint delta) public view returns(uint64) {
return SafeMath.add64(block.number, delta);
}
/**
* @dev Inspects the compact payment list provided and calculates the sum
* of the amounts referenced
* @param data binary array, with 12 bytes per item. 8-bytes amount,
* 4-bytes payment index.
* @return the sum of the amounts referenced on the array.
*/
function getDataSum(bytes memory data) public pure returns (uint sum) {
require(data.length > 0, "no data provided");
require(data.length % 12 == 0, "wrong data format, data length should be multiple of 12");
uint n = SafeMath.div(data.length, 12);
uint modulus = 2**64;
sum = 0;
// Get the sum of the stated amounts in data
// Each entry in data is [8-bytes amount][4-bytes payIndex]
for (uint i = 0; i < n; i++) {
// solium-disable-next-line security/no-inline-assembly
assembly {
let amount := mod(mload(add(data, add(8, mul(i, 12)))), modulus)
let result := add(sum, amount)
switch or(gt(result, modulus), eq(result, modulus))
case 1 { revert (0, 0) }
default { sum := result }
}
}
}
/**
* @dev Helper function that obtains the amount/payIndex pair located at
* position `index`.
* @param data binary array, with 12 bytes per item. 8-bytes amount,
* 4-bytes payment index.
* @param index Array item requested.
* @return amount and payIndex requested.
*/
function getDataAtIndex(bytes memory data, uint index) public pure returns (uint64 amount, uint32 payIndex) {
require(data.length > 0, "no data provided");
require(data.length % 12 == 0, "wrong data format, data length should be multiple of 12");
uint mod1 = 2**64;
uint mod2 = 2**32;
uint i = SafeMath.mul(index, 12);
require(i <= SafeMath.sub(data.length, 12), "index * 12 must be less or equal than (data.length - 12)");
// solium-disable-next-line security/no-inline-assembly
assembly {
amount := mod( mload(add(data, add(8, i))), mod1 )
payIndex := mod( mload(add(data, add(12, i))), mod2 )
}
}
/**
* @dev obtains the number of bytes per id in `payData`
* @param payData efficient binary representation of a list of accountIds
* @return bytes per id in `payData`
*/
function getBytesPerId(bytes payData) internal pure returns (uint) {
// payData includes a 2 byte header and a list of ids
// [0xff][bytesPerId]
uint len = payData.length;
require(len >= 2, "payData length should be >= 2");
require(uint8(payData[0]) == PAY_DATA_HEADER_MARKER, "payData header missing");
uint bytesPerId = uint(payData[1]);
require(bytesPerId > 0 && bytesPerId < 32, "second byte of payData should be positive and less than 32");
// remaining bytes should be a multiple of bytesPerId
require((len - 2) % bytesPerId == 0,
"payData length is invalid, all payees must have same amount of bytes (payData[1])");
return bytesPerId;
}
/**
* @dev Process payData, inspecting the list of ids, accumulating the amount for
* each entry of `id`.
* `payData` includes 2 header bytes, followed by n bytesPerId-bytes entries.
* `payData` format: [byte 0xff][byte bytesPerId][delta 0][delta 1]..[delta n-1]
* @param payData List of payees of a specific Payment, with the above format.
* @param id ID to look for in `payData`
* @param amount amount per occurrence of `id` in `payData`
* @return the amount sum for all occurrences of `id` in `payData`
*/
function getPayDataSum(bytes memory payData, uint id, uint amount) public pure returns (uint sum) {
uint bytesPerId = getBytesPerId(payData);
uint modulus = 1 << SafeMath.mul(bytesPerId, 8);
uint currentId = 0;
sum = 0;
for (uint i = 2; i < payData.length; i += bytesPerId) {
// Get next id delta from paydata
// currentId += payData[2+i*bytesPerId]
// solium-disable-next-line security/no-inline-assembly
assembly {
currentId := add(
currentId,
mod(
mload(add(payData, add(i, bytesPerId))),
modulus))
switch eq(currentId, id)
case 1 { sum := add(sum, amount) }
}
}
}
/**
* @dev calculates the number of accounts included in payData
* @param payData efficient binary representation of a list of accountIds
* @return number of accounts present
*/
function getPayDataCount(bytes payData) public pure returns (uint) {
uint bytesPerId = getBytesPerId(payData);
// calculate number of records
return SafeMath.div(payData.length - 2, bytesPerId);
}
/**
* @dev function. Phase I of the challenging game
* @param collectSlot Collect slot
* @param config Various parameters
* @param accounts a reference to the main accounts array
* @param challenger id of the challenger user
*/
function challenge_1(
Data.CollectSlot storage collectSlot,
Data.Config storage config,
Data.Account[] storage accounts,
uint32 challenger
)
public
onlyValidCollectSlot(collectSlot, 1)
{
require(accounts[challenger].balance >= config.challengeStake, "not enough balance");
collectSlot.status = 2;
collectSlot.challenger = challenger;
collectSlot.block = getFutureBlock(config.challengeStepBlocks);
accounts[challenger].balance -= config.challengeStake;
}
/**
* @dev Internal function. Phase II of the challenging game
* @param collectSlot Collect slot
* @param config Various parameters
* @param data Binary array listing the payments in which the user was referenced.
*/
function challenge_2(
Data.CollectSlot storage collectSlot,
Data.Config storage config,
bytes memory data
)
public
onlyValidCollectSlot(collectSlot, 2)
{
require(getDataSum(data) == collectSlot.amount, "data doesn't represent collected amount");
collectSlot.data = keccak256(data);
collectSlot.status = 3;
collectSlot.block = getFutureBlock(config.challengeStepBlocks);
}
/**
* @dev Internal function. Phase III of the challenging game
* @param collectSlot Collect slot
* @param config Various parameters
* @param data Binary array listing the payments in which the user was referenced.
* @param disputedPaymentIndex index selecting the disputed payment
*/
function challenge_3(
Data.CollectSlot storage collectSlot,
Data.Config storage config,
bytes memory data,
uint32 disputedPaymentIndex
)
public
onlyValidCollectSlot(collectSlot, 3)
{
require(collectSlot.data == keccak256(data),
"data mismatch, collected data hash doesn't match provided data hash");
(collectSlot.challengeAmount, collectSlot.index) = getDataAtIndex(data, disputedPaymentIndex);
collectSlot.status = 4;
collectSlot.block = getFutureBlock(config.challengeStepBlocks);
}
/**
* @dev Internal function. Phase IV of the challenging game
* @param collectSlot Collect slot
* @param payments a reference to the BatPay payments array
* @param payData binary data describing the list of account receiving
* tokens on the selected transfer
*/
function challenge_4(
Data.CollectSlot storage collectSlot,
Data.Payment[] storage payments,
bytes memory payData
)
public
onlyValidCollectSlot(collectSlot, 4)
{
require(collectSlot.index >= collectSlot.minPayIndex && collectSlot.index < collectSlot.maxPayIndex,
"payment referenced is out of range");
Data.Payment memory p = payments[collectSlot.index];
require(keccak256(payData) == p.paymentDataHash,
"payData mismatch, payment's data hash doesn't match provided payData hash");
require(p.lockingKeyHash == 0, "payment is locked");
uint collected = getPayDataSum(payData, collectSlot.to, p.amount);
// Check if id is included in bulkRegistration within payment
if (collectSlot.to >= p.smallestAccountId && collectSlot.to < p.greatestAccountId) {
collected = SafeMath.add(collected, p.amount);
}
require(collected == collectSlot.challengeAmount,
"amount mismatch, provided payData sum doesn't match collected challenge amount");
collectSlot.status = 5;
}
/**
* @dev the challenge was completed successfully, or the delegate failed to respond on time.
* The challenger will collect the stake.
* @param collectSlot Collect slot
* @param config Various parameters
* @param accounts a reference to the main accounts array
*/
function challenge_success(
Data.CollectSlot storage collectSlot,
Data.Config storage config,
Data.Account[] storage accounts
)
public
{
require((collectSlot.status == 2 || collectSlot.status == 4),
"Wrong Collect Slot status");
require(challengeHasExpired(collectSlot),
"Challenge not yet finished");
accounts[collectSlot.challenger].balance = SafeMath.add64(
accounts[collectSlot.challenger].balance,
SafeMath.add64(config.collectStake, config.challengeStake));
collectSlot.status = 0;
}
/**
* @dev Internal function. The delegate proved the challenger wrong, or
* the challenger failed to respond on time. The delegae collects the stake.
* @param collectSlot Collect slot
* @param config Various parameters
* @param accounts a reference to the main accounts array
*/
function challenge_failed(
Data.CollectSlot storage collectSlot,
Data.Config storage config,
Data.Account[] storage accounts
)
public
{
require(collectSlot.status == 5 || (collectSlot.status == 3 && block.number >= collectSlot.block),
"challenge not completed");
// Challenge failed
// delegate wins Stake
accounts[collectSlot.delegate].balance = SafeMath.add64(
accounts[collectSlot.delegate].balance,
config.challengeStake);
// reset slot to status=1, waiting for challenges
collectSlot.challenger = 0;
collectSlot.status = 1;
collectSlot.block = getFutureBlock(config.challengeBlocks);
}
/**
* @dev Helps verify a ECDSA signature, while recovering the signing address.
* @param hash Hash of the signed message
* @param sig binary representation of the r, s & v parameters.
* @return address of the signer if data provided is valid, zero otherwise.
*/
function recoverHelper(bytes32 hash, bytes sig) public pure returns (address) {
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return address(0);
}
return ecrecover(prefixedHash, v, r, s);
}
}
/**
* @title Payments and Challenge game - Performs the operations associated with
* transfer and the different steps of the collect challenge game.
*/
contract Payments is Accounts {
event PaymentRegistered(
uint32 indexed payIndex,
uint indexed from,
uint totalNumberOfPayees,
uint amount
);
event PaymentUnlocked(uint32 indexed payIndex, bytes key);
event PaymentRefunded(uint32 beneficiaryAccountId, uint64 amountRefunded);
/**
* Event for collection logging. Off-chain monitoring services may listen
* to this event to trigger challenges.
*/
event Collect(
uint indexed delegate,
uint indexed slot,
uint indexed to,
uint32 fromPayindex,
uint32 toPayIndex,
uint amount
);
event Challenge1(uint indexed delegate, uint indexed slot, uint challenger);
event Challenge2(uint indexed delegate, uint indexed slot);
event Challenge3(uint indexed delegate, uint indexed slot, uint index);
event Challenge4(uint indexed delegate, uint indexed slot);
event ChallengeSuccess(uint indexed delegate, uint indexed slot);
event ChallengeFailed(uint indexed delegate, uint indexed slot);
Payment[] public payments;
mapping (uint32 => mapping (uint32 => CollectSlot)) public collects;
/**
* @dev Register token payment to multiple recipients
* @param fromId Account id for the originator of the transaction
* @param amount Amount of tokens to pay each destination.
* @param fee Fee in tokens to be payed to the party providing the unlocking service
* @param payData Efficient representation of the destination account list
* @param newCount Number of new destination accounts that will be reserved during the registerPayment transaction
* @param rootHash Hash of the root hash of the Merkle tree listing the addresses reserved.
* @param lockingKeyHash hash resulting of calculating the keccak256 of
* of the key locking this payment to help in atomic data swaps.
* This hash will later be used by the `unlock` function to unlock the payment we are registering.
* The `lockingKeyHash` must be equal to the keccak256 of the packed
* encoding of the unlockerAccountId and the key used by the unlocker to encrypt the traded data:
* `keccak256(abi.encodePacked(unlockerAccountId, key))`
* DO NOT use previously used locking keys, since an attacker could realize that by comparing key hashes
* @param metadata Application specific data to be stored associated with the payment
*/
function registerPayment(
uint32 fromId,
uint64 amount,
uint64 fee,
bytes payData,
uint newCount,
bytes32 rootHash,
bytes32 lockingKeyHash,
bytes32 metadata
)
external
{
require(payments.length < 2**32, "Cannot add more payments");
require(isAccountOwner(fromId), "Invalid fromId");
require(amount > 0, "Invalid amount");
require(newCount == 0 || rootHash > 0, "Invalid root hash"); // although bulkRegister checks this, we anticipate
require(fee == 0 || lockingKeyHash > 0, "Invalid lock hash");
Payment memory p;
// Prepare a Payment struct
p.totalNumberOfPayees = SafeMath.add32(Challenge.getPayDataCount(payData), newCount);
require(p.totalNumberOfPayees > 0, "Invalid number of payees, should at least be 1 payee");
require(p.totalNumberOfPayees < params.maxTransfer,
"Too many payees, it should be less than config maxTransfer");
p.fromAccountId = fromId;
p.amount = amount;
p.fee = fee;
p.lockingKeyHash = lockingKeyHash;
p.metadata = metadata;
p.smallestAccountId = uint32(accounts.length);
p.greatestAccountId = SafeMath.add32(p.smallestAccountId, newCount);
p.lockTimeoutBlockNumber = SafeMath.add64(block.number, params.unlockBlocks);
p.paymentDataHash = keccak256(abi.encodePacked(payData));
// calculate total cost of payment
uint64 totalCost = SafeMath.mul64(amount, p.totalNumberOfPayees);
totalCost = SafeMath.add64(totalCost, fee);
// Check that fromId has enough balance and substract totalCost
balanceSub(fromId, totalCost);
// If this operation includes new accounts, do a bulkRegister
if (newCount > 0) {
bulkRegister(newCount, rootHash);
}
// Save the new Payment
payments.push(p);
emit PaymentRegistered(SafeMath.sub32(payments.length, 1), p.fromAccountId, p.totalNumberOfPayees, p.amount);
}
/**
* @dev provide the required key, releasing the payment and enabling the buyer decryption the digital content.
* @param payIndex payment Index associated with the registerPayment operation.
* @param unlockerAccountId id of the party providing the unlocking service. Fees wil be payed to this id.
* @param key Cryptographic key used to encrypt traded data.
*/
function unlock(uint32 payIndex, uint32 unlockerAccountId, bytes memory key) public returns(bool) {
require(payIndex < payments.length, "invalid payIndex, payments is not that long yet");
require(isValidId(unlockerAccountId), "Invalid unlockerAccountId");
require(block.number < payments[payIndex].lockTimeoutBlockNumber, "Hash lock expired");
bytes32 h = keccak256(abi.encodePacked(unlockerAccountId, key));
require(h == payments[payIndex].lockingKeyHash, "Invalid key");
payments[payIndex].lockingKeyHash = bytes32(0);
balanceAdd(unlockerAccountId, payments[payIndex].fee);
emit PaymentUnlocked(payIndex, key);
return true;
}
/**
* @dev Enables the buyer to recover funds associated with a `registerPayment()`
* operation for which decryption keys were not provided.
* @param payIndex Index of the payment transaction associated with this request.
* @return true if the operation succeded.
*/
function refundLockedPayment(uint32 payIndex) external returns (bool) {
require(payIndex < payments.length, "invalid payIndex, payments is not that long yet");
require(payments[payIndex].lockingKeyHash != 0, "payment is already unlocked");
require(block.number >= payments[payIndex].lockTimeoutBlockNumber, "Hash lock has not expired yet");
Payment memory payment = payments[payIndex];
require(payment.totalNumberOfPayees > 0, "payment already refunded");
uint64 total = SafeMath.add64(
SafeMath.mul64(payment.totalNumberOfPayees, payment.amount),
payment.fee
);
payment.totalNumberOfPayees = 0;
payment.fee = 0;
payment.amount = 0;
payments[payIndex] = payment;
// Complete refund
balanceAdd(payment.fromAccountId, total);
emit PaymentRefunded(payment.fromAccountId, total);
return true;
}
/**
* @dev let users claim pending balance associated with prior transactions
Users ask a delegate to complete the transaction on their behalf,
the delegate calculates the apropiate amount (declaredAmount) and
waits for a possible challenger.
If this is an instant collect, tokens are transfered immediatly.
* @param delegate id of the delegate account performing the operation on the name of the user.
* @param slotId Individual slot used for the challenge game.
* @param toAccountId Destination of the collect operation.
* @param maxPayIndex payIndex of the first payment index not covered by this application.
* @param declaredAmount amount of tokens owed to this user account
* @param fee fee in tokens to be paid for the end user help.
* @param destination Address to withdraw the full account balance.
* @param signature An R,S,V ECDS signature provided by a user.
*/
function collect(
uint32 delegate,
uint32 slotId,
uint32 toAccountId,
uint32 maxPayIndex,
uint64 declaredAmount,
uint64 fee,
address destination,
bytes memory signature
)
public
{
// Check delegate and toAccountId are valid
require(isAccountOwner(delegate), "invalid delegate");
require(isValidId(toAccountId), "toAccountId must be a valid account id");
// make sure the game slot is empty (release it if necessary)
freeSlot(delegate, slotId);
Account memory tacc = accounts[toAccountId];
require(tacc.owner != 0, "account registration has to be completed");
if (delegate != toAccountId) {
// If "toAccountId" != delegate, check who signed this transaction
bytes32 hash =
keccak256(
abi.encodePacked(
address(this), delegate, toAccountId, tacc.lastCollectedPaymentId,
maxPayIndex, declaredAmount, fee, destination
));
require(Challenge.recoverHelper(hash, signature) == tacc.owner, "Bad user signature");
}
// Check maxPayIndex is valid
require(maxPayIndex > 0 && maxPayIndex <= payments.length,
"invalid maxPayIndex, payments is not that long yet");
require(maxPayIndex > tacc.lastCollectedPaymentId, "account already collected payments up to maxPayIndex");
require(payments[maxPayIndex - 1].lockTimeoutBlockNumber < block.number,
"cannot collect payments that can be unlocked");
// Check if declaredAmount and fee are valid
require(declaredAmount <= params.maxCollectAmount, "declaredAmount is too big");
require(fee <= declaredAmount, "fee is too big, should be smaller than declaredAmount");
// Prepare the challenge slot
CollectSlot storage sl = collects[delegate][slotId];
sl.delegate = delegate;
sl.minPayIndex = tacc.lastCollectedPaymentId;
sl.maxPayIndex = maxPayIndex;
sl.amount = declaredAmount;
sl.to = toAccountId;
sl.block = Challenge.getFutureBlock(params.challengeBlocks);
sl.status = 1;
// Calculate how many tokens needs the delegate, and setup delegateAmount and addr
uint64 needed = params.collectStake;
// check if this is an instant collect
if (slotId >= INSTANT_SLOT) {
uint64 declaredAmountLessFee = SafeMath.sub64(declaredAmount, fee);
sl.delegateAmount = declaredAmount;
needed = SafeMath.add64(needed, declaredAmountLessFee);
sl.addr = address(0);
// Instant-collect, toAccount gets the declaredAmount now
balanceAdd(toAccountId, declaredAmountLessFee);
} else
{ // not instant-collect
sl.delegateAmount = fee;
sl.addr = destination;
}
// Check delegate has enough funds
require(accounts[delegate].balance >= needed, "not enough funds");
// Update the lastCollectPaymentId for the toAccount
accounts[toAccountId].lastCollectedPaymentId = uint32(maxPayIndex);
// Now the delegate Pays
balanceSub(delegate, needed);
// Proceed if the user is withdrawing its balance
if (destination != address(0) && slotId >= INSTANT_SLOT) {
uint64 toWithdraw = accounts[toAccountId].balance;
accounts[toAccountId].balance = 0;
require(token.transfer(destination, toWithdraw), "transfer failed");
}
emit Collect(delegate, slotId, toAccountId, tacc.lastCollectedPaymentId, maxPayIndex, declaredAmount);
}
/**
* @dev gets the number of payments issued
* @return returns the size of the payments array.
*/
function getPaymentsLength() external view returns (uint) {
return payments.length;
}
/**
* @dev initiate a challenge game
* @param delegate id of the delegate that performed the collect operation
* in the name of the end-user.
* @param slot slot used for the challenge game. Every user has a sperate
* set of slots
* @param challenger id of the user account challenging the delegate.
*/
function challenge_1(
uint32 delegate,
uint32 slot,
uint32 challenger
)
public
validId(delegate)
onlyAccountOwner(challenger)
{
Challenge.challenge_1(collects[delegate][slot], params, accounts, challenger);
emit Challenge1(delegate, slot, challenger);
}
/**
* @dev The delegate provides the list of payments that mentions the enduser
* @param delegate id of the delegate performing the collect operation
* @param slot slot used for the operation
* @param data binary list of payment indexes associated with this collect operation.
*/
function challenge_2(
uint32 delegate,
uint32 slot,
bytes memory data
)
public
onlyAccountOwner(delegate)
{
Challenge.challenge_2(collects[delegate][slot], params, data);
emit Challenge2(delegate, slot);
}
/**
* @dev the Challenger chooses a single index into the delegate provided data list
* @param delegate id of the delegate performing the collect operation
* @param slot slot used for the operation
* @param data binary list of payment indexes associated with this collect operation.
* @param index index into the data array for the payment id selected by the challenger
*/
function challenge_3(
uint32 delegate,
uint32 slot,
bytes memory data,
uint32 index
)
public
validId(delegate)
{
require(isAccountOwner(collects[delegate][slot].challenger), "only challenger can call challenge_2");
Challenge.challenge_3(collects[delegate][slot], params, data, index);
emit Challenge3(delegate, slot, index);
}
/**
* @dev the delegate provides proof that the destination account was
* included on that payment, winning the game
* @param delegate id of the delegate performing the collect operation
* @param slot slot used for the operation
*/
function challenge_4(
uint32 delegate,
uint32 slot,
bytes memory payData
)
public
onlyAccountOwner(delegate)
{
Challenge.challenge_4(
collects[delegate][slot],
payments,
payData
);
emit Challenge4(delegate, slot);
}
/**
* @dev the challenge was completed successfully. The delegate stake is slashed.
* @param delegate id of the delegate performing the collect operation
* @param slot slot used for the operation
*/
function challenge_success(
uint32 delegate,
uint32 slot
)
public
validId(delegate)
{
Challenge.challenge_success(collects[delegate][slot], params, accounts);
emit ChallengeSuccess(delegate, slot);
}
/**
* @dev The delegate won the challenge game. He gets the challenge stake.
* @param delegate id of the delegate performing the collect operation
* @param slot slot used for the operation
*/
function challenge_failed(
uint32 delegate,
uint32 slot
)
public
onlyAccountOwner(delegate)
{
Challenge.challenge_failed(collects[delegate][slot], params, accounts);
emit ChallengeFailed(delegate, slot);
}
/**
* @dev Releases a slot used by the collect channel game, only when the game is finished.
* This does three things:
* 1. Empty the slot
* 2. Pay the delegate
* 3. Pay the destinationAccount
* Also, if a token.transfer was requested, transfer the outstanding balance to the specified address.
* @param delegate id of the account requesting the release operation
* @param slot id of the slot requested for the duration of the challenge game
*/
function freeSlot(uint32 delegate, uint32 slot) public {
CollectSlot memory s = collects[delegate][slot];
// If this is slot is empty, nothing else to do here.
if (s.status == 0) return;
// Make sure this slot is ready to be freed.
// It should be in the waiting state(1) and with challenge time ran-out
require(s.status == 1, "slot not available");
require(block.number >= s.block, "slot not available");
// 1. Put the slot in the empty state
collects[delegate][slot].status = 0;
// 2. Pay the delegate
// This includes the stake as well as fees and other tokens reserved during collect()
// [delegateAmount + stake] => delegate
balanceAdd(delegate, SafeMath.add64(s.delegateAmount, params.collectStake));
// 3. Pay the destination account
// [amount - delegateAmount] => to
uint64 balance = SafeMath.sub64(s.amount, s.delegateAmount);
// was a transfer requested?
if (s.addr != address(0))
{
// empty the account balance
balance = SafeMath.add64(balance, accounts[s.to].balance);
accounts[s.to].balance = 0;
if (balance != 0)
require(token.transfer(s.addr, balance), "transfer failed");
} else
{
balanceAdd(s.to, balance);
}
}
}
/**
* @title BatchPayment processing
* @notice This contract allows to scale ERC-20 token transfer for fees or
* micropayments on the few-buyers / many-sellers setting.
*/
contract BatPay is Payments {
/**
* @dev Contract constructor, sets ERC20 token this contract will use for payments
* @param token_ ERC20 contract address
* @param maxBulk Maximum number of users to register in a single bulkRegister
* @param maxTransfer Maximum number of destinations on a single payment
* @param challengeBlocks number of blocks to wait for a challenge
* @param challengeStepBlocks number of blocks to wait for a single step on
* the challenge game
* @param collectStake stake in tokens for a collect operation
* @param challengeStake stake in tokens for the challenger of a collect operation
* @param unlockBlocks number of blocks to wait after registering payment
* for an unlock operation
* @param maxCollectAmount Maximum amount of tokens to be collected in a
* single transaction
*/
constructor(
IERC20 token_,
uint32 maxBulk,
uint32 maxTransfer,
uint32 challengeBlocks,
uint32 challengeStepBlocks,
uint64 collectStake,
uint64 challengeStake,
uint32 unlockBlocks,
uint64 maxCollectAmount
)
public
{
require(token_ != address(0), "Token address can't be zero");
require(maxBulk > 0, "Parameter maxBulk can't be zero");
require(maxTransfer > 0, "Parameter maxTransfer can't be zero");
require(challengeBlocks > 0, "Parameter challengeBlocks can't be zero");
require(challengeStepBlocks > 0, "Parameter challengeStepBlocks can't be zero");
require(collectStake > 0, "Parameter collectStake can't be zero");
require(challengeStake > 0, "Parameter challengeStake can't be zero");
require(unlockBlocks > 0, "Parameter unlockBlocks can't be zero");
require(maxCollectAmount > 0, "Parameter maxCollectAmount can't be zero");
owner = msg.sender;
token = IERC20(token_);
params.maxBulk = maxBulk;
params.maxTransfer = maxTransfer;
params.challengeBlocks = challengeBlocks;
params.challengeStepBlocks = challengeStepBlocks;
params.collectStake = collectStake;
params.challengeStake = challengeStake;
params.unlockBlocks = unlockBlocks;
params.maxCollectAmount = maxCollectAmount;
}
} | the challenge was completed successfully, or the delegate failed to respond on time. The challenger will collect the stake. collectSlot Collect slot config Various parameters accounts a reference to the main accounts array/ | function challenge_success(
Data.CollectSlot storage collectSlot,
Data.Config storage config,
Data.Account[] storage accounts
)
public
{
require((collectSlot.status == 2 || collectSlot.status == 4),
"Wrong Collect Slot status");
require(challengeHasExpired(collectSlot),
"Challenge not yet finished");
accounts[collectSlot.challenger].balance = SafeMath.add64(
accounts[collectSlot.challenger].balance,
SafeMath.add64(config.collectStake, config.challengeStake));
collectSlot.status = 0;
}
| 5,496,449 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;
import "./OwnableStorage.sol";
contract Ownable{
OwnableStorage _storage;
function initialize( address storage_ ) public {
_storage = OwnableStorage(storage_);
}
modifier OnlyAdmin(){
require( _storage.isAdmin(msg.sender) );
_;
}
modifier OnlyGovernance(){
require( _storage.isGovernance( msg.sender ) );
_;
}
modifier OnlyAdminOrGovernance(){
require( _storage.isAdmin(msg.sender) || _storage.isGovernance( msg.sender ) );
_;
}
function updateAdmin( address admin_ ) public OnlyAdmin {
_storage.setAdmin(admin_);
}
function updateGovenance( address gov_ ) public OnlyAdminOrGovernance {
_storage.setGovernance(gov_);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;
contract OwnableStorage {
address public _admin;
address public _governance;
constructor() payable {
_admin = msg.sender;
_governance = msg.sender;
}
function setAdmin( address account ) public {
require( isAdmin( msg.sender ));
_admin = account;
}
function setGovernance( address account ) public {
require( isAdmin( msg.sender ) || isGovernance( msg.sender ));
_admin = account;
}
function isAdmin( address account ) public view returns( bool ) {
return account == _admin;
}
function isGovernance( address account ) public view returns( bool ) {
return account == _admin;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./Ownable.sol";
// Hard Work Now! For Punkers by 0xViktor...
contract PunkRewardPool is Ownable, Initializable, ReentrancyGuard{
using SafeMath for uint;
using SafeERC20 for IERC20;
bool isStarting = false;
bool isInitialize = false;
uint constant MAX_WEIGHT = 500;
uint constant BLOCK_YEAR = 2102400;
IERC20 Punk;
uint startBlock;
address [] forges;
mapping ( address => uint ) totalSupplies;
mapping ( address => mapping( address=>uint ) ) balances;
mapping ( address => mapping( address=>uint ) ) checkPointBlocks;
mapping( address => uint ) weights;
uint weightSum;
mapping( address => uint ) distributed;
uint totalDistributed;
function initializePunkReward( address storage_, address punk_ ) public initializer {
// Hard Work Now! For Punkers by 0xViktor...
require(!isInitialize);
Ownable.initialize( storage_ );
Punk = IERC20( punk_ );
startBlock = 0;
weightSum = 0;
totalDistributed = 0;
isInitialize = true;
}
function start() public OnlyAdmin{
startBlock = block.number;
isStarting = true;
}
function addForge( address forge ) public OnlyAdminOrGovernance {
// Hard Work Now! For Punkers by 0xViktor...
require( !_checkForge( forge ), "PUNK_REWARD_POOL: Already Exist" );
forges.push( forge );
weights[ forge ] = 0;
}
function setForge( address forge, uint weight ) public OnlyAdminOrGovernance {
// Hard Work Now! For Punkers by 0xViktor...
require( _checkForge( forge ), "PUNK_REWARD_POOL: Not Exist Forge" );
( uint minWeight , uint maxWeight ) = getWeightRange( forge );
require( minWeight <= weight && weight <= maxWeight, "PUNK_REWARD_POOL: Invalid weight" );
weights[ forge ] = weight;
weightSum = 0;
for( uint i = 0 ; i < forges.length ; i++ ){
weightSum += weights[ forges[ i ] ];
}
}
function getWeightRange( address forge ) public view returns( uint, uint ){
// Hard Work Now! For Punkers by 0xViktor...
if( forges.length == 0 ) return ( 1, MAX_WEIGHT );
if( forges.length == 1 ) return ( weights[ forges[ 0 ] ], weights[ forges[ 0 ] ] );
if( weightSum == 0 ) return ( 0, MAX_WEIGHT );
uint highestWeight = 0;
uint excludeWeight = weightSum.sub( weights[ forge ] );
for( uint i = 0 ; i < forges.length ; i++ ){
if( forges[ i ] != forge && highestWeight < weights[ forges[ i ] ] ){
highestWeight = weights[ forges[ i ] ];
}
}
if( highestWeight > excludeWeight.sub( highestWeight ) ){
return ( highestWeight.sub( excludeWeight.sub( highestWeight ) ), MAX_WEIGHT < excludeWeight ? MAX_WEIGHT : excludeWeight );
}else{
return ( 0, MAX_WEIGHT < excludeWeight ? MAX_WEIGHT : excludeWeight );
}
}
function claimPunk( ) public {
// Hard Work Now! For Punkers by 0xViktor...
claimPunk( msg.sender );
}
function claimPunk( address to ) public {
// Hard Work Now! For Punkers by 0xViktor...
if( isStarting ){
for( uint i = 0 ; i < forges.length ; i++ ){
address forge = forges[i];
uint reward = getClaimPunk( forge, to );
checkPointBlocks[ forge ][ to ] = block.number;
if( reward > 0 ) Punk.safeTransfer( to, reward );
distributed[ forge ] = distributed[ forge ].add( reward );
totalDistributed = totalDistributed.add( reward );
}
}
}
function claimPunk( address forge, address to ) public nonReentrant {
// Hard Work Now! For Punkers by 0xViktor...
if( isStarting ){
uint reward = getClaimPunk( forge, to );
checkPointBlocks[ forge ][ to ] = block.number;
if( reward > 0 ) Punk.safeTransfer( to, reward );
distributed[ forge ] = distributed[ forge ].add( reward );
totalDistributed = totalDistributed.add( reward );
}
}
function staking( address forge, uint amount ) public {
// Hard Work Now! For Punkers by 0xViktor...
staking( forge, amount, msg.sender );
}
function unstaking( address forge, uint amount ) public {
// Hard Work Now! For Punkers by 0xViktor...
unstaking( forge, amount, msg.sender );
}
function staking( address forge, uint amount, address from ) public nonReentrant {
// Hard Work Now! For Punkers by 0xViktor...
require( msg.sender == from || _checkForge( msg.sender ), "REWARD POOL : NOT ALLOWD" );
claimPunk( from );
checkPointBlocks[ forge ][ from ] = block.number;
IERC20( forge ).safeTransferFrom( from, address( this ), amount );
balances[ forge ][ from ] = balances[ forge ][ from ].add( amount );
totalSupplies[ forge ] = totalSupplies[ forge ].add( amount );
}
function unstaking( address forge, uint amount, address from ) public nonReentrant {
// Hard Work Now! For Punkers by 0xViktor...
require( msg.sender == from || _checkForge( msg.sender ), "REWARD POOL : NOT ALLOWD" );
claimPunk( from );
checkPointBlocks[ forge ][ from ] = block.number;
balances[ forge ][ from ] = balances[ forge ][ from ].sub( amount );
IERC20( forge ).safeTransfer( from, amount );
totalSupplies[ forge ] = totalSupplies[ forge ].sub( amount );
}
function _checkForge( address forge ) internal view returns( bool ){
// Hard Work Now! For Punkers by 0xViktor...
bool check = false;
for( uint i = 0 ; i < forges.length ; i++ ){
if( forges[ i ] == forge ){
check = true;
break;
}
}
return check;
}
function _calcRewards( address forge, address user, uint fromBlock, uint currentBlock ) internal view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
uint balance = balances[ forge ][ user ];
if( balance == 0 ) return 0;
uint totalSupply = totalSupplies[ forge ];
uint weight = weights[ forge ];
uint startPeriod = _getPeriodFromBlock( fromBlock );
uint endPeriod = _getPeriodFromBlock( currentBlock );
if( startPeriod == endPeriod ){
uint during = currentBlock.sub( fromBlock ).mul( balance ).mul( weight ).mul( _perBlockRateFromPeriod( startPeriod ) );
return during.div( weightSum ).div( totalSupply );
}else{
uint denominator = weightSum.mul( totalSupply );
uint duringStartNumerator = _getBlockFromPeriod( startPeriod.add( 1 ) ).sub( fromBlock );
duringStartNumerator = duringStartNumerator.mul( weight ).mul( _perBlockRateFromPeriod( startPeriod ) ).mul( balance );
uint duringEndNumerator = currentBlock.sub( _getBlockFromPeriod( endPeriod ) );
duringEndNumerator = duringEndNumerator.mul( weight ).mul( _perBlockRateFromPeriod( endPeriod ) ).mul( balance );
uint duringMid = 0;
for( uint i = startPeriod.add( 1 ) ; i < endPeriod ; i++ ) {
uint numerator = BLOCK_YEAR.mul( 4 ).mul( balance ).mul( weight ).mul( _perBlockRateFromPeriod( i ) );
duringMid += numerator.div( denominator );
}
uint duringStartAmount = duringStartNumerator.div( denominator );
uint duringEndAmount = duringEndNumerator.div( denominator );
return duringStartAmount + duringMid + duringEndAmount;
}
}
function _getBlockFromPeriod( uint period ) internal view returns ( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return startBlock.add( period.sub( 1 ).mul( BLOCK_YEAR ).mul( 4 ) );
}
function _getPeriodFromBlock( uint blockNumber ) internal view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return blockNumber.sub( startBlock ).div( BLOCK_YEAR.mul( 4 ) ).add( 1 );
}
function _perBlockRateFromPeriod( uint period ) internal view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
uint totalDistribute = Punk.balanceOf( address( this ) ).add( totalDistributed ).div( period.mul( 2 ) );
uint perBlock = totalDistribute.div( BLOCK_YEAR.mul( 4 ) );
return perBlock;
}
function getClaimPunk( address to ) public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
uint reward = 0;
for( uint i = 0 ; i < forges.length ; i++ ){
reward += getClaimPunk( forges[ i ], to );
}
return reward;
}
function getClaimPunk( address forge, address to ) public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
uint checkPointBlock = checkPointBlocks[ forge ][ to ];
if( checkPointBlock <= getStartBlock() ){
checkPointBlock = getStartBlock();
}
return checkPointBlock > startBlock ? _calcRewards( forge, to, checkPointBlock, block.number ) : 0;
}
function getWeightSum() public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return weightSum;
}
function getWeight( address forge ) public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return weights[ forge ];
}
function getTotalDistributed( ) public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return totalDistributed;
}
function getDistributed( address forge ) public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return distributed[ forge ];
}
function getAllocation( ) public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return _perBlockRateFromPeriod( _getPeriodFromBlock( block.number ) );
}
function getAllocation( address forge ) public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return getAllocation( ).mul( weights[ forge ] ).div( weightSum );
}
function staked( address forge, address account ) public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return balances[ forge ][ account ];
}
function getTotalReward() public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return Punk.balanceOf( address( this ) ).add( totalDistributed );
}
function getStartBlock() public view returns( uint ){
// Hard Work Now! For Punkers by 0xViktor...
return startBlock;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
import "../../utils/Address.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_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'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
| Hard Work Now! For Punkers by 0xViktor... | function getAllocation( address forge ) public view returns( uint ){
return getAllocation( ).mul( weights[ forge ] ).div( weightSum );
}
| 1,144,748 |
./full_match/1/0x1e1FddCf2Df356F05E0fF1842e60f47F4B573659/sources/OxSniper.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("0xSniper", "0XS") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 7;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 15;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
uint256 totalSupply = 1_000_000_000 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 8,302,983 |
/**
*Submitted for verification at Etherscan.io on 2021-02-26
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.6;
pragma experimental ABIEncoderV2;
interface IPairXCore {
// 向池子中存入资产
function deposit( address token , address to , uint amount ) external ;
// 取回指定的Token资产及奖励
function claim( address token ) external returns (uint amount) ;
// 提取PairX的挖矿奖励,可以提取当前已解锁的份额
function redeem(address token ) external returns (uint amount ) ;
/**
* 结束流动性挖矿
*/
function finish() external ;
}
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
interface IStakingRewards {
// Views
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
function earned(address account) external view returns (uint256);
function getRewardForDuration() external view returns (uint256);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
// Mutative
function stake(uint256 amount) external;
function withdraw(uint256 amount) external;
function getReward() external;
function exit() external;
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed user, uint256 reward);
event RewardAdded(uint256 reward);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev 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);
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
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;
}
contract PairPairX is IPairXCore {
using SafeMath for uint256;
address public Owner;
uint8 public Fee = 10;
address public FeeTo;
uint256 private MinToken0Deposit;
uint256 private MinToken1Deposit;
// for pairx
address public RewardToken; // Reward Token
uint256 public RewardAmount;
uint8 public Status = 0; // 0 = not init , 1 = open , 2 = locked , 9 = finished
// uint public MaxLockDays = 365 ;
uint256 public RewardBeginTime = 0; // 开始PairX计算日期,在addLiquidityAndStake时设置
uint256 public DepositEndTime = 0; // 存入结束时间
uint256 public StakeEndTime = 0;
address public UniPairAddress; // 配对奖励Token address
address public MainToken; // stake and reward token
address public Token0; // Already sorted .
address public Token1;
TokenRecord Token0Record;
TokenRecord Token1Record;
address public StakeAddress; //
// uint StakeAmount ;
uint RewardGottedTotal ; //已提现总数
mapping(address => mapping(address => uint256)) UserBalance; // 用户充值余额 UserBalance[sender][token]
mapping(address => mapping(address => uint256)) RewardGotted; // RewardGotted[sender][token]
event Deposit(address from, address to, address token, uint256 amount);
event Claim(
address from,
address to,
address token,
uint256 principal,
uint256 interest,
uint256 reward
);
struct TokenRecord {
uint256 total; // 存入总代币计数
uint256 reward; // 分配的总奖励pairx,默认先分配40%,最后20%根据规则分配
uint256 compensation; // PairX补贴额度,默认为0
uint256 stake; // lon staking token
uint256 withdraw; // 可提现总量,可提现代币需要包含挖矿奖励部分
uint256 mint; // 挖矿奖励
}
modifier onlyOwner() {
require(msg.sender == Owner, "no role.");
_;
}
modifier isActive() {
require(block.timestamp < StakeEndTime, "Mining was expired.");
require(Status == 1, "Not open.");
_;
}
constructor(address owner) public {
Owner = owner;
}
function active(
address feeTo,
address pair,
address main,
address stake,
uint256 stakeEndTime
) external onlyOwner {
FeeTo = feeTo;
UniPairAddress = pair;
MainToken = main;
// 通过接口读取token0和token1的值
IUniswapV2Pair uni = IUniswapV2Pair(UniPairAddress);
Token0 = uni.token0();
Token1 = uni.token1();
StakeEndTime = stakeEndTime; //按秒计算,不再按天计算了
StakeAddress = stake;
}
/**
* deposit reward-tokens (PairX token).
*/
function setReward(
address reward,
uint256 amount,
uint256 token0min,
uint256 token1min,
uint256 depositEndTime
) external onlyOwner {
RewardToken = reward;
TransferHelper.safeTransferFrom(
reward,
msg.sender,
address(this),
amount
);
RewardAmount = RewardAmount.add(amount);
MinToken0Deposit = token0min;
MinToken1Deposit = token1min;
Status = 1;
//update TokenRecord
uint256 defaultReward = RewardAmount.mul(4).div(10);
Token0Record.reward = defaultReward;
Token1Record.reward = defaultReward;
DepositEndTime = depositEndTime;
}
function tokenRecordInfo(address token)
external
view
returns (
uint256 free,
uint256 total,
uint256 reward,
uint256 stake,
uint256 withdraw
)
{
if (token == Token0) {
// free = _tokenBalance(Token0);
free = Token0Record.withdraw ;
total = Token0Record.total;
reward = Token0Record.reward;
stake = Token0Record.stake;
withdraw = Token0Record.withdraw;
} else {
// free = _tokenBalance(Token1);
free = Token1Record.withdraw ;
total = Token1Record.total;
reward = Token1Record.reward;
stake = Token1Record.stake;
withdraw = Token1Record.withdraw;
}
}
function info() external view returns (
// address owner , uint8 fee , address feeTo ,
uint minToken0Deposit , uint minToken1Deposit ,
address rewardToken , uint rewardAmount ,
uint8 status , uint stakeEndTime ,
address token0 , address token1 , address pair ,
address mainToken , uint rewardBeginTime , uint depositEndTime
) {
minToken0Deposit = MinToken0Deposit ;
minToken1Deposit = MinToken1Deposit ;
rewardToken = RewardToken ;
rewardAmount = RewardAmount ;
status = Status ;
stakeEndTime = StakeEndTime ;
token0 = Token0 ;
token1 = Token1 ;
mainToken = MainToken ;
pair = UniPairAddress ;
rewardBeginTime = RewardBeginTime ;
depositEndTime = DepositEndTime ;
}
function depositInfo( address sender , address token ) external view returns
( uint depositBalance ,uint depositTotal , uint leftDays ,
uint lockedReward , uint freeReward , uint gottedReward ) {
depositBalance = UserBalance[sender][token] ;
if( token == Token0 ) {
depositTotal = Token0Record.total ;
} else {
depositTotal = Token1Record.total ;
}
// rewardTotal = RewardTotal[sender] ;
if( sender != address(0) ){
( leftDays , lockedReward , freeReward , gottedReward )
= getRewardRecord( token , sender ) ;
} else {
leftDays = 0 ;
lockedReward = 0 ;
freeReward = 0 ;
gottedReward = 0 ;
}
}
function getRewardRecord(address token , address sender ) public view returns
( uint leftDays , uint locked , uint free , uint gotted ) {
uint nowDate = getDateTime( block.timestamp ) ;
//计算一共可提取的奖励
uint depositAmount = UserBalance[sender][token] ;
TokenRecord memory record = token == Token0 ? Token0Record : Token1Record ;
leftDays = _leftDays( StakeEndTime , nowDate ) ;
locked = 0 ;
free = 0 ;
gotted = 0 ;
if( depositAmount == 0 ) {
return ( leftDays , 0 , 0 , 0 );
}
if( record.reward == 0 ) {
return ( leftDays , 0 , 0 , 0 );
}
gotted = RewardGotted[sender][token] ;
//换个计算方法,计算每秒可获得的收益
uint lockedTimes = _leftDays( StakeEndTime , RewardBeginTime ) ;
uint oneTimeReward = record.reward.div( lockedTimes ) ;
uint freeTime ;
if( nowDate > StakeEndTime ) {
leftDays = 0 ;
locked = 0 ;
freeTime = lockedTimes ;
} else {
leftDays = _leftDays( StakeEndTime , nowDate ) ;
freeTime = lockedTimes.sub( leftDays ) ;
}
// 防止溢出,保留3位精度
uint maxReward = depositAmount.mul( oneTimeReward ).div(1e15)
.mul( lockedTimes ).div( record.total.div(1e15) );
if( Status == 2 ) {
free = depositAmount.mul( oneTimeReward ).div(1e15)
.mul( freeTime ).div( record.total.div(1e15) );
if( free.add(gotted) > maxReward ){
locked = 0 ;
} else {
locked = maxReward.sub( free ).sub( gotted ) ;
}
} else if ( Status == 9 ) {
free = maxReward.sub( gotted ) ;
locked = 0 ;
} else if ( Status == 1 ) {
free = 0 ;
locked = maxReward ;
} else {
free = 0 ;
locked = 0 ;
}
}
function getDateTime( uint timestamp ) public pure returns ( uint ) {
// timeValue = timestamp ;
return timestamp ;
}
function _sendReward( address to , uint amount ) internal {
//Give reward tokens .
uint balance = RewardAmount.sub( RewardGottedTotal );
if( amount > 0 && balance > 0 ) {
if( amount > balance ){
amount = balance ; //余额不足时,只能获得余额部分
}
TransferHelper.safeTransfer( RewardToken , to , amount ) ;
// RewardAmount = RewardAmount.sub( amount ) ; 使用balanceOf 确定余额
}
}
function _deposit(address sender , address token , uint amount ) internal {
if( token == Token0 ) {
require( amount > MinToken0Deposit , "Deposit tokens is too less." ) ;
}
if( token == Token1 ) {
require( amount > MinToken1Deposit , "Deposit tokens is too less." ) ;
}
if( token == Token0 ) {
Token0Record.total = Token0Record.total.add( amount ) ;
Token0Record.withdraw = Token0Record.total ;
}
if( token == Token1 ) {
Token1Record.total = Token1Record.total.add( amount ) ;
Token1Record.withdraw = Token1Record.total ;
}
UserBalance[sender][token] = UserBalance[sender][token].add(amount );
}
function _fee( uint amount ) internal returns ( uint fee ) {
fee = amount.mul( Fee ).div( 100 ) ;
if( fee > 0 ) {
_safeTransfer( MainToken , FeeTo , fee ) ;
}
}
function _leftDays(uint afterDate , uint beforeDate ) internal pure returns( uint ) {
if( afterDate <= beforeDate ) {
return 0 ;
} else {
return afterDate.sub(beforeDate ) ;
// 将由天计算改为由秒计算
//return afterDate.sub(beforeDate).div( OneDay ) ;
}
}
/*
* 向池子中存入资产, 目前该接口只支持erc20代币.
* 如果需要使用eth,会在前置合约进行处理,将eth兑换成WETH
*/
function deposit( address token , address to , uint amount ) public override isActive {
require( Status == 1 , "Not allow deposit ." ) ;
require( (token == Token0) || ( token == Token1) , "Match token faild." ) ;
// More gas , But logic will more easy.
if( token == MainToken ){
TransferHelper.safeTransferFrom( token , msg.sender , address(this) , amount ) ;
} else {
// 兑换 weth
IWETH( token ).deposit{
value : amount
}() ;
}
_deposit( to , token , amount ) ;
emit Deposit( to, address(this) , token , amount ) ;
}
/**
* 提取可提现的奖励Token
*/
function redeem(address token ) public override returns ( uint amount ) {
require( Status == 2 || Status == 9 , "Not finished." ) ;
address sender = msg.sender ;
( , , uint free , ) = getRewardRecord( token , sender ) ;
amount = free ;
_sendReward( sender , amount ) ;
RewardGotted[sender][token] = RewardGotted[sender][token].add( amount ) ;
RewardGottedTotal = RewardGottedTotal.add( amount ) ;
}
// redeem all , claim from tokenlon , and removeLiquidity from uniswap
// 流程结束
function finish() external override onlyOwner {
// require(block.timestamp >= StakeEndTime , "It's not time for redemption." ) ;
// redeem liquidity from staking contracts
IStakingRewards staking = IStakingRewards(StakeAddress) ;
// uint stakeBalance = staking.balanceOf( address(this) ) ;
//计算MainToken余额变化,即挖矿Token的余额变化,获取收益
uint beforeExit = _tokenBalance( MainToken );
staking.exit() ;
uint afterExit = _tokenBalance( MainToken );
uint interest = afterExit.sub( beforeExit ) ;
// remove liquidity
IUniswapV2Pair pair = IUniswapV2Pair( UniPairAddress ) ;
uint liquidityBalance = pair.balanceOf( address(this) ) ;
TransferHelper.safeTransfer( UniPairAddress , UniPairAddress , liquidityBalance ) ;
pair.burn( address(this) ) ;
//计算剩余本金
uint mainTokenBalance = _tokenBalance( MainToken ) ;
uint principal = mainTokenBalance.sub( interest ).sub( RewardAmount ).add( RewardGottedTotal ) ;
// 收取 interest 的 10% 作为管理费
uint fee = _fee( interest ) ;
uint interestWithoutFee = interest - fee ;
//判断无偿损失
// 判断Token0是否受到了无偿损失影响
TokenRecord memory mainRecord = MainToken == Token0 ? Token0Record : Token1Record ;
uint mainTokenRate = 5 ;
uint pairTokenRate = 5 ; //各50%的收益,不需要补偿无偿损失的一方
if( mainRecord.total > principal ) {
// 有无偿损失
uint diff = mainRecord.total - principal ;
uint minDiff = mainRecord.total.div( 10 ) ; // 10%的损失
if( diff > minDiff ) {
//满足补贴条件
mainTokenRate = 6 ;
pairTokenRate = 4 ;
}
} else {
// 计算另一个token的是否满足补偿条件
TokenRecord memory pairRecord = MainToken == Token0 ? Token1Record : Token0Record ;
//获取配对Token的余额
address pairToken = Token0 == MainToken ? Token1 : Token0 ;
//TODO 二池因为奖励token和挖矿token属于同一token,所以这里通过余额计算会存在问题,需要调整
uint pairTokenBalance = _tokenBalance( pairToken ) ;
uint diff = pairRecord.total - pairTokenBalance ;
uint minDiff = pairRecord.total.div(10) ;
if( diff > minDiff ) {
pairTokenRate = 6 ;
mainTokenRate = 4 ;
}
}
( uint token0Rate , uint token1Rate ) = Token0 == MainToken ?
( mainTokenRate , pairTokenRate) : ( pairTokenRate , mainTokenRate ) ;
Token0Record.reward = RewardAmount.mul( token0Rate ).div( 10 ) ;
Token1Record.reward = RewardAmount.mul( token1Rate ).div( 10 ) ;
Token0Record.mint = interestWithoutFee.mul( token0Rate ).div( 10 ) ;
Token1Record.mint = interestWithoutFee.mul( token1Rate ).div( 10 ) ;
// 设置为挖矿结束
Status = 9 ;
}
/**
* 添加流动性并开始挖矿时
* 1、不接收继续存入资产。
* 2、开始计算PairX的挖矿奖励,并线性释放。
*/
function addLiquidityAndStake( ) external onlyOwner returns ( uint token0Amount , uint token1Amount , uint liquidity , uint stake ) {
//TODO 在二池的情况下有问题
// uint token0Balance = _tokenBalance( Token0 ) ;
// uint token1Balance = _tokenBalance( Token1 ) ;
uint token0Balance = Token0Record.total ;
uint token1Balance = Token1Record.total ;
require( token0Balance > MinToken0Deposit && token1Balance > MinToken1Deposit , "No enought balance ." ) ;
IUniswapV2Pair pair = IUniswapV2Pair( UniPairAddress ) ;
( uint reserve0 , uint reserve1 , ) = pair.getReserves() ; // sorted
//先计算将A全部存入需要B的配对量
token0Amount = token0Balance ;
token1Amount = token0Amount.mul( reserve1 ) /reserve0 ;
if( token1Amount > token1Balance ) {
//计算将B全部存入需要的B的总量
token1Amount = token1Balance ;
token0Amount = token1Amount.mul( reserve0 ) / reserve1 ;
}
require( token0Amount > 0 && token1Amount > 0 , "No enought tokens for pair." ) ;
TransferHelper.safeTransfer( Token0 , UniPairAddress , token0Amount ) ;
TransferHelper.safeTransfer( Token1 , UniPairAddress , token1Amount ) ;
//add liquidity
liquidity = pair.mint( address(this) ) ;
require( liquidity > 0 , "Stake faild. No liquidity." ) ;
//stake
stake = _stake( ) ;
// 开始计算PairX挖矿
RewardBeginTime = getDateTime( block.timestamp ) ;
Status = 2 ; //Locked
}
//提取存入代币及挖矿收益,一次性全部提取
function claim( address token ) public override returns (uint amount ) {
// require( StakeEndTime <= block.timestamp , "Unexpired for locked.") ;
// 余额做了处理,不用担心重入
amount = UserBalance[msg.sender][token] ;
require( amount > 0 , "Invaild request, balance is not enough." ) ;
require( Status != 2 , "Not finish. " ) ; //locked
require( token == Token0 || token == Token1 , "No matched token.") ;
uint reward = 0 ;
uint principal = amount ;
uint interest = 0 ;
if( Status == 1 ) {
// 直接提取本金,但没有任何收益
_safeTransfer( token , msg.sender , amount ) ;
if( token == Token0 ) {
Token0Record.total = Token0Record.total.sub( amount ) ;
Token0Record.withdraw = Token0Record.total ;
}
if( token == Token1 ) {
Token1Record.total = Token1Record.total.sub( amount ) ;
Token1Record.withdraw = Token1Record.total ;
}
// UserBalance[msg.sender][token] = UserBalance[msg.sender][token].sub( amount ) ;
}
if( Status == 9 ) {
TokenRecord storage tokenRecord = token == Token0 ? Token0Record : Token1Record ;
// 计算可提取的本金 amount / total * withdraw
principal = amount.div(1e15).mul( tokenRecord.withdraw ).div( tokenRecord.total.div(1e15) );
if( tokenRecord.mint > 0 ) {
interest = amount.div(1e15).mul( tokenRecord.mint ).div( tokenRecord.total.div(1e15) ) ;
}
// if( token == Token0 ) {
// tokenBalance = Token0Record.total ;
// }
if( token == MainToken ) {
// 一次性转入
uint tranAmount = principal + interest ;
_safeTransfer( token , msg.sender , tranAmount ) ;
} else {
_safeTransfer( token , msg.sender , principal ) ;
if( interest > 0 ) {
// 分别转出
_safeTransfer( MainToken , msg.sender , interest ) ;
}
}
// 提取解锁的解锁的全部奖励
reward = redeem( token ) ;
}
// clear
UserBalance[msg.sender][token] = uint(0);
emit Claim( address(this) , msg.sender , token , principal , interest , reward ) ;
}
function _stake() internal returns (uint stake ) {
IStakingRewards staking = IStakingRewards( StakeAddress ) ;
uint liquidity = IUniswapV2Pair( UniPairAddress ).balanceOf( address(this) ) ;
stake = liquidity ;
TransferHelper.safeApprove( UniPairAddress , StakeAddress , liquidity) ;
staking.stake( liquidity ) ;
// emit Staking( address(this) , StakeAddress , liquidity , stake ) ;
}
function depositETH() external payable {
uint ethValue = msg.value ;
require( ethValue > 0 , "Payment is zero." ) ;
address weth = Token0 == MainToken ? Token1 : Token0 ;
deposit( weth , msg.sender , ethValue ) ;
}
function _safeTransfer( address token , address to , uint amount ) internal {
uint balance = _tokenBalance( token ) ;
if( amount > balance ){
amount = balance ;
}
if( token == MainToken ) {
TransferHelper.safeTransfer( token , to , amount ) ;
} else {
// weth
IWETH( token ).withdraw( amount ) ;
TransferHelper.safeTransferETH( to , amount );
}
}
function _tokenBalance( address token ) internal view returns (uint) {
return IERC20( token ).balanceOf( address(this) ) ;
}
receive() external payable {
assert(msg.sender == Token0 || msg.sender == Token1 ); // only accept ETH via fallback from the WETH contract
}
} | rewardTotal = RewardTotal[sender] ; | function depositInfo( address sender , address token ) external view returns
( uint depositBalance ,uint depositTotal , uint leftDays ,
uint lockedReward , uint freeReward , uint gottedReward ) {
depositBalance = UserBalance[sender][token] ;
if( token == Token0 ) {
depositTotal = Token0Record.total ;
depositTotal = Token1Record.total ;
}
if( sender != address(0) ){
( leftDays , lockedReward , freeReward , gottedReward )
= getRewardRecord( token , sender ) ;
leftDays = 0 ;
lockedReward = 0 ;
freeReward = 0 ;
gottedReward = 0 ;
}
}
| 6,834,310 |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.6.6;
import '@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
// import 'hardhat/console.sol';
contract AutoBuy {
using SafeMath for uint256;
address haremToken;
IUniswapV2Router02 uniswapRouterV2;
IERC20 haremLPToken;
constructor(address _haremToken, address _uniswapRouterV2, address _haremLPToken) public{
haremToken = _haremToken;
uniswapRouterV2 = IUniswapV2Router02(_uniswapRouterV2);
haremLPToken = IERC20(_haremLPToken);
}
function swapAndAddLiquidity(uint256 amount) public payable{
require(msg.value == amount.mul(2), 'Message value incorrect.');
// console.log(haremLPToken.balanceOf(address(this)));
address[] memory path = new address[](2);
path[0] = uniswapRouterV2.WETH();
path[1] = haremToken;
uniswapRouterV2.swapExactETHForTokens.value(amount)(0, path, address(this), block.timestamp);
// console.log(IERC20(haremToken).balanceOf(address(this)));
IERC20(haremToken).approve(address(uniswapRouterV2), IERC20(haremToken).balanceOf(address(this)));
uniswapRouterV2.addLiquidityETH.value(amount)(haremToken, IERC20(haremToken).balanceOf(address(this)), 0, 0, address(this), block.timestamp);
// console.log(haremLPToken.balanceOf(address(this)));
haremLPToken.transfer(msg.sender, IERC20(haremLPToken).balanceOf(address(this)));
// console.log(haremLPToken.balanceOf(address(this)));
// console.log(haremLPToken.balanceOf(msg.sender));
}
function swap() public payable {
address[] memory path = new address[](2);
path[0] = uniswapRouterV2.WETH();
path[1] = haremToken;
uniswapRouterV2.swapExactETHForTokens.value(msg.value)(0, path, address(this), block.timestamp);
IERC20(haremToken).transfer(msg.sender, IERC20(haremToken).balanceOf(address(this)));
}
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// 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;
/**
* @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.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);
}
| console.log(haremLPToken.balanceOf(address(this))); console.log(IERC20(haremToken).balanceOf(address(this))); console.log(haremLPToken.balanceOf(address(this))); console.log(haremLPToken.balanceOf(address(this))); console.log(haremLPToken.balanceOf(msg.sender)); | function swapAndAddLiquidity(uint256 amount) public payable{
require(msg.value == amount.mul(2), 'Message value incorrect.');
address[] memory path = new address[](2);
path[0] = uniswapRouterV2.WETH();
path[1] = haremToken;
uniswapRouterV2.swapExactETHForTokens.value(amount)(0, path, address(this), block.timestamp);
IERC20(haremToken).approve(address(uniswapRouterV2), IERC20(haremToken).balanceOf(address(this)));
uniswapRouterV2.addLiquidityETH.value(amount)(haremToken, IERC20(haremToken).balanceOf(address(this)), 0, 0, address(this), block.timestamp);
haremLPToken.transfer(msg.sender, IERC20(haremLPToken).balanceOf(address(this)));
}
| 12,086,327 |
./full_match/1/0x70832E3e9a3268Fe9A5a47803e945fC34280B976/sources/src/Registry.sol | Helper function to unpause some target./ | function _unpauseTarget(address target) internal {
if (!isCallerPaused[target]) revert Registry__TargetNotPaused(target);
isCallerPaused[target] = false;
emit TargetUnpaused(target);
}
| 3,224,015 |
./full_match/314/0x7b7f1f85F599b63432F5D782041c25Dad354f999/sources/node_modules/@openzeppelin/contracts/utils/ReentrancyGuard.sol | By storing the original value once again, a refund is triggered (see https:eips.ethereum.org/EIPS/eip-2200) | function _nonReentrantAfter() private {
_status = NOT_ENTERED;
}
| 8,082,965 |
./full_match/5/0xBB4a18773C5F036Ad821059dd3574320934b567F/sources/contracts/MonoLiquidity.sol | 0x swap this function is used to execute a swap on 0x it takes the parameters from the API response and executes the swap it also gives an infinite allowance to the 0x contract to spend the `sellToken` the amount to swap is determined in `sellAmount` field when fetching the quote from the API, it's encoded in the `data` field and passed to this function as `swapCallData`/ The `sellTokenAddress` field from the API response. The `buyTokenAddress` field from the API response. The `allowanceTarget` field from the API response. The `to` field from the API response. The `data` field from the API response. It's the encoded data payload that needs to be sent to the 0x Exchange Proxy contract to execute the swap Checks that the swapTarget is actually the address of 0x ExchangeProxy Give `spender` (0x contract) an infinite allowance to spend the `sellToken` Note that for some tokens (e.g., USDT, KNC), you must first reset any existing allowance to 0 Track the initial user balance of the buyToken, so we can calculate how much was bought at the end the calculation will be made by subtracting the initial balance from the final balance of the buyToken : this assumes that the msg.sender is the holder of the buyToken, if not, this needs to be changed Execute the swap by calling the 0x ExchangeProxy contract Note that the swapCallData is the encoded data payload that needs to be sent to the 0x Exchange Proxy contract to execute the swap The swapCallData is generated by the 0x API and passed to this function as a parameter The swapCallData is generated by the 0x API based on the parameters passed to the API IERC20(sellToken).approve(ROUTER, amountIn); IERC20(buyToken).approve(ROUTER, amountOut); address[] memory path = new address[](2); path[0] = sellToken; path[1] = buyToken; IUniswapV2Router02(ROUTER).swapExactTokensForTokens( amountIn, amountOut, path, msg.sender, block.timestamp ); it checks if there is any unspent protocol fees left in the contract balance resulted of any unspent protocol fees, and if so, it refunds the sender dev: double check if it's necessary, not sure if any unspent fees will be sent to this contract | function zeroxSwap(
address sellToken,
address buyToken,
address spender,
address payable swapTarget,
bytes calldata swapCallData,
uint amountIn,
uint amountOut
) external payable {
require(swapTarget == exchangeProxy, "Target not ExchangeProxy");
require(
IERC20(sellToken).approve(spender, type(uint256).max),
"allowance error"
);
uint256 boughtAmount = IERC20(buyToken).balanceOf(msg.sender);
require(success, "SWAP_CALL_FAILED");
if (address(this).balance > 0) {
require(success2, "Refund failed");
}
boughtAmount = IERC20(buyToken).balanceOf(address(this));
IERC20(buyToken).transfer(msg.sender, boughtAmount),
"Transfer failed"
);
}
| 7,061,691 |
./full_match/5/0x443B523d2994762FDC76043EDD194314f60641cC/sources/contracts/RedistributionChef.sol | Rescue ETH force-sent to contract | function rescueETH() external onlyOwner {
require(sent);
}
| 7,063,460 |
./full_match/1/0x5537f945D8c3FCFDc1b8DECEEBD220FAD26aFdA8/sources/contracts/ComposableStablePool.sol | Translate parameters to avoid stack-too-deep issues in the constructor | function _extractStorageParams(NewPoolParams memory params)
private
view
returns (ComposableStablePoolStorage.StorageParams memory)
{
return
ComposableStablePoolStorage.StorageParams({
registeredTokens: _insertSorted(params.tokens, IERC20(this)),
tokenRateProviders: params.rateProviders,
exemptFromYieldProtocolFeeFlags: params.exemptFromYieldProtocolFeeFlags
});
}
| 4,901,416 |
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// SPDX-License-Identifier: MIT
import "@openzeppelin-3.4.0/token/ERC20/IERC20.sol";
import "@openzeppelin-3.4.0/token/ERC20/SafeERC20.sol";
import "./interfaces/Upgradeable.sol";
import "./GovToken.sol";
import "./MintCoordinator_Polygon.sol";
import "./interfaces/IMasterChef.sol";
contract MasterChef_Polygon is Upgradeable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The GOV TOKEN!
GovToken public GOV;
// Dev address.
address public devaddr;
// Block number when bonus GOV period ends.
uint256 public bonusEndBlock;
// GOV tokens created per block.
uint256 public GOVPerBlock;
// Bonus muliplier for early GOV makers.
uint256 public constant BONUS_MULTIPLIER = 0;
// unused
address public migrator;
// Info of each pool.
IMasterChef.PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => IMasterChef.UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when GOV mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
// add the GOV pool first to have ID 0
uint256 internal constant GOV_POOL_ID = 0;
event AddExternalReward(
address indexed sender,
uint256 indexed pid,
uint256 amount
);
MintCoordinator_Polygon public constant coordinator = MintCoordinator_Polygon(0x52fb1688B829BDb2BF70058f0BBfFD38af26cc2b);
mapping(IERC20 => bool) public poolExists;
modifier nonDuplicated(IERC20 _lpToken) {
require(!poolExists[_lpToken], "pool exists");
_;
}
// total deposits in a pool
mapping(uint256 => uint256) public balanceOf;
// pool rewards locked for future claim
mapping(uint256 => bool) public isLocked;
// total locked rewards for a user
mapping(address => uint256) internal _lockedRewards;
bool public notPaused;
modifier checkNoPause() {
require(notPaused || msg.sender == owner(), "paused");
_;
}
// vestingStamp for a user
mapping(address => uint256) public userStartVestingStamp;
//default value if userStartVestingStamp[user] == 0
uint256 public startVestingStamp;
uint256 public vestingDuration; // 15768000 6 months (6 * 365 * 24 * 60 * 60)
event AddAltReward(
address indexed sender,
uint256 indexed pid,
uint256 amount
);
event ClaimAltRewards(
address indexed user,
uint256 amount
);
//Mapping pid -- accumulated bnbPerGov
mapping(uint256 => uint256[]) public altRewardsRounds; // Old
//user => lastClaimedRound
mapping(address => uint256) public userAltRewardsRounds; // Old
//pid -- altRewardsPerShare
mapping(uint256 => uint256) public altRewardsPerShare;
//pid -- (user -- altRewardsPerShare)
mapping(uint256 => mapping(address => uint256)) public userAltRewardsPerShare;
bool public vestingDisabled;
uint256 internal constant IBZRX_POOL_ID = 2;
function initialize(
GovToken _GOV,
address _devaddr,
uint256 _GOVPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public onlyOwner {
require(address(GOV) == address(0), "unauthorized");
GOV = _GOV;
devaddr = _devaddr;
GOVPerBlock = _GOVPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function setVestingDuration(uint256 _vestingDuration)
external
onlyOwner
{
vestingDuration = _vestingDuration;
}
function setStartVestingStamp(uint256 _startVestingStamp)
external
onlyOwner
{
startVestingStamp = _startVestingStamp;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate)
public
onlyOwner
nonDuplicated(_lpToken)
{
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock =
block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolExists[_lpToken] = true;
poolInfo.push(
IMasterChef.PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accGOVPerShare: 0
})
);
}
// Update the given pool's GOV allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate)
public
onlyOwner
{
if (_withUpdate) {
massUpdatePools();
}
IMasterChef.PoolInfo storage pool = poolInfo[_pid];
require(address(pool.lpToken) != address(0) && poolExists[pool.lpToken], "pool not exists");
totalAllocPoint = totalAllocPoint.sub(pool.allocPoint).add(
_allocPoint
);
pool.allocPoint = _allocPoint;
if (block.number < pool.lastRewardBlock) {
pool.lastRewardBlock = startBlock;
}
}
function transferTokenOwnership(address newOwner)
public
onlyOwner
{
GOV.transferOwnership(newOwner);
}
function setStartBlock(uint256 _startBlock)
public
onlyOwner
{
startBlock = _startBlock;
}
function setLocked(uint256 _pid, bool _toggle)
public
onlyOwner
{
isLocked[_pid] = _toggle;
}
function setGOVPerBlock(uint256 _GOVPerBlock)
public
onlyOwner
{
massUpdatePools();
GOVPerBlock = _GOVPerBlock;
}
function getMultiplier(uint256 _from, uint256 _to)
public
view
returns (uint256)
{
return getMultiplierPrecise(_from, _to).div(1e18);
}
function getMultiplierNow()
public
view
returns (uint256)
{
return getMultiplierPrecise(block.number - 1, block.number);
}
function getMultiplierPrecise(uint256 _from, uint256 _to)
public
view
returns (uint256)
{
return _getDecliningMultipler(_from, _to, startBlock);
}
function _getDecliningMultipler(uint256 _from, uint256 _to, uint256 _bonusStartBlock)
internal
view
returns (uint256)
{
return _to.sub(_from).mul(1e18);
/*
// _periodBlocks = 1296000 = 60 * 60 * 24 * 30 / 2 = blocks_in_30_days (assume 2 second blocks)
uint256 _bonusEndBlock = _bonusStartBlock + 1296000;
// multiplier = 10e18
// declinePerBlock = 6944444444444 = (10e18 - 1e18) / _periodBlocks
uint256 _startMultipler;
uint256 _endMultipler;
uint256 _avgMultiplier;
if (_to <= _bonusEndBlock) {
_startMultipler = SafeMath.sub(10e18,
_from.sub(_bonusStartBlock)
.mul(6944444444444)
);
_endMultipler = SafeMath.sub(10e18,
_to.sub(_bonusStartBlock)
.mul(6944444444444)
);
_avgMultiplier = (_startMultipler + _endMultipler) / 2;
return _to.sub(_from).mul(_avgMultiplier);
} else if (_from >= _bonusEndBlock) {
return _to.sub(_from).mul(1e18);
} else {
_startMultipler = SafeMath.sub(10e18,
_from.sub(_bonusStartBlock)
.mul(6944444444444)
);
_endMultipler = 1e18;
_avgMultiplier = (_startMultipler + _endMultipler) / 2;
return _bonusEndBlock.sub(_from).mul(_avgMultiplier).add(
_to.sub(_bonusEndBlock).mul(1e18)
);
}*/
}
function _pendingGOV(uint256 _pid, address _user)
internal
view
returns (uint256)
{
IMasterChef.PoolInfo storage pool = poolInfo[_pid];
IMasterChef.UserInfo storage user = userInfo[_pid][_user];
uint256 accGOVPerShare = pool.accGOVPerShare.mul(1e18);
uint256 lpSupply = balanceOf[_pid];
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier =
getMultiplierPrecise(pool.lastRewardBlock, block.number);
uint256 GOVReward =
multiplier.mul(GOVPerBlock).mul(pool.allocPoint).div(
totalAllocPoint
);
accGOVPerShare = accGOVPerShare.add(
GOVReward.mul(1e12).div(lpSupply)
);
}
return user.amount.mul(accGOVPerShare).div(1e30).sub(user.rewardDebt);
}
function pendingAltRewards(uint256 pid, address _user)
external
view
returns (uint256)
{
return _pendingAltRewards(pid, _user);
}
//Splitted by pid in case if we want to distribute altRewards to other pids like bzrx
function _pendingAltRewards(uint256 pid, address _user)
internal
view
returns (uint256)
{
uint256 userSupply = userInfo[pid][_user].amount;
uint256 _altRewardsPerShare = altRewardsPerShare[pid];
if (_altRewardsPerShare == 0)
return 0;
if (userSupply == 0)
return 0;
uint256 _userAltRewardsPerShare = userAltRewardsPerShare[pid][_user];
//Handle the backcapability,
//when all user claim altrewards at least once we can remove this check
if(_userAltRewardsPerShare == 0 && pid == GOV_POOL_ID){
//Or didnt claim or didnt migrate
//check if migrate
uint256 _lastClaimedRound = userAltRewardsRounds[_user];
//Never claimed yet
if (_lastClaimedRound != 0) {
_lastClaimedRound -= 1; //correct index to start from 0
_userAltRewardsPerShare = altRewardsRounds[pid][_lastClaimedRound];
}
}
return (_altRewardsPerShare.sub(_userAltRewardsPerShare)).mul(userSupply).div(1e12);
}
// View function to see pending GOVs on frontend.
function pendingGOV(uint256 _pid, address _user)
external
view
returns (uint256)
{
return _pendingGOV(_pid, _user);
}
function unlockedRewards(address _user)
public
view
returns (uint256)
{
uint256 _locked = _lockedRewards[_user];
if(_locked == 0) {
return 0;
}
return calculateUnlockedRewards(_locked, now, userStartVestingStamp[_user]);
}
function calculateUnlockedRewards(uint256 _locked, uint256 currentStamp, uint256 _userStartVestingStamp)
public
view
returns (uint256)
{
//Unlock everything
if(vestingDisabled){
return _locked;
}
//Vesting is not started
if(startVestingStamp == 0 || vestingDuration == 0){
return 0;
}
if(_userStartVestingStamp == 0) {
_userStartVestingStamp = startVestingStamp;
}
uint256 _cliffDuration = currentStamp.sub(_userStartVestingStamp);
if(_cliffDuration >= vestingDuration)
return _locked;
return _cliffDuration.mul(_locked.div(vestingDuration)); // _locked.div(vestingDuration) is unlockedPerSecond
}
function lockedRewards(address _user)
public
view
returns (uint256)
{
return _lockedRewards[_user].sub(unlockedRewards(_user));
}
function toggleVesting(bool _isEnabled) external onlyOwner {
vestingDisabled = !_isEnabled;
}
function togglePause(bool _isPaused) external onlyOwner {
notPaused = !_isPaused;
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public checkNoPause {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function massMigrateToBalanceOf() public onlyOwner {
require(!notPaused, "!paused");
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
balanceOf[pid] = poolInfo[pid].lpToken.balanceOf(address(this));
}
massUpdatePools();
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public checkNoPause {
IMasterChef.PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = balanceOf[_pid];
uint256 _GOVPerBlock = GOVPerBlock;
uint256 _allocPoint = pool.allocPoint;
if (lpSupply == 0 || _GOVPerBlock == 0 || _allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplierPrecise(pool.lastRewardBlock, block.number);
uint256 GOVReward =
multiplier.mul(_GOVPerBlock).mul(_allocPoint).div(
totalAllocPoint
);
// 250m = 250 * 1e6
if (coordinator.totalMinted() >= 250*1e6*1e18) {
pool.allocPoint = 0;
return;
}
coordinator.mint(devaddr, GOVReward.div(1e19));
coordinator.mint(address(this), GOVReward.div(1e18));
pool.accGOVPerShare = pool.accGOVPerShare.add(
GOVReward.div(1e6).div(lpSupply)
);
pool.lastRewardBlock = block.number;
}
// Anyone can contribute GOV to a given pool
function addExternalReward(uint256 _amount) public checkNoPause {
IMasterChef.PoolInfo storage pool = poolInfo[GOV_POOL_ID];
require(block.number > pool.lastRewardBlock, "rewards not started");
uint256 lpSupply = balanceOf[GOV_POOL_ID];
require(lpSupply != 0, "no deposits");
updatePool(GOV_POOL_ID);
GOV.transferFrom(
address(msg.sender),
address(this),
_amount
);
pool.accGOVPerShare = pool.accGOVPerShare.add(
_amount.mul(1e12).div(lpSupply)
);
emit AddExternalReward(msg.sender, GOV_POOL_ID, _amount);
}
// Anyone can contribute native token rewards to GOV pool stakers
function addAltReward() public payable checkNoPause {
IMasterChef.PoolInfo storage pool = poolInfo[IBZRX_POOL_ID];
require(block.number > pool.lastRewardBlock, "rewards not started");
uint256 lpSupply = balanceOf[IBZRX_POOL_ID];
require(lpSupply != 0, "no deposits");
updatePool(IBZRX_POOL_ID);
altRewardsPerShare[IBZRX_POOL_ID] = altRewardsPerShare[IBZRX_POOL_ID]
.add(msg.value.mul(1e12).div(lpSupply));
emit AddAltReward(msg.sender, IBZRX_POOL_ID, msg.value);
}
// Deposit LP tokens to MasterChef for GOV allocation.
function deposit(uint256 _pid, uint256 _amount) public checkNoPause {
poolInfo[_pid].lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
_deposit(_pid, _amount);
}
function _deposit(uint256 _pid, uint256 _amount) internal {
IMasterChef.PoolInfo storage pool = poolInfo[_pid];
IMasterChef.UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 userAmount = user.amount;
uint256 pending;
uint256 pendingAlt;
if (userAmount != 0) {
pending = userAmount
.mul(pool.accGOVPerShare)
.div(1e12)
.sub(user.rewardDebt);
}
if (_pid == GOV_POOL_ID || _pid == IBZRX_POOL_ID) {
pendingAlt = _pendingAltRewards(_pid, msg.sender);
//Update userAltRewardsPerShare even if user got nothing in the current round
userAltRewardsPerShare[_pid][msg.sender] = altRewardsPerShare[_pid];
}
if (_amount != 0) {
balanceOf[_pid] = balanceOf[_pid].add(_amount);
userAmount = userAmount.add(_amount);
emit Deposit(msg.sender, _pid, _amount);
}
user.rewardDebt = userAmount.mul(pool.accGOVPerShare).div(1e12);
user.amount = userAmount;
//user vestingStartStamp recalculation is done in safeGOVTransfer
safeGOVTransfer(_pid, pending);
if (pendingAlt != 0) {
sendValueIfPossible(msg.sender, pendingAlt);
}
}
function claimReward(uint256 _pid) public checkNoPause {
_deposit(_pid, 0);
}
function compoundReward(uint256 _pid) public checkNoPause {
uint256 balance = GOV.balanceOf(msg.sender);
_deposit(_pid, 0);
// locked pools are ignored since they auto-compound
if (!isLocked[_pid]) {
balance = GOV.balanceOf(msg.sender).sub(balance);
if (balance != 0)
deposit(GOV_POOL_ID, balance);
}
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public checkNoPause {
IMasterChef.PoolInfo storage pool = poolInfo[_pid];
IMasterChef.UserInfo storage user = userInfo[_pid][msg.sender];
uint256 userAmount = user.amount;
require(_amount != 0 && userAmount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = userAmount
.mul(pool.accGOVPerShare)
.div(1e12)
.sub(user.rewardDebt);
uint256 pendingAlt;
IERC20 lpToken = pool.lpToken;
if (_pid == GOV_POOL_ID || _pid == IBZRX_POOL_ID) {
uint256 availableAmount = userAmount.sub(lockedRewards(msg.sender));
if (_amount > availableAmount) {
_amount = availableAmount;
}
pendingAlt = _pendingAltRewards(_pid, msg.sender);
//Update userAltRewardsPerShare even if user got nothing in the current round
userAltRewardsPerShare[_pid][msg.sender] = altRewardsPerShare[_pid];
}
balanceOf[_pid] = balanceOf[_pid].sub(_amount);
userAmount = userAmount.sub(_amount);
user.rewardDebt = userAmount.mul(pool.accGOVPerShare).div(1e12);
user.amount = userAmount;
lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
//user vestingStartStamp recalculation is done in safeGOVTransfer
safeGOVTransfer(_pid, pending);
if (pendingAlt != 0) {
sendValueIfPossible(msg.sender, pendingAlt);
}
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public checkNoPause {
IMasterChef.PoolInfo storage pool = poolInfo[_pid];
IMasterChef.UserInfo storage user = userInfo[_pid][msg.sender];
uint256 _amount = user.amount;
uint256 pendingAlt;
IERC20 lpToken = pool.lpToken;
if (_pid == GOV_POOL_ID || _pid == IBZRX_POOL_ID) {
uint256 availableAmount = _amount.sub(lockedRewards(msg.sender));
if (_amount > availableAmount) {
_amount = availableAmount;
}
pendingAlt = _pendingAltRewards(_pid, msg.sender);
//Update userAltRewardsPerShare even if user got nothing in the current round
userAltRewardsPerShare[_pid][msg.sender] = altRewardsPerShare[_pid];
}
lpToken.safeTransfer(address(msg.sender), _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
balanceOf[_pid] = balanceOf[_pid].sub(_amount);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accGOVPerShare).div(1e12);
if (pendingAlt != 0) {
sendValueIfPossible(msg.sender, pendingAlt);
}
}
function safeGOVTransfer(uint256 _pid, uint256 _amount) internal {
if (_amount == 0) {
return;
}
uint256 GOVBal = GOV.balanceOf(address(this));
if (_amount > GOVBal) {
_amount = GOVBal;
}
if (isLocked[_pid]) {
uint256 _locked = _lockedRewards[msg.sender];
_lockedRewards[msg.sender] = _locked.add(_amount);
userStartVestingStamp[msg.sender] = calculateVestingStartStamp(now, userStartVestingStamp[msg.sender], _locked, _amount);
_deposit(GOV_POOL_ID, _amount);
} else {
GOV.transfer(msg.sender, _amount);
}
}
//This function will be internal after testing,
function calculateVestingStartStamp(uint256 currentStamp, uint256 _userStartVestingStamp, uint256 _lockedAmount, uint256 _depositAmount)
public
view
returns(uint256)
{
//VestingStartStamp will be distributed between
//_userStartVestingStamp (min) and currentStamp (max) depends on _lockedAmount and _depositAmount
//To avoid calculation on limit values
if(_lockedAmount == 0) return startVestingStamp;
if(_depositAmount >= _lockedAmount) return currentStamp;
if(_depositAmount == 0) return _userStartVestingStamp;
//Vesting is not started, set 0 as default value
if(startVestingStamp == 0 || vestingDuration == 0){
return 0;
}
if(_userStartVestingStamp == 0) {
_userStartVestingStamp = startVestingStamp;
}
uint256 cliffDuration = currentStamp.sub(_userStartVestingStamp);
uint256 depositShare = _depositAmount.mul(1e12).div(_lockedAmount);
return _userStartVestingStamp.add(cliffDuration.mul(depositShare).div(1e12));
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
// Custom logic - helpers
function getPoolInfos() external view returns(IMasterChef.PoolInfo[] memory poolInfos) {
uint256 length = poolInfo.length;
poolInfos = new IMasterChef.PoolInfo[](length);
for (uint256 pid = 0; pid < length; ++pid) {
poolInfos[pid] = poolInfo[pid];
}
}
function getOptimisedUserInfos(address _user) external view returns(uint256[4][] memory userInfos) {
uint256 length = poolInfo.length;
userInfos = new uint256[4][](length);
for (uint256 pid = 0; pid < length; ++pid) {
userInfos[pid][0] = userInfo[pid][_user].amount;
userInfos[pid][1] = _pendingGOV(pid, _user);
userInfos[pid][2] = isLocked[pid] ? 1 : 0;
userInfos[pid][3] = (pid == GOV_POOL_ID || pid == IBZRX_POOL_ID) ? _pendingAltRewards(pid, _user) : 0;
}
}
function getUserInfos(address _wallet) external view returns(IMasterChef.UserInfo[] memory userInfos) {
uint256 length = poolInfo.length;
userInfos = new IMasterChef.UserInfo[](length);
for (uint256 pid = 0; pid < length; ++pid) {
userInfos[pid] = userInfo[pid][_wallet];
}
}
function getPendingGOV(address _user) external view returns(uint256[] memory pending) {
uint256 length = poolInfo.length;
pending = new uint256[](length);
for (uint256 pid = 0; pid < length; ++pid) {
pending[pid] = _pendingGOV(pid, _user);
}
}
function sendValueIfPossible(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{ value: amount }("");
if (!success) {
(success, ) = devaddr.call{ value: amount }("");
if (success)
emit ClaimAltRewards(devaddr, amount);
} else {
emit ClaimAltRewards(recipient, amount);
}
}
//Should be called only once after migration to new calculation
function setInitialAltRewardsPerShare()
external
onlyOwner
{
uint256 index = altRewardsRounds[GOV_POOL_ID].length;
if(index == 0) {
return;
}
uint256 _currentRound = altRewardsRounds[GOV_POOL_ID].length;
uint256 currentAccumulatedAltRewards = altRewardsRounds[GOV_POOL_ID][_currentRound-1];
altRewardsPerShare[GOV_POOL_ID] = currentAccumulatedAltRewards;
}
} | Anyone can contribute GOV to a given pool | function addExternalReward(uint256 _amount) public checkNoPause {
IMasterChef.PoolInfo storage pool = poolInfo[GOV_POOL_ID];
require(block.number > pool.lastRewardBlock, "rewards not started");
uint256 lpSupply = balanceOf[GOV_POOL_ID];
require(lpSupply != 0, "no deposits");
updatePool(GOV_POOL_ID);
GOV.transferFrom(
address(msg.sender),
address(this),
_amount
);
pool.accGOVPerShare = pool.accGOVPerShare.add(
_amount.mul(1e12).div(lpSupply)
);
emit AddExternalReward(msg.sender, GOV_POOL_ID, _amount);
}
| 15,815,778 |
pragma solidity 0.5.17;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../../utils/BytesLib.sol";
/// @title Group Selection
/// @notice The group selection protocol is an interactive method of selecting
/// candidate group from the set of all stakers given a pseudorandom seed value.
///
/// The protocol produces a representative result, where each staker's profit is
/// proportional to the number of tokens they have staked. Produced candidate
/// groups are of constant size.
///
/// Group selection protocol accepts seed as an input - a pseudorandom value
/// used to construct candidate tickets. Each candidate group member can
/// submit their tickets. The maximum number of tickets one can submit depends
/// on their staking weight - relation of the minimum stake to the candidate's
/// stake.
///
/// There is a certain timeout, expressed in blocks, when tickets can be
/// submitted. Each ticket is a mix of staker's address, virtual staker index
/// and group selection seed. Candidate group members are selected based on
/// the best tickets submitted. There has to be a minimum number of tickets
/// submitted, equal to the candidate group size so that the protocol can
/// complete successfully.
library GroupSelection {
using SafeMath for uint256;
using BytesLib for bytes;
struct Storage {
// Tickets submitted by member candidates during the current group
// selection execution and accepted by the protocol for the
// consideration.
uint64[] tickets;
// Information about ticket submitters (group member candidates).
mapping(uint256 => address) candidate;
// Pseudorandom seed value used as an input for the group selection.
uint256 seed;
// Timeout in blocks after which the ticket submission is finished.
uint256 ticketSubmissionTimeout;
// Number of block at which the group selection started and from which
// ticket submissions are accepted.
uint256 ticketSubmissionStartBlock;
// Indicates whether a group selection is currently in progress.
// Concurrent group selections are not allowed.
bool inProgress;
// Captures the minimum stake when group selection starts. This is to ensure the
// same staking weight divisor is applied for all member candidates participating.
uint256 minimumStake;
// Map simulates a sorted linked list of ticket values by their indexes.
// key -> value represent indices from the tickets[] array.
// 'key' index holds an index of a ticket and 'value' holds an index
// of the next ticket. Tickets are sorted by their value in
// descending order starting from the tail.
// Ex. tickets = [151, 42, 175, 7]
// tail: 2 because tickets[2] = 175
// previousTicketIndex[0] -> 1
// previousTicketIndex[1] -> 3
// previousTicketIndex[2] -> 0
// previousTicketIndex[3] -> 3 note: index that holds a lowest
// value points to itself because there is no `nil` in Solidity.
// Traversing from tail: [2]->[0]->[1]->[3] result in 175->151->42->7
bytes previousTicketIndices;
// Tail represents an index of a ticket in a tickets[] array which holds
// the highest ticket value. It is a tail of the linked list defined by
// `previousTicketIndex`.
uint256 tail;
// Size of a group in the threshold relay.
uint256 groupSize;
}
/// @notice Starts group selection protocol.
/// @param _seed pseudorandom seed value used as an input for the group
/// selection. All submitted tickets needs to have the seed mixed-in into the
/// value.
function start(Storage storage self, uint256 _seed) public {
// We execute the minimum required cleanup here needed in case the
// previous group selection failed and did not clean up properly in
// finish function.
cleanupTickets(self);
self.inProgress = true;
self.seed = _seed;
self.ticketSubmissionStartBlock = block.number;
}
/// @notice Finishes group selection protocol clearing up all the submitted
/// tickets. This function may be expensive if not executed as a part of
/// another transaction consuming a lot of gas and as a result, getting
/// gas refund for clearing up the storage.
function finish(Storage storage self) public {
cleanupCandidates(self);
cleanupTickets(self);
self.inProgress = false;
}
/// @notice Submits ticket to request to participate in a new candidate group.
/// @param ticket Bytes representation of a ticket that holds the following:
/// - ticketValue: first 8 bytes of a result of keccak256 cryptography hash
/// function on the combination of the group selection seed (previous
/// beacon output), staker-specific value (address) and virtual staker index.
/// - stakerValue: a staker-specific value which is the address of the staker.
/// - virtualStakerIndex: 4-bytes number within a range of 1 to staker's weight;
/// has to be unique for all tickets submitted by the given staker for the
/// current candidate group selection.
/// @param stakingWeight Ratio of the minimum stake to the candidate's
/// stake.
function submitTicket(
Storage storage self,
bytes32 ticket,
uint256 stakingWeight
) public {
uint64 ticketValue;
uint160 stakerValue;
uint32 virtualStakerIndex;
bytes memory ticketBytes = abi.encodePacked(ticket);
/* solium-disable-next-line */
assembly {
// ticket value is 8 bytes long
ticketValue := mload(add(ticketBytes, 8))
// staker value is 20 bytes long
stakerValue := mload(add(ticketBytes, 28))
// virtual staker index is 4 bytes long
virtualStakerIndex := mload(add(ticketBytes, 32))
}
submitTicket(
self,
ticketValue,
uint256(stakerValue),
uint256(virtualStakerIndex),
stakingWeight
);
}
/// @notice Submits ticket to request to participate in a new candidate group.
/// @param ticketValue First 8 bytes of a result of keccak256 cryptography hash
/// function on the combination of the group selection seed (previous
/// beacon output), staker-specific value (address) and virtual staker index.
/// @param stakerValue Staker-specific value which is the address of the staker.
/// @param virtualStakerIndex 4-bytes number within a range of 1 to staker's weight;
/// has to be unique for all tickets submitted by the given staker for the
/// current candidate group selection.
/// @param stakingWeight Ratio of the minimum stake to the candidate's
/// stake.
function submitTicket(
Storage storage self,
uint64 ticketValue,
uint256 stakerValue,
uint256 virtualStakerIndex,
uint256 stakingWeight
) public {
if (block.number > self.ticketSubmissionStartBlock.add(self.ticketSubmissionTimeout)) {
revert("Ticket submission is over");
}
if (self.candidate[ticketValue] != address(0)) {
revert("Duplicate ticket");
}
if (isTicketValid(
ticketValue,
stakerValue,
virtualStakerIndex,
stakingWeight,
self.seed
)) {
addTicket(self, ticketValue);
} else {
revert("Invalid ticket");
}
}
/// @notice Performs full verification of the ticket.
function isTicketValid(
uint64 ticketValue,
uint256 stakerValue,
uint256 virtualStakerIndex,
uint256 stakingWeight,
uint256 groupSelectionSeed
) internal view returns(bool) {
uint64 ticketValueExpected;
bytes memory ticketBytes = abi.encodePacked(
keccak256(
abi.encodePacked(
groupSelectionSeed,
stakerValue,
virtualStakerIndex
)
)
);
// use first 8 bytes to compare ticket values
/* solium-disable-next-line */
assembly {
ticketValueExpected := mload(add(ticketBytes, 8))
}
bool isVirtualStakerIndexValid = virtualStakerIndex > 0 && virtualStakerIndex <= stakingWeight;
bool isStakerValueValid = stakerValue == uint256(msg.sender);
bool isTicketValueValid = ticketValue == ticketValueExpected;
return isVirtualStakerIndexValid && isStakerValueValid && isTicketValueValid;
}
/// @notice Adds a new, verified ticket. Ticket is accepted when it is lower
/// than the currently highest ticket or when the number of tickets is still
/// below the group size.
function addTicket(Storage storage self, uint64 newTicketValue) internal {
uint256[] memory previousTicketIndex = readPreviousTicketIndices(self);
uint256[] memory ordered = getTicketValueOrderedIndices(
self,
previousTicketIndex
);
// any ticket goes when the tickets array size is lower than the group size
if (self.tickets.length < self.groupSize) {
// no tickets
if (self.tickets.length == 0) {
self.tickets.push(newTicketValue);
// higher than the current highest
} else if (newTicketValue > self.tickets[self.tail]) {
self.tickets.push(newTicketValue);
uint256 oldTail = self.tail;
self.tail = self.tickets.length-1;
previousTicketIndex[self.tail] = oldTail;
// lower than the current lowest
} else if (newTicketValue < self.tickets[ordered[0]]) {
self.tickets.push(newTicketValue);
// last element points to itself
previousTicketIndex[self.tickets.length - 1] = self.tickets.length - 1;
// previous lowest ticket points to the new lowest
previousTicketIndex[ordered[0]] = self.tickets.length - 1;
// higher than the lowest ticket value and lower than the highest ticket value
} else {
self.tickets.push(newTicketValue);
uint256 j = findReplacementIndex(self, newTicketValue, ordered);
previousTicketIndex[self.tickets.length - 1] = previousTicketIndex[j];
previousTicketIndex[j] = self.tickets.length - 1;
}
self.candidate[newTicketValue] = msg.sender;
} else if (newTicketValue < self.tickets[self.tail]) {
uint256 ticketToRemove = self.tickets[self.tail];
// new ticket is lower than currently lowest
if (newTicketValue < self.tickets[ordered[0]]) {
// replacing highest ticket with the new lowest
self.tickets[self.tail] = newTicketValue;
uint256 newTail = previousTicketIndex[self.tail];
previousTicketIndex[ordered[0]] = self.tail;
previousTicketIndex[self.tail] = self.tail;
self.tail = newTail;
} else { // new ticket is between lowest and highest
uint256 j = findReplacementIndex(self, newTicketValue, ordered);
self.tickets[self.tail] = newTicketValue;
// do not change the order if a new ticket is still highest
if (j != self.tail) {
uint newTail = previousTicketIndex[self.tail];
previousTicketIndex[self.tail] = previousTicketIndex[j];
previousTicketIndex[j] = self.tail;
self.tail = newTail;
}
}
// we are replacing tickets so we also need to replace information
// about the submitter
delete self.candidate[ticketToRemove];
self.candidate[newTicketValue] = msg.sender;
}
storePreviousTicketIndices(self, previousTicketIndex);
}
/// @notice Use binary search to find an index for a new ticket in the tickets[] array
function findReplacementIndex(
Storage storage self,
uint64 newTicketValue,
uint256[] memory ordered
) internal view returns (uint256) {
uint256 lo = 0;
uint256 hi = ordered.length - 1;
uint256 mid = 0;
while (lo <= hi) {
mid = (lo + hi) >> 1;
if (newTicketValue < self.tickets[ordered[mid]]) {
hi = mid - 1;
} else if (newTicketValue > self.tickets[ordered[mid]]) {
lo = mid + 1;
} else {
return ordered[mid];
}
}
return ordered[lo];
}
function readPreviousTicketIndices(Storage storage self)
internal view returns (uint256[] memory uncompressed)
{
bytes memory compressed = self.previousTicketIndices;
uncompressed = new uint256[](self.groupSize);
for (uint256 i = 0; i < compressed.length; i++) {
uncompressed[i] = uint256(uint8(compressed[i]));
}
}
function storePreviousTicketIndices(
Storage storage self,
uint256[] memory uncompressed
) internal {
bytes memory compressed = new bytes(uncompressed.length);
for (uint256 i = 0; i < compressed.length; i++) {
compressed[i] = bytes1(uint8(uncompressed[i]));
}
self.previousTicketIndices = compressed;
}
/// @notice Creates an array of ticket indexes based on their values in the
/// ascending order:
///
/// ordered[n-1] = tail
/// ordered[n-2] = previousTicketIndex[tail]
/// ordered[n-3] = previousTicketIndex[ordered[n-2]]
function getTicketValueOrderedIndices(
Storage storage self,
uint256[] memory previousIndices
) internal view returns (uint256[] memory) {
uint256[] memory ordered = new uint256[](self.tickets.length);
if (ordered.length > 0) {
ordered[self.tickets.length-1] = self.tail;
if (ordered.length > 1) {
for (uint256 i = self.tickets.length - 1; i > 0; i--) {
ordered[i-1] = previousIndices[ordered[i]];
}
}
}
return ordered;
}
/// @notice Gets selected participants in ascending order of their tickets.
function selectedParticipants(Storage storage self) public view returns (address[] memory) {
require(
block.number >= self.ticketSubmissionStartBlock.add(self.ticketSubmissionTimeout),
"Ticket submission in progress"
);
require(self.tickets.length >= self.groupSize, "Not enough tickets submitted");
uint256[] memory previousTicketIndex = readPreviousTicketIndices(self);
address[] memory selected = new address[](self.groupSize);
uint256 ticketIndex = self.tail;
selected[self.tickets.length - 1] = self.candidate[self.tickets[ticketIndex]];
for (uint256 i = self.tickets.length - 1; i > 0; i--) {
ticketIndex = previousTicketIndex[ticketIndex];
selected[i-1] = self.candidate[self.tickets[ticketIndex]];
}
return selected;
}
/// @notice Clears up data of the group selection tickets.
function cleanupTickets(Storage storage self) internal {
delete self.tickets;
self.tail = 0;
}
/// @notice Clears up data of the group selection candidates.
/// This operation may have a significant cost if not executed as a part of
/// another transaction consuming a lot of gas and as a result, getting
/// gas refund for clearing up the storage.
function cleanupCandidates(Storage storage self) internal {
for (uint i = 0; i < self.tickets.length; i++) {
delete self.candidate[self.tickets[i]];
}
}
}
| Performs full verification of the ticket. use first 8 bytes to compare ticket values solium-disable-next-line / | function isTicketValid(
uint64 ticketValue,
uint256 stakerValue,
uint256 virtualStakerIndex,
uint256 stakingWeight,
uint256 groupSelectionSeed
) internal view returns(bool) {
uint64 ticketValueExpected;
bytes memory ticketBytes = abi.encodePacked(
keccak256(
abi.encodePacked(
groupSelectionSeed,
stakerValue,
virtualStakerIndex
)
)
);
assembly {
ticketValueExpected := mload(add(ticketBytes, 8))
}
bool isVirtualStakerIndexValid = virtualStakerIndex > 0 && virtualStakerIndex <= stakingWeight;
bool isStakerValueValid = stakerValue == uint256(msg.sender);
bool isTicketValueValid = ticketValue == ticketValueExpected;
return isVirtualStakerIndexValid && isStakerValueValid && isTicketValueValid;
}
| 7,324,562 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "../proxy/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.6.0 <0.8.0;
import "../proxy/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.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_AddressResolver } from "../../../libraries/resolver/Lib_AddressResolver.sol";
import { Lib_OVMCodec } from "../../../libraries/codec/Lib_OVMCodec.sol";
import { Lib_AddressManager } from "../../../libraries/resolver/Lib_AddressManager.sol";
import { Lib_SecureMerkleTrie } from "../../../libraries/trie/Lib_SecureMerkleTrie.sol";
import { Lib_PredeployAddresses } from "../../../libraries/constants/Lib_PredeployAddresses.sol";
import { Lib_CrossDomainUtils } from "../../../libraries/bridge/Lib_CrossDomainUtils.sol";
/* Interface Imports */
import { iOVM_L1CrossDomainMessenger } from "../../../iOVM/bridge/messaging/iOVM_L1CrossDomainMessenger.sol";
import { iOVM_CanonicalTransactionChain } from "../../../iOVM/chain/iOVM_CanonicalTransactionChain.sol";
import { iOVM_StateCommitmentChain } from "../../../iOVM/chain/iOVM_StateCommitmentChain.sol";
/* External Imports */
import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { PausableUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
/**
* @title OVM_L1CrossDomainMessenger
* @dev The L1 Cross Domain Messenger contract sends messages from L1 to L2, and relays messages
* from L2 onto L1. In the event that a message sent from L1 to L2 is rejected for exceeding the L2
* epoch gas limit, it can be resubmitted via this contract's replay function.
*
* Compiler used: solc
* Runtime target: EVM
*/
contract OVM_L1CrossDomainMessenger is
iOVM_L1CrossDomainMessenger,
Lib_AddressResolver,
OwnableUpgradeable,
PausableUpgradeable,
ReentrancyGuardUpgradeable
{
/**********
* Events *
**********/
event MessageBlocked(
bytes32 indexed _xDomainCalldataHash
);
event MessageAllowed(
bytes32 indexed _xDomainCalldataHash
);
/*************
* Constants *
*************/
// The default x-domain message sender being set to a non-zero value makes
// deployment a bit more expensive, but in exchange the refund on every call to
// `relayMessage` by the L1 and L2 messengers will be higher.
address internal constant DEFAULT_XDOMAIN_SENDER = 0x000000000000000000000000000000000000dEaD;
/**********************
* Contract Variables *
**********************/
mapping (bytes32 => bool) public blockedMessages;
mapping (bytes32 => bool) public relayedMessages;
mapping (bytes32 => bool) public successfulMessages;
address internal xDomainMsgSender = DEFAULT_XDOMAIN_SENDER;
/***************
* Constructor *
***************/
/**
* This contract is intended to be behind a delegate proxy.
* We pass the zero address to the address resolver just to satisfy the constructor.
* We still need to set this value in initialize().
*/
constructor()
Lib_AddressResolver(address(0))
{}
/**********************
* Function Modifiers *
**********************/
/**
* Modifier to enforce that, if configured, only the OVM_L2MessageRelayer contract may
* successfully call a method.
*/
modifier onlyRelayer() {
address relayer = resolve("OVM_L2MessageRelayer");
if (relayer != address(0)) {
require(
msg.sender == relayer,
"Only OVM_L2MessageRelayer can relay L2-to-L1 messages."
);
}
_;
}
/********************
* Public Functions *
********************/
/**
* @param _libAddressManager Address of the Address Manager.
*/
function initialize(
address _libAddressManager
)
public
initializer
{
require(
address(libAddressManager) == address(0),
"L1CrossDomainMessenger already intialized."
);
libAddressManager = Lib_AddressManager(_libAddressManager);
xDomainMsgSender = DEFAULT_XDOMAIN_SENDER;
// Initialize upgradable OZ contracts
__Context_init_unchained(); // Context is a dependency for both Ownable and Pausable
__Ownable_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
}
/**
* Pause relaying.
*/
function pause()
external
onlyOwner
{
_pause();
}
/**
* Block a message.
* @param _xDomainCalldataHash Hash of the message to block.
*/
function blockMessage(
bytes32 _xDomainCalldataHash
)
external
onlyOwner
{
blockedMessages[_xDomainCalldataHash] = true;
emit MessageBlocked(_xDomainCalldataHash);
}
/**
* Allow a message.
* @param _xDomainCalldataHash Hash of the message to block.
*/
function allowMessage(
bytes32 _xDomainCalldataHash
)
external
onlyOwner
{
blockedMessages[_xDomainCalldataHash] = false;
emit MessageAllowed(_xDomainCalldataHash);
}
function xDomainMessageSender()
public
override
view
returns (
address
)
{
require(xDomainMsgSender != DEFAULT_XDOMAIN_SENDER, "xDomainMessageSender is not set");
return xDomainMsgSender;
}
/**
* Sends a cross domain message to the target messenger.
* @param _target Target contract address.
* @param _message Message to send to the target.
* @param _gasLimit Gas limit for the provided message.
*/
function sendMessage(
address _target,
bytes memory _message,
uint32 _gasLimit
)
override
public
{
address ovmCanonicalTransactionChain = resolve("OVM_CanonicalTransactionChain");
// Use the CTC queue length as nonce
uint40 nonce = iOVM_CanonicalTransactionChain(ovmCanonicalTransactionChain).getQueueLength();
bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(
_target,
msg.sender,
_message,
nonce
);
address l2CrossDomainMessenger = resolve("OVM_L2CrossDomainMessenger");
_sendXDomainMessage(ovmCanonicalTransactionChain, l2CrossDomainMessenger, xDomainCalldata, _gasLimit);
emit SentMessage(xDomainCalldata);
}
/**
* Relays a cross domain message to a contract.
* @inheritdoc iOVM_L1CrossDomainMessenger
*/
function relayMessage(
address _target,
address _sender,
bytes memory _message,
uint256 _messageNonce,
L2MessageInclusionProof memory _proof
)
override
public
nonReentrant
onlyRelayer
whenNotPaused
{
bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(
_target,
_sender,
_message,
_messageNonce
);
require(
_verifyXDomainMessage(
xDomainCalldata,
_proof
) == true,
"Provided message could not be verified."
);
bytes32 xDomainCalldataHash = keccak256(xDomainCalldata);
require(
successfulMessages[xDomainCalldataHash] == false,
"Provided message has already been received."
);
require(
blockedMessages[xDomainCalldataHash] == false,
"Provided message has been blocked."
);
require(
_target != resolve("OVM_CanonicalTransactionChain"),
"Cannot send L2->L1 messages to L1 system contracts."
);
xDomainMsgSender = _sender;
(bool success, ) = _target.call(_message);
xDomainMsgSender = DEFAULT_XDOMAIN_SENDER;
// Mark the message as received if the call was successful. Ensures that a message can be
// relayed multiple times in the case that the call reverted.
if (success == true) {
successfulMessages[xDomainCalldataHash] = true;
emit RelayedMessage(xDomainCalldataHash);
} else {
emit FailedRelayedMessage(xDomainCalldataHash);
}
// Store an identifier that can be used to prove that the given message was relayed by some
// user. Gives us an easy way to pay relayers for their work.
bytes32 relayId = keccak256(
abi.encodePacked(
xDomainCalldata,
msg.sender,
block.number
)
);
relayedMessages[relayId] = true;
}
/**
* Replays a cross domain message to the target messenger.
* @inheritdoc iOVM_L1CrossDomainMessenger
*/
function replayMessage(
address _target,
address _sender,
bytes memory _message,
uint256 _queueIndex,
uint32 _gasLimit
)
override
public
{
// Verify that the message is in the queue:
address canonicalTransactionChain = resolve("OVM_CanonicalTransactionChain");
Lib_OVMCodec.QueueElement memory element = iOVM_CanonicalTransactionChain(canonicalTransactionChain).getQueueElement(_queueIndex);
address l2CrossDomainMessenger = resolve("OVM_L2CrossDomainMessenger");
// Compute the transactionHash
bytes32 transactionHash = keccak256(
abi.encode(
address(this),
l2CrossDomainMessenger,
_gasLimit,
_message
)
);
require(
transactionHash == element.transactionHash,
"Provided message has not been enqueued."
);
bytes memory xDomainCalldata = Lib_CrossDomainUtils.encodeXDomainCalldata(
_target,
_sender,
_message,
_queueIndex
);
_sendXDomainMessage(canonicalTransactionChain, l2CrossDomainMessenger, xDomainCalldata, _gasLimit);
}
/**********************
* Internal Functions *
**********************/
/**
* Verifies that the given message is valid.
* @param _xDomainCalldata Calldata to verify.
* @param _proof Inclusion proof for the message.
* @return Whether or not the provided message is valid.
*/
function _verifyXDomainMessage(
bytes memory _xDomainCalldata,
L2MessageInclusionProof memory _proof
)
internal
view
returns (
bool
)
{
return (
_verifyStateRootProof(_proof)
&& _verifyStorageProof(_xDomainCalldata, _proof)
);
}
/**
* Verifies that the state root within an inclusion proof is valid.
* @param _proof Message inclusion proof.
* @return Whether or not the provided proof is valid.
*/
function _verifyStateRootProof(
L2MessageInclusionProof memory _proof
)
internal
view
returns (
bool
)
{
iOVM_StateCommitmentChain ovmStateCommitmentChain = iOVM_StateCommitmentChain(
resolve("OVM_StateCommitmentChain")
);
return (
ovmStateCommitmentChain.insideFraudProofWindow(_proof.stateRootBatchHeader) == false
&& ovmStateCommitmentChain.verifyStateCommitment(
_proof.stateRoot,
_proof.stateRootBatchHeader,
_proof.stateRootProof
)
);
}
/**
* Verifies that the storage proof within an inclusion proof is valid.
* @param _xDomainCalldata Encoded message calldata.
* @param _proof Message inclusion proof.
* @return Whether or not the provided proof is valid.
*/
function _verifyStorageProof(
bytes memory _xDomainCalldata,
L2MessageInclusionProof memory _proof
)
internal
view
returns (
bool
)
{
bytes32 storageKey = keccak256(
abi.encodePacked(
keccak256(
abi.encodePacked(
_xDomainCalldata,
resolve("OVM_L2CrossDomainMessenger")
)
),
uint256(0)
)
);
(
bool exists,
bytes memory encodedMessagePassingAccount
) = Lib_SecureMerkleTrie.get(
abi.encodePacked(Lib_PredeployAddresses.L2_TO_L1_MESSAGE_PASSER),
_proof.stateTrieWitness,
_proof.stateRoot
);
require(
exists == true,
"Message passing predeploy has not been initialized or invalid proof provided."
);
Lib_OVMCodec.EVMAccount memory account = Lib_OVMCodec.decodeEVMAccount(
encodedMessagePassingAccount
);
return Lib_SecureMerkleTrie.verifyInclusionProof(
abi.encodePacked(storageKey),
abi.encodePacked(uint8(1)),
_proof.storageTrieWitness,
account.storageRoot
);
}
/**
* Sends a cross domain message.
* @param _canonicalTransactionChain Address of the OVM_CanonicalTransactionChain instance.
* @param _l2CrossDomainMessenger Address of the OVM_L2CrossDomainMessenger instance.
* @param _message Message to send.
* @param _gasLimit OVM gas limit for the message.
*/
function _sendXDomainMessage(
address _canonicalTransactionChain,
address _l2CrossDomainMessenger,
bytes memory _message,
uint256 _gasLimit
)
internal
{
iOVM_CanonicalTransactionChain(_canonicalTransactionChain).enqueue(
_l2CrossDomainMessenger,
_gasLimit,
_message
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @title iOVM_CrossDomainMessenger
*/
interface iOVM_CrossDomainMessenger {
/**********
* Events *
**********/
event SentMessage(bytes message);
event RelayedMessage(bytes32 msgHash);
event FailedRelayedMessage(bytes32 msgHash);
/*************
* Variables *
*************/
function xDomainMessageSender() external view returns (address);
/********************
* Public Functions *
********************/
/**
* Sends a cross domain message to the target messenger.
* @param _target Target contract address.
* @param _message Message to send to the target.
* @param _gasLimit Gas limit for the provided message.
*/
function sendMessage(
address _target,
bytes calldata _message,
uint32 _gasLimit
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../../libraries/codec/Lib_OVMCodec.sol";
/* Interface Imports */
import { iOVM_CrossDomainMessenger } from "./iOVM_CrossDomainMessenger.sol";
/**
* @title iOVM_L1CrossDomainMessenger
*/
interface iOVM_L1CrossDomainMessenger is iOVM_CrossDomainMessenger {
/*******************
* Data Structures *
*******************/
struct L2MessageInclusionProof {
bytes32 stateRoot;
Lib_OVMCodec.ChainBatchHeader stateRootBatchHeader;
Lib_OVMCodec.ChainInclusionProof stateRootProof;
bytes stateTrieWitness;
bytes storageTrieWitness;
}
/********************
* Public Functions *
********************/
/**
* Relays a cross domain message to a contract.
* @param _target Target contract address.
* @param _sender Message sender address.
* @param _message Message to send to the target.
* @param _messageNonce Nonce for the provided message.
* @param _proof Inclusion proof for the given message.
*/
function relayMessage(
address _target,
address _sender,
bytes memory _message,
uint256 _messageNonce,
L2MessageInclusionProof memory _proof
) external;
/**
* Replays a cross domain message to the target messenger.
* @param _target Target contract address.
* @param _sender Original sender address.
* @param _message Message to send to the target.
* @param _queueIndex CTC Queue index for the message to replay.
* @param _gasLimit Gas limit for the provided message.
*/
function replayMessage(
address _target,
address _sender,
bytes memory _message,
uint256 _queueIndex,
uint32 _gasLimit
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/* Interface Imports */
import { iOVM_ChainStorageContainer } from "./iOVM_ChainStorageContainer.sol";
/**
* @title iOVM_CanonicalTransactionChain
*/
interface iOVM_CanonicalTransactionChain {
/**********
* Events *
**********/
event TransactionEnqueued(
address _l1TxOrigin,
address _target,
uint256 _gasLimit,
bytes _data,
uint256 _queueIndex,
uint256 _timestamp
);
event QueueBatchAppended(
uint256 _startingQueueIndex,
uint256 _numQueueElements,
uint256 _totalElements
);
event SequencerBatchAppended(
uint256 _startingQueueIndex,
uint256 _numQueueElements,
uint256 _totalElements
);
event TransactionBatchAppended(
uint256 indexed _batchIndex,
bytes32 _batchRoot,
uint256 _batchSize,
uint256 _prevTotalElements,
bytes _extraData
);
/***********
* Structs *
***********/
struct BatchContext {
uint256 numSequencedTransactions;
uint256 numSubsequentQueueTransactions;
uint256 timestamp;
uint256 blockNumber;
}
/********************
* Public Functions *
********************/
/**
* Accesses the batch storage container.
* @return Reference to the batch storage container.
*/
function batches()
external
view
returns (
iOVM_ChainStorageContainer
);
/**
* Accesses the queue storage container.
* @return Reference to the queue storage container.
*/
function queue()
external
view
returns (
iOVM_ChainStorageContainer
);
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements()
external
view
returns (
uint256 _totalElements
);
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches()
external
view
returns (
uint256 _totalBatches
);
/**
* Returns the index of the next element to be enqueued.
* @return Index for the next queue element.
*/
function getNextQueueIndex()
external
view
returns (
uint40
);
/**
* Gets the queue element at a particular index.
* @param _index Index of the queue element to access.
* @return _element Queue element at the given index.
*/
function getQueueElement(
uint256 _index
)
external
view
returns (
Lib_OVMCodec.QueueElement memory _element
);
/**
* Returns the timestamp of the last transaction.
* @return Timestamp for the last transaction.
*/
function getLastTimestamp()
external
view
returns (
uint40
);
/**
* Returns the blocknumber of the last transaction.
* @return Blocknumber for the last transaction.
*/
function getLastBlockNumber()
external
view
returns (
uint40
);
/**
* Get the number of queue elements which have not yet been included.
* @return Number of pending queue elements.
*/
function getNumPendingQueueElements()
external
view
returns (
uint40
);
/**
* Retrieves the length of the queue, including
* both pending and canonical transactions.
* @return Length of the queue.
*/
function getQueueLength()
external
view
returns (
uint40
);
/**
* Adds a transaction to the queue.
* @param _target Target contract to send the transaction to.
* @param _gasLimit Gas limit for the given transaction.
* @param _data Transaction data.
*/
function enqueue(
address _target,
uint256 _gasLimit,
bytes memory _data
)
external;
/**
* Appends a given number of queued transactions as a single batch.
* @param _numQueuedTransactions Number of transactions to append.
*/
function appendQueueBatch(
uint256 _numQueuedTransactions
)
external;
/**
* Allows the sequencer to append a batch of transactions.
* @dev This function uses a custom encoding scheme for efficiency reasons.
* .param _shouldStartAtElement Specific batch we expect to start appending to.
* .param _totalElementsToAppend Total number of batch elements we expect to append.
* .param _contexts Array of batch contexts.
* .param _transactionDataFields Array of raw transaction data.
*/
function appendSequencerBatch(
// uint40 _shouldStartAtElement,
// uint24 _totalElementsToAppend,
// BatchContext[] _contexts,
// bytes[] _transactionDataFields
)
external;
/**
* Verifies whether a transaction is included in the chain.
* @param _transaction Transaction to verify.
* @param _txChainElement Transaction chain element corresponding to the transaction.
* @param _batchHeader Header of the batch the transaction was included in.
* @param _inclusionProof Inclusion proof for the provided transaction chain element.
* @return True if the transaction exists in the CTC, false if not.
*/
function verifyTransaction(
Lib_OVMCodec.Transaction memory _transaction,
Lib_OVMCodec.TransactionChainElement memory _txChainElement,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _inclusionProof
)
external
view
returns (
bool
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title iOVM_ChainStorageContainer
*/
interface iOVM_ChainStorageContainer {
/********************
* Public Functions *
********************/
/**
* Sets the container's global metadata field. We're using `bytes27` here because we use five
* bytes to maintain the length of the underlying data structure, meaning we have an extra
* 27 bytes to store arbitrary data.
* @param _globalMetadata New global metadata to set.
*/
function setGlobalMetadata(
bytes27 _globalMetadata
)
external;
/**
* Retrieves the container's global metadata field.
* @return Container global metadata field.
*/
function getGlobalMetadata()
external
view
returns (
bytes27
);
/**
* Retrieves the number of objects stored in the container.
* @return Number of objects in the container.
*/
function length()
external
view
returns (
uint256
);
/**
* Pushes an object into the container.
* @param _object A 32 byte value to insert into the container.
*/
function push(
bytes32 _object
)
external;
/**
* Pushes an object into the container. Function allows setting the global metadata since
* we'll need to touch the "length" storage slot anyway, which also contains the global
* metadata (it's an optimization).
* @param _object A 32 byte value to insert into the container.
* @param _globalMetadata New global metadata for the container.
*/
function push(
bytes32 _object,
bytes27 _globalMetadata
)
external;
/**
* Retrieves an object from the container.
* @param _index Index of the particular object to access.
* @return 32 byte object value.
*/
function get(
uint256 _index
)
external
view
returns (
bytes32
);
/**
* Removes all objects after and including a given index.
* @param _index Object index to delete from.
*/
function deleteElementsAfterInclusive(
uint256 _index
)
external;
/**
* Removes all objects after and including a given index. Also allows setting the global
* metadata field.
* @param _index Object index to delete from.
* @param _globalMetadata New global metadata for the container.
*/
function deleteElementsAfterInclusive(
uint256 _index,
bytes27 _globalMetadata
)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_OVMCodec } from "../../libraries/codec/Lib_OVMCodec.sol";
/**
* @title iOVM_StateCommitmentChain
*/
interface iOVM_StateCommitmentChain {
/**********
* Events *
**********/
event StateBatchAppended(
uint256 indexed _batchIndex,
bytes32 _batchRoot,
uint256 _batchSize,
uint256 _prevTotalElements,
bytes _extraData
);
event StateBatchDeleted(
uint256 indexed _batchIndex,
bytes32 _batchRoot
);
/********************
* Public Functions *
********************/
/**
* Retrieves the total number of elements submitted.
* @return _totalElements Total submitted elements.
*/
function getTotalElements()
external
view
returns (
uint256 _totalElements
);
/**
* Retrieves the total number of batches submitted.
* @return _totalBatches Total submitted batches.
*/
function getTotalBatches()
external
view
returns (
uint256 _totalBatches
);
/**
* Retrieves the timestamp of the last batch submitted by the sequencer.
* @return _lastSequencerTimestamp Last sequencer batch timestamp.
*/
function getLastSequencerTimestamp()
external
view
returns (
uint256 _lastSequencerTimestamp
);
/**
* Appends a batch of state roots to the chain.
* @param _batch Batch of state roots.
* @param _shouldStartAtElement Index of the element at which this batch should start.
*/
function appendStateBatch(
bytes32[] calldata _batch,
uint256 _shouldStartAtElement
)
external;
/**
* Deletes all state roots after (and including) a given batch.
* @param _batchHeader Header of the batch to start deleting from.
*/
function deleteStateBatch(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external;
/**
* Verifies a batch inclusion proof.
* @param _element Hash of the element to verify a proof for.
* @param _batchHeader Header of the batch in which the element was included.
* @param _proof Merkle inclusion proof for the element.
*/
function verifyStateCommitment(
bytes32 _element,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _proof
)
external
view
returns (
bool _verified
);
/**
* Checks whether a given batch is still inside its fraud proof window.
* @param _batchHeader Header of the batch to check.
* @return _inside Whether or not the batch is inside the fraud proof window.
*/
function insideFraudProofWindow(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
external
view
returns (
bool _inside
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
/**
* @title Lib_CrossDomainUtils
*/
library Lib_CrossDomainUtils {
/**
* Generates the correct cross domain calldata for a message.
* @param _target Target contract address.
* @param _sender Message sender address.
* @param _message Message to send to the target.
* @param _messageNonce Nonce for the provided message.
* @return ABI encoded cross domain calldata.
*/
function encodeXDomainCalldata(
address _target,
address _sender,
bytes memory _message,
uint256 _messageNonce
)
internal
pure
returns (
bytes memory
)
{
return abi.encodeWithSignature(
"relayMessage(address,address,bytes,uint256)",
_target,
_sender,
_message,
_messageNonce
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol";
import { Lib_Bytes32Utils } from "../utils/Lib_Bytes32Utils.sol";
/**
* @title Lib_OVMCodec
*/
library Lib_OVMCodec {
/*********
* Enums *
*********/
enum QueueOrigin {
SEQUENCER_QUEUE,
L1TOL2_QUEUE
}
/***********
* Structs *
***********/
struct Account {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
address ethAddress;
bool isFresh;
}
struct EVMAccount {
uint256 nonce;
uint256 balance;
bytes32 storageRoot;
bytes32 codeHash;
}
struct ChainBatchHeader {
uint256 batchIndex;
bytes32 batchRoot;
uint256 batchSize;
uint256 prevTotalElements;
bytes extraData;
}
struct ChainInclusionProof {
uint256 index;
bytes32[] siblings;
}
struct Transaction {
uint256 timestamp;
uint256 blockNumber;
QueueOrigin l1QueueOrigin;
address l1TxOrigin;
address entrypoint;
uint256 gasLimit;
bytes data;
}
struct TransactionChainElement {
bool isSequenced;
uint256 queueIndex; // QUEUED TX ONLY
uint256 timestamp; // SEQUENCER TX ONLY
uint256 blockNumber; // SEQUENCER TX ONLY
bytes txData; // SEQUENCER TX ONLY
}
struct QueueElement {
bytes32 transactionHash;
uint40 timestamp;
uint40 blockNumber;
}
/**********************
* Internal Functions *
**********************/
/**
* Encodes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Encoded transaction bytes.
*/
function encodeTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes memory
)
{
return abi.encodePacked(
_transaction.timestamp,
_transaction.blockNumber,
_transaction.l1QueueOrigin,
_transaction.l1TxOrigin,
_transaction.entrypoint,
_transaction.gasLimit,
_transaction.data
);
}
/**
* Hashes a standard OVM transaction.
* @param _transaction OVM transaction to encode.
* @return Hashed transaction
*/
function hashTransaction(
Transaction memory _transaction
)
internal
pure
returns (
bytes32
)
{
return keccak256(encodeTransaction(_transaction));
}
/**
* Converts an OVM account to an EVM account.
* @param _in OVM account to convert.
* @return Converted EVM account.
*/
function toEVMAccount(
Account memory _in
)
internal
pure
returns (
EVMAccount memory
)
{
return EVMAccount({
nonce: _in.nonce,
balance: _in.balance,
storageRoot: _in.storageRoot,
codeHash: _in.codeHash
});
}
/**
* @notice RLP-encodes an account state struct.
* @param _account Account state struct.
* @return RLP-encoded account state.
*/
function encodeEVMAccount(
EVMAccount memory _account
)
internal
pure
returns (
bytes memory
)
{
bytes[] memory raw = new bytes[](4);
// Unfortunately we can't create this array outright because
// Lib_RLPWriter.writeList will reject fixed-size arrays. Assigning
// index-by-index circumvents this issue.
raw[0] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.nonce)
)
);
raw[1] = Lib_RLPWriter.writeBytes(
Lib_Bytes32Utils.removeLeadingZeros(
bytes32(_account.balance)
)
);
raw[2] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.storageRoot));
raw[3] = Lib_RLPWriter.writeBytes(abi.encodePacked(_account.codeHash));
return Lib_RLPWriter.writeList(raw);
}
/**
* @notice Decodes an RLP-encoded account state into a useful struct.
* @param _encoded RLP-encoded account state.
* @return Account state struct.
*/
function decodeEVMAccount(
bytes memory _encoded
)
internal
pure
returns (
EVMAccount memory
)
{
Lib_RLPReader.RLPItem[] memory accountState = Lib_RLPReader.readList(_encoded);
return EVMAccount({
nonce: Lib_RLPReader.readUint256(accountState[0]),
balance: Lib_RLPReader.readUint256(accountState[1]),
storageRoot: Lib_RLPReader.readBytes32(accountState[2]),
codeHash: Lib_RLPReader.readBytes32(accountState[3])
});
}
/**
* Calculates a hash for a given batch header.
* @param _batchHeader Header to hash.
* @return Hash of the header.
*/
function hashBatchHeader(
Lib_OVMCodec.ChainBatchHeader memory _batchHeader
)
internal
pure
returns (
bytes32
)
{
return keccak256(
abi.encode(
_batchHeader.batchRoot,
_batchHeader.batchSize,
_batchHeader.prevTotalElements,
_batchHeader.extraData
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_PredeployAddresses
*/
library Lib_PredeployAddresses {
address internal constant L2_TO_L1_MESSAGE_PASSER = 0x4200000000000000000000000000000000000000;
address internal constant L1_MESSAGE_SENDER = 0x4200000000000000000000000000000000000001;
address internal constant DEPLOYER_WHITELIST = 0x4200000000000000000000000000000000000002;
address internal constant ECDSA_CONTRACT_ACCOUNT = 0x4200000000000000000000000000000000000003;
address internal constant SEQUENCER_ENTRYPOINT = 0x4200000000000000000000000000000000000005;
address payable internal constant OVM_ETH = 0x4200000000000000000000000000000000000006;
address internal constant L2_CROSS_DOMAIN_MESSENGER = 0x4200000000000000000000000000000000000007;
address internal constant LIB_ADDRESS_MANAGER = 0x4200000000000000000000000000000000000008;
address internal constant PROXY_EOA = 0x4200000000000000000000000000000000000009;
address internal constant EXECUTION_MANAGER_WRAPPER = 0x420000000000000000000000000000000000000B;
address internal constant SEQUENCER_FEE_WALLET = 0x4200000000000000000000000000000000000011;
address internal constant ERC1820_REGISTRY = 0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24;
address internal constant L2_STANDARD_BRIDGE = 0x4200000000000000000000000000000000000010;
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* External Imports */
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
/**
* @title Lib_AddressManager
*/
contract Lib_AddressManager is Ownable {
/**********
* Events *
**********/
event AddressSet(
string indexed _name,
address _newAddress,
address _oldAddress
);
/*************
* Variables *
*************/
mapping (bytes32 => address) private addresses;
/********************
* Public Functions *
********************/
/**
* Changes the address associated with a particular name.
* @param _name String name to associate an address with.
* @param _address Address to associate with the name.
*/
function setAddress(
string memory _name,
address _address
)
external
onlyOwner
{
bytes32 nameHash = _getNameHash(_name);
address oldAddress = addresses[nameHash];
addresses[nameHash] = _address;
emit AddressSet(
_name,
_address,
oldAddress
);
}
/**
* Retrieves the address associated with a given name.
* @param _name Name to retrieve an address for.
* @return Address associated with the given name.
*/
function getAddress(
string memory _name
)
external
view
returns (
address
)
{
return addresses[_getNameHash(_name)];
}
/**********************
* Internal Functions *
**********************/
/**
* Computes the hash of a name.
* @param _name Name to compute a hash for.
* @return Hash of the given name.
*/
function _getNameHash(
string memory _name
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_name));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_AddressManager } from "./Lib_AddressManager.sol";
/**
* @title Lib_AddressResolver
*/
abstract contract Lib_AddressResolver {
/*************
* Variables *
*************/
Lib_AddressManager public libAddressManager;
/***************
* Constructor *
***************/
/**
* @param _libAddressManager Address of the Lib_AddressManager.
*/
constructor(
address _libAddressManager
) {
libAddressManager = Lib_AddressManager(_libAddressManager);
}
/********************
* Public Functions *
********************/
/**
* Resolves the address associated with a given name.
* @param _name Name to resolve an address for.
* @return Address associated with the given name.
*/
function resolve(
string memory _name
)
public
view
returns (
address
)
{
return libAddressManager.getAddress(_name);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_RLPReader
* @dev Adapted from "RLPReader" by Hamdi Allam ([email protected]).
*/
library Lib_RLPReader {
/*************
* Constants *
*************/
uint256 constant internal MAX_LIST_LENGTH = 32;
/*********
* Enums *
*********/
enum RLPItemType {
DATA_ITEM,
LIST_ITEM
}
/***********
* Structs *
***********/
struct RLPItem {
uint256 length;
uint256 ptr;
}
/**********************
* Internal Functions *
**********************/
/**
* Converts bytes to a reference to memory position and length.
* @param _in Input bytes to convert.
* @return Output memory reference.
*/
function toRLPItem(
bytes memory _in
)
internal
pure
returns (
RLPItem memory
)
{
uint256 ptr;
assembly {
ptr := add(_in, 32)
}
return RLPItem({
length: _in.length,
ptr: ptr
});
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
RLPItem memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
(
uint256 listOffset,
,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.LIST_ITEM,
"Invalid RLP list value."
);
// Solidity in-memory arrays can't be increased in size, but *can* be decreased in size by
// writing to the length. Since we can't know the number of RLP items without looping over
// the entire input, we'd have to loop twice to accurately size this array. It's easier to
// simply set a reasonable maximum list length and decrease the size before we finish.
RLPItem[] memory out = new RLPItem[](MAX_LIST_LENGTH);
uint256 itemCount = 0;
uint256 offset = listOffset;
while (offset < _in.length) {
require(
itemCount < MAX_LIST_LENGTH,
"Provided RLP list exceeds max list length."
);
(
uint256 itemOffset,
uint256 itemLength,
) = _decodeLength(RLPItem({
length: _in.length - offset,
ptr: _in.ptr + offset
}));
out[itemCount] = RLPItem({
length: itemLength + itemOffset,
ptr: _in.ptr + offset
});
itemCount += 1;
offset += itemOffset + itemLength;
}
// Decrease the array size to match the actual item count.
assembly {
mstore(out, itemCount)
}
return out;
}
/**
* Reads an RLP list value into a list of RLP items.
* @param _in RLP list value.
* @return Decoded RLP list items.
*/
function readList(
bytes memory _in
)
internal
pure
returns (
RLPItem[] memory
)
{
return readList(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes value."
);
return _copy(_in.ptr, itemOffset, itemLength);
}
/**
* Reads an RLP bytes value into bytes.
* @param _in RLP bytes value.
* @return Decoded bytes.
*/
function readBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory
)
{
return readBytes(
toRLPItem(_in)
);
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
RLPItem memory _in
)
internal
pure
returns (
string memory
)
{
return string(readBytes(_in));
}
/**
* Reads an RLP string value into a string.
* @param _in RLP string value.
* @return Decoded string.
*/
function readString(
bytes memory _in
)
internal
pure
returns (
string memory
)
{
return readString(
toRLPItem(_in)
);
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
RLPItem memory _in
)
internal
pure
returns (
bytes32
)
{
require(
_in.length <= 33,
"Invalid RLP bytes32 value."
);
(
uint256 itemOffset,
uint256 itemLength,
RLPItemType itemType
) = _decodeLength(_in);
require(
itemType == RLPItemType.DATA_ITEM,
"Invalid RLP bytes32 value."
);
uint256 ptr = _in.ptr + itemOffset;
bytes32 out;
assembly {
out := mload(ptr)
// Shift the bytes over to match the item size.
if lt(itemLength, 32) {
out := div(out, exp(256, sub(32, itemLength)))
}
}
return out;
}
/**
* Reads an RLP bytes32 value into a bytes32.
* @param _in RLP bytes32 value.
* @return Decoded bytes32.
*/
function readBytes32(
bytes memory _in
)
internal
pure
returns (
bytes32
)
{
return readBytes32(
toRLPItem(_in)
);
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
RLPItem memory _in
)
internal
pure
returns (
uint256
)
{
return uint256(readBytes32(_in));
}
/**
* Reads an RLP uint256 value into a uint256.
* @param _in RLP uint256 value.
* @return Decoded uint256.
*/
function readUint256(
bytes memory _in
)
internal
pure
returns (
uint256
)
{
return readUint256(
toRLPItem(_in)
);
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
RLPItem memory _in
)
internal
pure
returns (
bool
)
{
require(
_in.length == 1,
"Invalid RLP boolean value."
);
uint256 ptr = _in.ptr;
uint256 out;
assembly {
out := byte(0, mload(ptr))
}
require(
out == 0 || out == 1,
"Lib_RLPReader: Invalid RLP boolean value, must be 0 or 1"
);
return out != 0;
}
/**
* Reads an RLP bool value into a bool.
* @param _in RLP bool value.
* @return Decoded bool.
*/
function readBool(
bytes memory _in
)
internal
pure
returns (
bool
)
{
return readBool(
toRLPItem(_in)
);
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
RLPItem memory _in
)
internal
pure
returns (
address
)
{
if (_in.length == 1) {
return address(0);
}
require(
_in.length == 21,
"Invalid RLP address value."
);
return address(readUint256(_in));
}
/**
* Reads an RLP address value into a address.
* @param _in RLP address value.
* @return Decoded address.
*/
function readAddress(
bytes memory _in
)
internal
pure
returns (
address
)
{
return readAddress(
toRLPItem(_in)
);
}
/**
* Reads the raw bytes of an RLP item.
* @param _in RLP item to read.
* @return Raw RLP bytes.
*/
function readRawBytes(
RLPItem memory _in
)
internal
pure
returns (
bytes memory
)
{
return _copy(_in);
}
/*********************
* Private Functions *
*********************/
/**
* Decodes the length of an RLP item.
* @param _in RLP item to decode.
* @return Offset of the encoded data.
* @return Length of the encoded data.
* @return RLP item type (LIST_ITEM or DATA_ITEM).
*/
function _decodeLength(
RLPItem memory _in
)
private
pure
returns (
uint256,
uint256,
RLPItemType
)
{
require(
_in.length > 0,
"RLP item cannot be null."
);
uint256 ptr = _in.ptr;
uint256 prefix;
assembly {
prefix := byte(0, mload(ptr))
}
if (prefix <= 0x7f) {
// Single byte.
return (0, 1, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xb7) {
// Short string.
uint256 strLen = prefix - 0x80;
require(
_in.length > strLen,
"Invalid RLP short string."
);
return (1, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xbf) {
// Long string.
uint256 lenOfStrLen = prefix - 0xb7;
require(
_in.length > lenOfStrLen,
"Invalid RLP long string length."
);
uint256 strLen;
assembly {
// Pick out the string length.
strLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfStrLen))
)
}
require(
_in.length > lenOfStrLen + strLen,
"Invalid RLP long string."
);
return (1 + lenOfStrLen, strLen, RLPItemType.DATA_ITEM);
} else if (prefix <= 0xf7) {
// Short list.
uint256 listLen = prefix - 0xc0;
require(
_in.length > listLen,
"Invalid RLP short list."
);
return (1, listLen, RLPItemType.LIST_ITEM);
} else {
// Long list.
uint256 lenOfListLen = prefix - 0xf7;
require(
_in.length > lenOfListLen,
"Invalid RLP long list length."
);
uint256 listLen;
assembly {
// Pick out the list length.
listLen := div(
mload(add(ptr, 1)),
exp(256, sub(32, lenOfListLen))
)
}
require(
_in.length > lenOfListLen + listLen,
"Invalid RLP long list."
);
return (1 + lenOfListLen, listLen, RLPItemType.LIST_ITEM);
}
}
/**
* Copies the bytes from a memory location.
* @param _src Pointer to the location to read from.
* @param _offset Offset to start reading from.
* @param _length Number of bytes to read.
* @return Copied bytes.
*/
function _copy(
uint256 _src,
uint256 _offset,
uint256 _length
)
private
pure
returns (
bytes memory
)
{
bytes memory out = new bytes(_length);
if (out.length == 0) {
return out;
}
uint256 src = _src + _offset;
uint256 dest;
assembly {
dest := add(out, 32)
}
// Copy over as many complete words as we can.
for (uint256 i = 0; i < _length / 32; i++) {
assembly {
mstore(dest, mload(src))
}
src += 32;
dest += 32;
}
// Pick out the remaining bytes.
uint256 mask = 256 ** (32 - (_length % 32)) - 1;
assembly {
mstore(
dest,
or(
and(mload(src), not(mask)),
and(mload(dest), mask)
)
)
}
return out;
}
/**
* Copies an RLP item into bytes.
* @param _in RLP item to copy.
* @return Copied bytes.
*/
function _copy(
RLPItem memory _in
)
private
pure
returns (
bytes memory
)
{
return _copy(_in.ptr, 0, _in.length);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/**
* @title Lib_RLPWriter
* @author Bakaoh (with modifications)
*/
library Lib_RLPWriter {
/**********************
* Internal Functions *
**********************/
/**
* RLP encodes a byte string.
* @param _in The byte string to encode.
* @return The RLP encoded string in bytes.
*/
function writeBytes(
bytes memory _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory encoded;
if (_in.length == 1 && uint8(_in[0]) < 128) {
encoded = _in;
} else {
encoded = abi.encodePacked(_writeLength(_in.length, 128), _in);
}
return encoded;
}
/**
* RLP encodes a list of RLP encoded byte byte strings.
* @param _in The list of RLP encoded byte strings.
* @return The RLP encoded list of items in bytes.
*/
function writeList(
bytes[] memory _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory list = _flatten(_in);
return abi.encodePacked(_writeLength(list.length, 192), list);
}
/**
* RLP encodes a string.
* @param _in The string to encode.
* @return The RLP encoded string in bytes.
*/
function writeString(
string memory _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(bytes(_in));
}
/**
* RLP encodes an address.
* @param _in The address to encode.
* @return The RLP encoded address in bytes.
*/
function writeAddress(
address _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a bytes32 value.
* @param _in The bytes32 to encode.
* @return _out The RLP encoded bytes32 in bytes.
*/
function writeBytes32(
bytes32 _in
)
internal
pure
returns (
bytes memory _out
)
{
return writeBytes(abi.encodePacked(_in));
}
/**
* RLP encodes a uint.
* @param _in The uint256 to encode.
* @return The RLP encoded uint256 in bytes.
*/
function writeUint(
uint256 _in
)
internal
pure
returns (
bytes memory
)
{
return writeBytes(_toBinary(_in));
}
/**
* RLP encodes a bool.
* @param _in The bool to encode.
* @return The RLP encoded bool in bytes.
*/
function writeBool(
bool _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory encoded = new bytes(1);
encoded[0] = (_in ? bytes1(0x01) : bytes1(0x80));
return encoded;
}
/*********************
* Private Functions *
*********************/
/**
* Encode the first byte, followed by the `len` in binary form if `length` is more than 55.
* @param _len The length of the string or the payload.
* @param _offset 128 if item is string, 192 if item is list.
* @return RLP encoded bytes.
*/
function _writeLength(
uint256 _len,
uint256 _offset
)
private
pure
returns (
bytes memory
)
{
bytes memory encoded;
if (_len < 56) {
encoded = new bytes(1);
encoded[0] = byte(uint8(_len) + uint8(_offset));
} else {
uint256 lenLen;
uint256 i = 1;
while (_len / i != 0) {
lenLen++;
i *= 256;
}
encoded = new bytes(lenLen + 1);
encoded[0] = byte(uint8(lenLen) + uint8(_offset) + 55);
for(i = 1; i <= lenLen; i++) {
encoded[i] = byte(uint8((_len / (256**(lenLen-i))) % 256));
}
}
return encoded;
}
/**
* Encode integer in big endian binary form with no leading zeroes.
* @notice TODO: This should be optimized with assembly to save gas costs.
* @param _x The integer to encode.
* @return RLP encoded bytes.
*/
function _toBinary(
uint256 _x
)
private
pure
returns (
bytes memory
)
{
bytes memory b = abi.encodePacked(_x);
uint256 i = 0;
for (; i < 32; i++) {
if (b[i] != 0) {
break;
}
}
bytes memory res = new bytes(32 - i);
for (uint256 j = 0; j < res.length; j++) {
res[j] = b[i++];
}
return res;
}
/**
* Copies a piece of memory to another location.
* @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol.
* @param _dest Destination location.
* @param _src Source location.
* @param _len Length of memory to copy.
*/
function _memcpy(
uint256 _dest,
uint256 _src,
uint256 _len
)
private
pure
{
uint256 dest = _dest;
uint256 src = _src;
uint256 len = _len;
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
uint256 mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/**
* Flattens a list of byte strings into one byte string.
* @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol.
* @param _list List of byte strings to flatten.
* @return The flattened byte string.
*/
function _flatten(
bytes[] memory _list
)
private
pure
returns (
bytes memory
)
{
if (_list.length == 0) {
return new bytes(0);
}
uint256 len;
uint256 i = 0;
for (; i < _list.length; i++) {
len += _list[i].length;
}
bytes memory flattened = new bytes(len);
uint256 flattenedPtr;
assembly { flattenedPtr := add(flattened, 0x20) }
for(i = 0; i < _list.length; i++) {
bytes memory item = _list[i];
uint256 listPtr;
assembly { listPtr := add(item, 0x20)}
_memcpy(flattenedPtr, listPtr, item.length);
flattenedPtr += _list[i].length;
}
return flattened;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/* Library Imports */
import { Lib_BytesUtils } from "../utils/Lib_BytesUtils.sol";
import { Lib_RLPReader } from "../rlp/Lib_RLPReader.sol";
import { Lib_RLPWriter } from "../rlp/Lib_RLPWriter.sol";
/**
* @title Lib_MerkleTrie
*/
library Lib_MerkleTrie {
/*******************
* Data Structures *
*******************/
enum NodeType {
BranchNode,
ExtensionNode,
LeafNode
}
struct TrieNode {
bytes encoded;
Lib_RLPReader.RLPItem[] decoded;
}
/**********************
* Contract Constants *
**********************/
// TREE_RADIX determines the number of elements per branch node.
uint256 constant TREE_RADIX = 16;
// Branch nodes have TREE_RADIX elements plus an additional `value` slot.
uint256 constant BRANCH_NODE_LENGTH = TREE_RADIX + 1;
// Leaf nodes and extension nodes always have two elements, a `path` and a `value`.
uint256 constant LEAF_OR_EXTENSION_NODE_LENGTH = 2;
// Prefixes are prepended to the `path` within a leaf or extension node and
// allow us to differentiate between the two node types. `ODD` or `EVEN` is
// determined by the number of nibbles within the unprefixed `path`. If the
// number of nibbles if even, we need to insert an extra padding nibble so
// the resulting prefixed `path` has an even number of nibbles.
uint8 constant PREFIX_EXTENSION_EVEN = 0;
uint8 constant PREFIX_EXTENSION_ODD = 1;
uint8 constant PREFIX_LEAF_EVEN = 2;
uint8 constant PREFIX_LEAF_ODD = 3;
// Just a utility constant. RLP represents `NULL` as 0x80.
bytes1 constant RLP_NULL = bytes1(0x80);
bytes constant RLP_NULL_BYTES = hex'80';
bytes32 constant internal KECCAK256_RLP_NULL_BYTES = keccak256(RLP_NULL_BYTES);
/**********************
* Internal Functions *
**********************/
/**
* @notice Verifies a proof that a given key/value pair is present in the
* Merkle trie.
* @param _key Key of the node to search for, as a hex string.
* @param _value Value of the node to search for, as a hex string.
* @param _proof Merkle trie inclusion proof for the desired node. Unlike
* traditional Merkle trees, this proof is executed top-down and consists
* of a list of RLP-encoded nodes that make a path down to the target node.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _verified `true` if the k/v pair exists in the trie, `false` otherwise.
*/
function verifyInclusionProof(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _verified
)
{
(
bool exists,
bytes memory value
) = get(_key, _proof, _root);
return (
exists && Lib_BytesUtils.equal(_value, value)
);
}
/**
* @notice Updates a Merkle trie and returns a new root hash.
* @param _key Key of the node to update, as a hex string.
* @param _value Value of the node to update, as a hex string.
* @param _proof Merkle trie inclusion proof for the node *nearest* the
* target node. If the key exists, we can simply update the value.
* Otherwise, we need to modify the trie to handle the new k/v pair.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _updatedRoot Root hash of the newly constructed trie.
*/
function update(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
// Special case when inserting the very first node.
if (_root == KECCAK256_RLP_NULL_BYTES) {
return getSingleNodeRootHash(_key, _value);
}
TrieNode[] memory proof = _parseProof(_proof);
(uint256 pathLength, bytes memory keyRemainder, ) = _walkNodePath(proof, _key, _root);
TrieNode[] memory newPath = _getNewPath(proof, pathLength, _key, keyRemainder, _value);
return _getUpdatedTrieRoot(newPath, _key);
}
/**
* @notice Retrieves the value associated with a given key.
* @param _key Key to search for, as hex bytes.
* @param _proof Merkle trie inclusion proof for the key.
* @param _root Known root of the Merkle trie.
* @return _exists Whether or not the key exists.
* @return _value Value of the key if it exists.
*/
function get(
bytes memory _key,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _exists,
bytes memory _value
)
{
TrieNode[] memory proof = _parseProof(_proof);
(uint256 pathLength, bytes memory keyRemainder, bool isFinalNode) = _walkNodePath(proof, _key, _root);
bool exists = keyRemainder.length == 0;
require(
exists || isFinalNode,
"Provided proof is invalid."
);
bytes memory value = exists ? _getNodeValue(proof[pathLength - 1]) : bytes('');
return (
exists,
value
);
}
/**
* Computes the root hash for a trie with a single node.
* @param _key Key for the single node.
* @param _value Value for the single node.
* @return _updatedRoot Hash of the trie.
*/
function getSingleNodeRootHash(
bytes memory _key,
bytes memory _value
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
return keccak256(_makeLeafNode(
Lib_BytesUtils.toNibbles(_key),
_value
).encoded);
}
/*********************
* Private Functions *
*********************/
/**
* @notice Walks through a proof using a provided key.
* @param _proof Inclusion proof to walk through.
* @param _key Key to use for the walk.
* @param _root Known root of the trie.
* @return _pathLength Length of the final path
* @return _keyRemainder Portion of the key remaining after the walk.
* @return _isFinalNode Whether or not we've hit a dead end.
*/
function _walkNodePath(
TrieNode[] memory _proof,
bytes memory _key,
bytes32 _root
)
private
pure
returns (
uint256 _pathLength,
bytes memory _keyRemainder,
bool _isFinalNode
)
{
uint256 pathLength = 0;
bytes memory key = Lib_BytesUtils.toNibbles(_key);
bytes32 currentNodeID = _root;
uint256 currentKeyIndex = 0;
uint256 currentKeyIncrement = 0;
TrieNode memory currentNode;
// Proof is top-down, so we start at the first element (root).
for (uint256 i = 0; i < _proof.length; i++) {
currentNode = _proof[i];
currentKeyIndex += currentKeyIncrement;
// Keep track of the proof elements we actually need.
// It's expensive to resize arrays, so this simply reduces gas costs.
pathLength += 1;
if (currentKeyIndex == 0) {
// First proof element is always the root node.
require(
keccak256(currentNode.encoded) == currentNodeID,
"Invalid root hash"
);
} else if (currentNode.encoded.length >= 32) {
// Nodes 32 bytes or larger are hashed inside branch nodes.
require(
keccak256(currentNode.encoded) == currentNodeID,
"Invalid large internal hash"
);
} else {
// Nodes smaller than 31 bytes aren't hashed.
require(
Lib_BytesUtils.toBytes32(currentNode.encoded) == currentNodeID,
"Invalid internal node hash"
);
}
if (currentNode.decoded.length == BRANCH_NODE_LENGTH) {
if (currentKeyIndex == key.length) {
// We've hit the end of the key, meaning the value should be within this branch node.
break;
} else {
// We're not at the end of the key yet.
// Figure out what the next node ID should be and continue.
uint8 branchKey = uint8(key[currentKeyIndex]);
Lib_RLPReader.RLPItem memory nextNode = currentNode.decoded[branchKey];
currentNodeID = _getNodeID(nextNode);
currentKeyIncrement = 1;
continue;
}
} else if (currentNode.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) {
bytes memory path = _getNodePath(currentNode);
uint8 prefix = uint8(path[0]);
uint8 offset = 2 - prefix % 2;
bytes memory pathRemainder = Lib_BytesUtils.slice(path, offset);
bytes memory keyRemainder = Lib_BytesUtils.slice(key, currentKeyIndex);
uint256 sharedNibbleLength = _getSharedNibbleLength(pathRemainder, keyRemainder);
if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) {
if (
pathRemainder.length == sharedNibbleLength &&
keyRemainder.length == sharedNibbleLength
) {
// The key within this leaf matches our key exactly.
// Increment the key index to reflect that we have no remainder.
currentKeyIndex += sharedNibbleLength;
}
// We've hit a leaf node, so our next node should be NULL.
currentNodeID = bytes32(RLP_NULL);
break;
} else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) {
if (sharedNibbleLength != pathRemainder.length) {
// Our extension node is not identical to the remainder.
// We've hit the end of this path, updates will need to modify this extension.
currentNodeID = bytes32(RLP_NULL);
break;
} else {
// Our extension shares some nibbles.
// Carry on to the next node.
currentNodeID = _getNodeID(currentNode.decoded[1]);
currentKeyIncrement = sharedNibbleLength;
continue;
}
} else {
revert("Received a node with an unknown prefix");
}
} else {
revert("Received an unparseable node.");
}
}
// If our node ID is NULL, then we're at a dead end.
bool isFinalNode = currentNodeID == bytes32(RLP_NULL);
return (pathLength, Lib_BytesUtils.slice(key, currentKeyIndex), isFinalNode);
}
/**
* @notice Creates new nodes to support a k/v pair insertion into a given Merkle trie path.
* @param _path Path to the node nearest the k/v pair.
* @param _pathLength Length of the path. Necessary because the provided path may include
* additional nodes (e.g., it comes directly from a proof) and we can't resize in-memory
* arrays without costly duplication.
* @param _key Full original key.
* @param _keyRemainder Portion of the initial key that must be inserted into the trie.
* @param _value Value to insert at the given key.
* @return _newPath A new path with the inserted k/v pair and extra supporting nodes.
*/
function _getNewPath(
TrieNode[] memory _path,
uint256 _pathLength,
bytes memory _key,
bytes memory _keyRemainder,
bytes memory _value
)
private
pure
returns (
TrieNode[] memory _newPath
)
{
bytes memory keyRemainder = _keyRemainder;
// Most of our logic depends on the status of the last node in the path.
TrieNode memory lastNode = _path[_pathLength - 1];
NodeType lastNodeType = _getNodeType(lastNode);
// Create an array for newly created nodes.
// We need up to three new nodes, depending on the contents of the last node.
// Since array resizing is expensive, we'll keep track of the size manually.
// We're using an explicit `totalNewNodes += 1` after insertions for clarity.
TrieNode[] memory newNodes = new TrieNode[](3);
uint256 totalNewNodes = 0;
// Reference: https://github.com/ethereumjs/merkle-patricia-tree/blob/c0a10395aab37d42c175a47114ebfcbd7efcf059/src/baseTrie.ts#L294-L313
bool matchLeaf = false;
if (lastNodeType == NodeType.LeafNode) {
uint256 l = 0;
if (_path.length > 0) {
for (uint256 i = 0; i < _path.length - 1; i++) {
if (_getNodeType(_path[i]) == NodeType.BranchNode) {
l++;
} else {
l += _getNodeKey(_path[i]).length;
}
}
}
if (
_getSharedNibbleLength(
_getNodeKey(lastNode),
Lib_BytesUtils.slice(Lib_BytesUtils.toNibbles(_key), l)
) == _getNodeKey(lastNode).length
&& keyRemainder.length == 0
) {
matchLeaf = true;
}
}
if (matchLeaf) {
// We've found a leaf node with the given key.
// Simply need to update the value of the node to match.
newNodes[totalNewNodes] = _makeLeafNode(_getNodeKey(lastNode), _value);
totalNewNodes += 1;
} else if (lastNodeType == NodeType.BranchNode) {
if (keyRemainder.length == 0) {
// We've found a branch node with the given key.
// Simply need to update the value of the node to match.
newNodes[totalNewNodes] = _editBranchValue(lastNode, _value);
totalNewNodes += 1;
} else {
// We've found a branch node, but it doesn't contain our key.
// Reinsert the old branch for now.
newNodes[totalNewNodes] = lastNode;
totalNewNodes += 1;
// Create a new leaf node, slicing our remainder since the first byte points
// to our branch node.
newNodes[totalNewNodes] = _makeLeafNode(Lib_BytesUtils.slice(keyRemainder, 1), _value);
totalNewNodes += 1;
}
} else {
// Our last node is either an extension node or a leaf node with a different key.
bytes memory lastNodeKey = _getNodeKey(lastNode);
uint256 sharedNibbleLength = _getSharedNibbleLength(lastNodeKey, keyRemainder);
if (sharedNibbleLength != 0) {
// We've got some shared nibbles between the last node and our key remainder.
// We'll need to insert an extension node that covers these shared nibbles.
bytes memory nextNodeKey = Lib_BytesUtils.slice(lastNodeKey, 0, sharedNibbleLength);
newNodes[totalNewNodes] = _makeExtensionNode(nextNodeKey, _getNodeHash(_value));
totalNewNodes += 1;
// Cut down the keys since we've just covered these shared nibbles.
lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, sharedNibbleLength);
keyRemainder = Lib_BytesUtils.slice(keyRemainder, sharedNibbleLength);
}
// Create an empty branch to fill in.
TrieNode memory newBranch = _makeEmptyBranchNode();
if (lastNodeKey.length == 0) {
// Key remainder was larger than the key for our last node.
// The value within our last node is therefore going to be shifted into
// a branch value slot.
newBranch = _editBranchValue(newBranch, _getNodeValue(lastNode));
} else {
// Last node key was larger than the key remainder.
// We're going to modify some index of our branch.
uint8 branchKey = uint8(lastNodeKey[0]);
// Move on to the next nibble.
lastNodeKey = Lib_BytesUtils.slice(lastNodeKey, 1);
if (lastNodeType == NodeType.LeafNode) {
// We're dealing with a leaf node.
// We'll modify the key and insert the old leaf node into the branch index.
TrieNode memory modifiedLastNode = _makeLeafNode(lastNodeKey, _getNodeValue(lastNode));
newBranch = _editBranchIndex(newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded));
} else if (lastNodeKey.length != 0) {
// We're dealing with a shrinking extension node.
// We need to modify the node to decrease the size of the key.
TrieNode memory modifiedLastNode = _makeExtensionNode(lastNodeKey, _getNodeValue(lastNode));
newBranch = _editBranchIndex(newBranch, branchKey, _getNodeHash(modifiedLastNode.encoded));
} else {
// We're dealing with an unnecessary extension node.
// We're going to delete the node entirely.
// Simply insert its current value into the branch index.
newBranch = _editBranchIndex(newBranch, branchKey, _getNodeValue(lastNode));
}
}
if (keyRemainder.length == 0) {
// We've got nothing left in the key remainder.
// Simply insert the value into the branch value slot.
newBranch = _editBranchValue(newBranch, _value);
// Push the branch into the list of new nodes.
newNodes[totalNewNodes] = newBranch;
totalNewNodes += 1;
} else {
// We've got some key remainder to work with.
// We'll be inserting a leaf node into the trie.
// First, move on to the next nibble.
keyRemainder = Lib_BytesUtils.slice(keyRemainder, 1);
// Push the branch into the list of new nodes.
newNodes[totalNewNodes] = newBranch;
totalNewNodes += 1;
// Push a new leaf node for our k/v pair.
newNodes[totalNewNodes] = _makeLeafNode(keyRemainder, _value);
totalNewNodes += 1;
}
}
// Finally, join the old path with our newly created nodes.
// Since we're overwriting the last node in the path, we use `_pathLength - 1`.
return _joinNodeArrays(_path, _pathLength - 1, newNodes, totalNewNodes);
}
/**
* @notice Computes the trie root from a given path.
* @param _nodes Path to some k/v pair.
* @param _key Key for the k/v pair.
* @return _updatedRoot Root hash for the updated trie.
*/
function _getUpdatedTrieRoot(
TrieNode[] memory _nodes,
bytes memory _key
)
private
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = Lib_BytesUtils.toNibbles(_key);
// Some variables to keep track of during iteration.
TrieNode memory currentNode;
NodeType currentNodeType;
bytes memory previousNodeHash;
// Run through the path backwards to rebuild our root hash.
for (uint256 i = _nodes.length; i > 0; i--) {
// Pick out the current node.
currentNode = _nodes[i - 1];
currentNodeType = _getNodeType(currentNode);
if (currentNodeType == NodeType.LeafNode) {
// Leaf nodes are already correctly encoded.
// Shift the key over to account for the nodes key.
bytes memory nodeKey = _getNodeKey(currentNode);
key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length);
} else if (currentNodeType == NodeType.ExtensionNode) {
// Shift the key over to account for the nodes key.
bytes memory nodeKey = _getNodeKey(currentNode);
key = Lib_BytesUtils.slice(key, 0, key.length - nodeKey.length);
// If this node is the last element in the path, it'll be correctly encoded
// and we can skip this part.
if (previousNodeHash.length > 0) {
// Re-encode the node based on the previous node.
currentNode = _editExtensionNodeValue(currentNode, previousNodeHash);
}
} else if (currentNodeType == NodeType.BranchNode) {
// If this node is the last element in the path, it'll be correctly encoded
// and we can skip this part.
if (previousNodeHash.length > 0) {
// Re-encode the node based on the previous node.
uint8 branchKey = uint8(key[key.length - 1]);
key = Lib_BytesUtils.slice(key, 0, key.length - 1);
currentNode = _editBranchIndex(currentNode, branchKey, previousNodeHash);
}
}
// Compute the node hash for the next iteration.
previousNodeHash = _getNodeHash(currentNode.encoded);
}
// Current node should be the root at this point.
// Simply return the hash of its encoding.
return keccak256(currentNode.encoded);
}
/**
* @notice Parses an RLP-encoded proof into something more useful.
* @param _proof RLP-encoded proof to parse.
* @return _parsed Proof parsed into easily accessible structs.
*/
function _parseProof(
bytes memory _proof
)
private
pure
returns (
TrieNode[] memory _parsed
)
{
Lib_RLPReader.RLPItem[] memory nodes = Lib_RLPReader.readList(_proof);
TrieNode[] memory proof = new TrieNode[](nodes.length);
for (uint256 i = 0; i < nodes.length; i++) {
bytes memory encoded = Lib_RLPReader.readBytes(nodes[i]);
proof[i] = TrieNode({
encoded: encoded,
decoded: Lib_RLPReader.readList(encoded)
});
}
return proof;
}
/**
* @notice Picks out the ID for a node. Node ID is referred to as the
* "hash" within the specification, but nodes < 32 bytes are not actually
* hashed.
* @param _node Node to pull an ID for.
* @return _nodeID ID for the node, depending on the size of its contents.
*/
function _getNodeID(
Lib_RLPReader.RLPItem memory _node
)
private
pure
returns (
bytes32 _nodeID
)
{
bytes memory nodeID;
if (_node.length < 32) {
// Nodes smaller than 32 bytes are RLP encoded.
nodeID = Lib_RLPReader.readRawBytes(_node);
} else {
// Nodes 32 bytes or larger are hashed.
nodeID = Lib_RLPReader.readBytes(_node);
}
return Lib_BytesUtils.toBytes32(nodeID);
}
/**
* @notice Gets the path for a leaf or extension node.
* @param _node Node to get a path for.
* @return _path Node path, converted to an array of nibbles.
*/
function _getNodePath(
TrieNode memory _node
)
private
pure
returns (
bytes memory _path
)
{
return Lib_BytesUtils.toNibbles(Lib_RLPReader.readBytes(_node.decoded[0]));
}
/**
* @notice Gets the key for a leaf or extension node. Keys are essentially
* just paths without any prefix.
* @param _node Node to get a key for.
* @return _key Node key, converted to an array of nibbles.
*/
function _getNodeKey(
TrieNode memory _node
)
private
pure
returns (
bytes memory _key
)
{
return _removeHexPrefix(_getNodePath(_node));
}
/**
* @notice Gets the path for a node.
* @param _node Node to get a value for.
* @return _value Node value, as hex bytes.
*/
function _getNodeValue(
TrieNode memory _node
)
private
pure
returns (
bytes memory _value
)
{
return Lib_RLPReader.readBytes(_node.decoded[_node.decoded.length - 1]);
}
/**
* @notice Computes the node hash for an encoded node. Nodes < 32 bytes
* are not hashed, all others are keccak256 hashed.
* @param _encoded Encoded node to hash.
* @return _hash Hash of the encoded node. Simply the input if < 32 bytes.
*/
function _getNodeHash(
bytes memory _encoded
)
private
pure
returns (
bytes memory _hash
)
{
if (_encoded.length < 32) {
return _encoded;
} else {
return abi.encodePacked(keccak256(_encoded));
}
}
/**
* @notice Determines the type for a given node.
* @param _node Node to determine a type for.
* @return _type Type of the node; BranchNode/ExtensionNode/LeafNode.
*/
function _getNodeType(
TrieNode memory _node
)
private
pure
returns (
NodeType _type
)
{
if (_node.decoded.length == BRANCH_NODE_LENGTH) {
return NodeType.BranchNode;
} else if (_node.decoded.length == LEAF_OR_EXTENSION_NODE_LENGTH) {
bytes memory path = _getNodePath(_node);
uint8 prefix = uint8(path[0]);
if (prefix == PREFIX_LEAF_EVEN || prefix == PREFIX_LEAF_ODD) {
return NodeType.LeafNode;
} else if (prefix == PREFIX_EXTENSION_EVEN || prefix == PREFIX_EXTENSION_ODD) {
return NodeType.ExtensionNode;
}
}
revert("Invalid node type");
}
/**
* @notice Utility; determines the number of nibbles shared between two
* nibble arrays.
* @param _a First nibble array.
* @param _b Second nibble array.
* @return _shared Number of shared nibbles.
*/
function _getSharedNibbleLength(
bytes memory _a,
bytes memory _b
)
private
pure
returns (
uint256 _shared
)
{
uint256 i = 0;
while (_a.length > i && _b.length > i && _a[i] == _b[i]) {
i++;
}
return i;
}
/**
* @notice Utility; converts an RLP-encoded node into our nice struct.
* @param _raw RLP-encoded node to convert.
* @return _node Node as a TrieNode struct.
*/
function _makeNode(
bytes[] memory _raw
)
private
pure
returns (
TrieNode memory _node
)
{
bytes memory encoded = Lib_RLPWriter.writeList(_raw);
return TrieNode({
encoded: encoded,
decoded: Lib_RLPReader.readList(encoded)
});
}
/**
* @notice Utility; converts an RLP-decoded node into our nice struct.
* @param _items RLP-decoded node to convert.
* @return _node Node as a TrieNode struct.
*/
function _makeNode(
Lib_RLPReader.RLPItem[] memory _items
)
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](_items.length);
for (uint256 i = 0; i < _items.length; i++) {
raw[i] = Lib_RLPReader.readRawBytes(_items[i]);
}
return _makeNode(raw);
}
/**
* @notice Creates a new extension node.
* @param _key Key for the extension node, unprefixed.
* @param _value Value for the extension node.
* @return _node New extension node with the given k/v pair.
*/
function _makeExtensionNode(
bytes memory _key,
bytes memory _value
)
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_key, false);
raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));
raw[1] = Lib_RLPWriter.writeBytes(_value);
return _makeNode(raw);
}
/**
* Creates a new extension node with the same key but a different value.
* @param _node Extension node to copy and modify.
* @param _value New value for the extension node.
* @return New node with the same key and different value.
*/
function _editExtensionNodeValue(
TrieNode memory _node,
bytes memory _value
)
private
pure
returns (
TrieNode memory
)
{
bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_getNodeKey(_node), false);
raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));
if (_value.length < 32) {
raw[1] = _value;
} else {
raw[1] = Lib_RLPWriter.writeBytes(_value);
}
return _makeNode(raw);
}
/**
* @notice Creates a new leaf node.
* @dev This function is essentially identical to `_makeExtensionNode`.
* Although we could route both to a single method with a flag, it's
* more gas efficient to keep them separate and duplicate the logic.
* @param _key Key for the leaf node, unprefixed.
* @param _value Value for the leaf node.
* @return _node New leaf node with the given k/v pair.
*/
function _makeLeafNode(
bytes memory _key,
bytes memory _value
)
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](2);
bytes memory key = _addHexPrefix(_key, true);
raw[0] = Lib_RLPWriter.writeBytes(Lib_BytesUtils.fromNibbles(key));
raw[1] = Lib_RLPWriter.writeBytes(_value);
return _makeNode(raw);
}
/**
* @notice Creates an empty branch node.
* @return _node Empty branch node as a TrieNode struct.
*/
function _makeEmptyBranchNode()
private
pure
returns (
TrieNode memory _node
)
{
bytes[] memory raw = new bytes[](BRANCH_NODE_LENGTH);
for (uint256 i = 0; i < raw.length; i++) {
raw[i] = RLP_NULL_BYTES;
}
return _makeNode(raw);
}
/**
* @notice Modifies the value slot for a given branch.
* @param _branch Branch node to modify.
* @param _value Value to insert into the branch.
* @return _updatedNode Modified branch node.
*/
function _editBranchValue(
TrieNode memory _branch,
bytes memory _value
)
private
pure
returns (
TrieNode memory _updatedNode
)
{
bytes memory encoded = Lib_RLPWriter.writeBytes(_value);
_branch.decoded[_branch.decoded.length - 1] = Lib_RLPReader.toRLPItem(encoded);
return _makeNode(_branch.decoded);
}
/**
* @notice Modifies a slot at an index for a given branch.
* @param _branch Branch node to modify.
* @param _index Slot index to modify.
* @param _value Value to insert into the slot.
* @return _updatedNode Modified branch node.
*/
function _editBranchIndex(
TrieNode memory _branch,
uint8 _index,
bytes memory _value
)
private
pure
returns (
TrieNode memory _updatedNode
)
{
bytes memory encoded = _value.length < 32 ? _value : Lib_RLPWriter.writeBytes(_value);
_branch.decoded[_index] = Lib_RLPReader.toRLPItem(encoded);
return _makeNode(_branch.decoded);
}
/**
* @notice Utility; adds a prefix to a key.
* @param _key Key to prefix.
* @param _isLeaf Whether or not the key belongs to a leaf.
* @return _prefixedKey Prefixed key.
*/
function _addHexPrefix(
bytes memory _key,
bool _isLeaf
)
private
pure
returns (
bytes memory _prefixedKey
)
{
uint8 prefix = _isLeaf ? uint8(0x02) : uint8(0x00);
uint8 offset = uint8(_key.length % 2);
bytes memory prefixed = new bytes(2 - offset);
prefixed[0] = bytes1(prefix + offset);
return abi.encodePacked(prefixed, _key);
}
/**
* @notice Utility; removes a prefix from a path.
* @param _path Path to remove the prefix from.
* @return _unprefixedKey Unprefixed key.
*/
function _removeHexPrefix(
bytes memory _path
)
private
pure
returns (
bytes memory _unprefixedKey
)
{
if (uint8(_path[0]) % 2 == 0) {
return Lib_BytesUtils.slice(_path, 2);
} else {
return Lib_BytesUtils.slice(_path, 1);
}
}
/**
* @notice Utility; combines two node arrays. Array lengths are required
* because the actual lengths may be longer than the filled lengths.
* Array resizing is extremely costly and should be avoided.
* @param _a First array to join.
* @param _aLength Length of the first array.
* @param _b Second array to join.
* @param _bLength Length of the second array.
* @return _joined Combined node array.
*/
function _joinNodeArrays(
TrieNode[] memory _a,
uint256 _aLength,
TrieNode[] memory _b,
uint256 _bLength
)
private
pure
returns (
TrieNode[] memory _joined
)
{
TrieNode[] memory ret = new TrieNode[](_aLength + _bLength);
// Copy elements from the first array.
for (uint256 i = 0; i < _aLength; i++) {
ret[i] = _a[i];
}
// Copy elements from the second array.
for (uint256 i = 0; i < _bLength; i++) {
ret[i + _aLength] = _b[i];
}
return ret;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
/* Library Imports */
import { Lib_MerkleTrie } from "./Lib_MerkleTrie.sol";
/**
* @title Lib_SecureMerkleTrie
*/
library Lib_SecureMerkleTrie {
/**********************
* Internal Functions *
**********************/
/**
* @notice Verifies a proof that a given key/value pair is present in the
* Merkle trie.
* @param _key Key of the node to search for, as a hex string.
* @param _value Value of the node to search for, as a hex string.
* @param _proof Merkle trie inclusion proof for the desired node. Unlike
* traditional Merkle trees, this proof is executed top-down and consists
* of a list of RLP-encoded nodes that make a path down to the target node.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _verified `true` if the k/v pair exists in the trie, `false` otherwise.
*/
function verifyInclusionProof(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _verified
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.verifyInclusionProof(key, _value, _proof, _root);
}
/**
* @notice Updates a Merkle trie and returns a new root hash.
* @param _key Key of the node to update, as a hex string.
* @param _value Value of the node to update, as a hex string.
* @param _proof Merkle trie inclusion proof for the node *nearest* the
* target node. If the key exists, we can simply update the value.
* Otherwise, we need to modify the trie to handle the new k/v pair.
* @param _root Known root of the Merkle trie. Used to verify that the
* included proof is correctly constructed.
* @return _updatedRoot Root hash of the newly constructed trie.
*/
function update(
bytes memory _key,
bytes memory _value,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.update(key, _value, _proof, _root);
}
/**
* @notice Retrieves the value associated with a given key.
* @param _key Key to search for, as hex bytes.
* @param _proof Merkle trie inclusion proof for the key.
* @param _root Known root of the Merkle trie.
* @return _exists Whether or not the key exists.
* @return _value Value of the key if it exists.
*/
function get(
bytes memory _key,
bytes memory _proof,
bytes32 _root
)
internal
pure
returns (
bool _exists,
bytes memory _value
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.get(key, _proof, _root);
}
/**
* Computes the root hash for a trie with a single node.
* @param _key Key for the single node.
* @param _value Value for the single node.
* @return _updatedRoot Hash of the trie.
*/
function getSingleNodeRootHash(
bytes memory _key,
bytes memory _value
)
internal
pure
returns (
bytes32 _updatedRoot
)
{
bytes memory key = _getSecureKey(_key);
return Lib_MerkleTrie.getSingleNodeRootHash(key, _value);
}
/*********************
* Private Functions *
*********************/
/**
* Computes the secure counterpart to a key.
* @param _key Key to get a secure key from.
* @return _secureKey Secure version of the key.
*/
function _getSecureKey(
bytes memory _key
)
private
pure
returns (
bytes memory _secureKey
)
{
return abi.encodePacked(keccak256(_key));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_Byte32Utils
*/
library Lib_Bytes32Utils {
/**********************
* Internal Functions *
**********************/
/**
* Converts a bytes32 value to a boolean. Anything non-zero will be converted to "true."
* @param _in Input bytes32 value.
* @return Bytes32 as a boolean.
*/
function toBool(
bytes32 _in
)
internal
pure
returns (
bool
)
{
return _in != 0;
}
/**
* Converts a boolean to a bytes32 value.
* @param _in Input boolean value.
* @return Boolean as a bytes32.
*/
function fromBool(
bool _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in ? 1 : 0));
}
/**
* Converts a bytes32 value to an address. Takes the *last* 20 bytes.
* @param _in Input bytes32 value.
* @return Bytes32 as an address.
*/
function toAddress(
bytes32 _in
)
internal
pure
returns (
address
)
{
return address(uint160(uint256(_in)));
}
/**
* Converts an address to a bytes32.
* @param _in Input address value.
* @return Address as a bytes32.
*/
function fromAddress(
address _in
)
internal
pure
returns (
bytes32
)
{
return bytes32(uint256(_in));
}
/**
* Removes the leading zeros from a bytes32 value and returns a new (smaller) bytes value.
* @param _in Input bytes32 value.
* @return Bytes32 without any leading zeros.
*/
function removeLeadingZeros(
bytes32 _in
)
internal
pure
returns (
bytes memory
)
{
bytes memory out;
assembly {
// Figure out how many leading zero bytes to remove.
let shift := 0
for { let i := 0 } and(lt(i, 32), eq(byte(i, _in), 0)) { i := add(i, 1) } {
shift := add(shift, 1)
}
// Reserve some space for our output and fix the free memory pointer.
out := mload(0x40)
mstore(0x40, add(out, 0x40))
// Shift the value and store it into the output bytes.
mstore(add(out, 0x20), shl(mul(shift, 8), _in))
// Store the new size (with leading zero bytes removed) in the output byte size.
mstore(out, sub(32, shift))
}
return out;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.5.0 <0.8.0;
/**
* @title Lib_BytesUtils
*/
library Lib_BytesUtils {
/**********************
* Internal Functions *
**********************/
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
)
internal
pure
returns (
bytes memory
)
{
require(_length + 31 >= _length, "slice_overflow");
require(_start + _length >= _start, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
//zero out the 32 bytes slice we are about to return
//we need to do it because Solidity does not garbage collect
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function slice(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
bytes memory
)
{
if (_start >= _bytes.length) {
return bytes('');
}
return slice(_bytes, _start, _bytes.length - _start);
}
function toBytes32PadLeft(
bytes memory _bytes
)
internal
pure
returns (
bytes32
)
{
bytes32 ret;
uint256 len = _bytes.length <= 32 ? _bytes.length : 32;
assembly {
ret := shr(mul(sub(32, len), 8), mload(add(_bytes, 32)))
}
return ret;
}
function toBytes32(
bytes memory _bytes
)
internal
pure
returns (
bytes32
)
{
if (_bytes.length < 32) {
bytes32 ret;
assembly {
ret := mload(add(_bytes, 32))
}
return ret;
}
return abi.decode(_bytes,(bytes32)); // will truncate if input length > 32 bytes
}
function toUint256(
bytes memory _bytes
)
internal
pure
returns (
uint256
)
{
return uint256(toBytes32(_bytes));
}
function toUint24(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
uint24
)
{
require(_start + 3 >= _start, "toUint24_overflow");
require(_bytes.length >= _start + 3 , "toUint24_outOfBounds");
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint8(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
uint8
)
{
require(_start + 1 >= _start, "toUint8_overflow");
require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toAddress(
bytes memory _bytes,
uint256 _start
)
internal
pure
returns (
address
)
{
require(_start + 20 >= _start, "toAddress_overflow");
require(_bytes.length >= _start + 20, "toAddress_outOfBounds");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toNibbles(
bytes memory _bytes
)
internal
pure
returns (
bytes memory
)
{
bytes memory nibbles = new bytes(_bytes.length * 2);
for (uint256 i = 0; i < _bytes.length; i++) {
nibbles[i * 2] = _bytes[i] >> 4;
nibbles[i * 2 + 1] = bytes1(uint8(_bytes[i]) % 16);
}
return nibbles;
}
function fromNibbles(
bytes memory _bytes
)
internal
pure
returns (
bytes memory
)
{
bytes memory ret = new bytes(_bytes.length / 2);
for (uint256 i = 0; i < ret.length; i++) {
ret[i] = (_bytes[i * 2] << 4) | (_bytes[i * 2 + 1]);
}
return ret;
}
function equal(
bytes memory _bytes,
bytes memory _other
)
internal
pure
returns (
bool
)
{
return keccak256(_bytes) == keccak256(_other);
}
}
| Generates the correct cross domain calldata for a message. _target Target contract address. _sender Message sender address. _message Message to send to the target. _messageNonce Nonce for the provided message. return ABI encoded cross domain calldata./ | function batches()
external
view
returns (
iOVM_ChainStorageContainer
);
function queue()
external
view
returns (
iOVM_ChainStorageContainer
);
function getTotalElements()
external
view
returns (
uint256 _totalElements
);
function getTotalBatches()
external
view
returns (
uint256 _totalBatches
);
function getNextQueueIndex()
external
view
returns (
uint40
);
function getQueueElement(
uint256 _index
)
external
view
returns (
Lib_OVMCodec.QueueElement memory _element
);
function getLastTimestamp()
external
view
returns (
uint40
);
function getLastBlockNumber()
external
view
returns (
uint40
);
function getNumPendingQueueElements()
external
view
returns (
uint40
);
function getQueueLength()
external
view
returns (
uint40
);
function enqueue(
address _target,
uint256 _gasLimit,
bytes memory _data
)
external;
function appendQueueBatch(
uint256 _numQueuedTransactions
)
external;
function appendSequencerBatch(
)
external;
function verifyTransaction(
Lib_OVMCodec.Transaction memory _transaction,
Lib_OVMCodec.TransactionChainElement memory _txChainElement,
Lib_OVMCodec.ChainBatchHeader memory _batchHeader,
Lib_OVMCodec.ChainInclusionProof memory _inclusionProof
)
external
view
returns (
bool
);
}
pragma solidity >0.5.0 <0.8.0;
}
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
}
pragma solidity >0.5.0 <0.8.0;
pragma experimental ABIEncoderV2;
{
return abi.encodeWithSignature(
"relayMessage(address,address,bytes,uint256)",
_target,
_sender,
_message,
_messageNonce
);
}
| 5,909,510 |
./full_match/1/0x2B81d60dc40f6Ca230be5Abf5641D4c2E38dba01/sources/src/vaults/VaultGovernance.sol | Set Delayed Protocol Params params New params | function _stageDelayedProtocolParams(bytes memory params) internal {
_requireProtocolAdmin();
uint256 delayFactor = _delayedProtocolParams.length == 0 ? 0 : 1;
_stagedDelayedProtocolParams = params;
_delayedProtocolParamsTimestamp =
block.timestamp +
_internalParams.protocolGovernance.governanceDelay() *
delayFactor;
}
| 8,327,319 |
./full_match/1/0x59B7E328F655B82E617E20446B393be472E8cBa5/sources/browser/MoneyPrinter.sol | This is the function that will be called postLoan i.e. Encode the logic to handle your flashloaned funds here | function callFunction(
address sender,
Account.Info memory account,
bytes memory data
) external override {
(address tokenIn, uint amountIn, address[] memory path) = abi.decode(data, (address, uint256, address[]));
IERC20(tokenIn).approve(uni_addr, amountIn);
uni.swapExactTokensForTokens(amountIn, amountIn, path, address(this), block.timestamp + 5 minutes);
uint256 repayAmount = amountIn + 2;
uint256 balance = IERC20(tokenIn).balanceOf(address(this));
require(
IERC20(tokenIn).balanceOf(address(this)) >= repayAmount,
"Not enough funds to repay dydx loan!"
);
uint profit = IERC20(tokenIn).balanceOf(address(this)) - repayAmount;
IERC20(tokenIn).transfer(owner, profit);
}
| 17,040,700 |
./full_match/1/0x363E9489a4ccE10Ee3F86Bc049E08290D1731957/sources/contracts/oz/access/Ownable.sol | Throws if the sender is not the owner./ | function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OnlyOwner();
}
}
| 8,341,061 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/IFeeDistributor.sol";
import "../interfaces/ILiquidityGauge.sol";
import "../interfaces/ISanToken.sol";
import "../interfaces/IStableMaster.sol";
import "../interfaces/IStableMasterFront.sol";
import "../interfaces/IVeANGLE.sol";
import "../interfaces/external/IWETH9.sol";
import "../interfaces/external/uniswap/IUniswapRouter.sol";
/// @title Angle Router
/// @author Angle Core Team
/// @notice The `AngleRouter` contract facilitates interactions for users with the protocol. It was built to reduce the number
/// of approvals required to users and the number of transactions needed to perform some complex actions: like deposit and stake
/// in just one transaction
/// @dev Interfaces were designed for both advanced users which know the addresses of the protocol's contract, but most of the time
/// users which only know addresses of the stablecoins and collateral types of the protocol can perform the actions they want without
/// needing to understand what's happening under the hood
contract AngleRouter is Initializable, ReentrancyGuardUpgradeable {
using SafeERC20 for IERC20;
/// @notice Base used for params
uint256 public constant BASE_PARAMS = 10**9;
/// @notice Base used for params
uint256 private constant _MAX_TOKENS = 10;
// @notice Wrapped ETH contract
IWETH9 public constant WETH9 = IWETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
// @notice ANGLE contract
IERC20 public constant ANGLE = IERC20(0x31429d1856aD1377A8A0079410B297e1a9e214c2);
// @notice veANGLE contract
IVeANGLE public constant VEANGLE = IVeANGLE(0x0C462Dbb9EC8cD1630f1728B2CFD2769d09f0dd5);
// =========================== Structs and Enums ===============================
/// @notice Action types
enum ActionType {
claimRewards,
claimWeeklyInterest,
gaugeDeposit,
withdraw,
mint,
deposit,
openPerpetual,
addToPerpetual,
veANGLEDeposit
}
/// @notice All possible swaps
enum SwapType {
UniswapV3,
oneINCH
}
/// @notice Params for swaps
/// @param inToken Token to swap
/// @param collateral Token to swap for
/// @param amountIn Amount of token to sell
/// @param minAmountOut Minimum amount of collateral to receive for the swap to not revert
/// @param args Either the path for Uniswap or the payload for 1Inch
/// @param swapType Which swap route to take
struct ParamsSwapType {
IERC20 inToken;
address collateral;
uint256 amountIn;
uint256 minAmountOut;
bytes args;
SwapType swapType;
}
/// @notice Params for direct collateral transfer
/// @param inToken Token to transfer
/// @param amountIn Amount of token transfer
struct TransferType {
IERC20 inToken;
uint256 amountIn;
}
/// @notice References to the contracts associated to a collateral for a stablecoin
struct Pairs {
IPoolManager poolManager;
IPerpetualManagerFrontWithClaim perpetualManager;
ISanToken sanToken;
ILiquidityGauge gauge;
}
/// @notice Data needed to get permits
struct PermitType {
address token;
address owner;
uint256 value;
uint256 deadline;
uint8 v;
bytes32 r;
bytes32 s;
}
// =============================== Events ======================================
event AdminChanged(address indexed admin, bool setGovernor);
event StablecoinAdded(address indexed stableMaster);
event StablecoinRemoved(address indexed stableMaster);
event CollateralToggled(address indexed stableMaster, address indexed poolManager, address indexed liquidityGauge);
event SanTokenLiquidityGaugeUpdated(address indexed sanToken, address indexed newLiquidityGauge);
event Recovered(address indexed tokenAddress, address indexed to, uint256 amount);
// =============================== Mappings ====================================
/// @notice Maps an agToken to its counterpart `StableMaster`
mapping(IERC20 => IStableMasterFront) public mapStableMasters;
/// @notice Maps a `StableMaster` to a mapping of collateral token to its counterpart `PoolManager`
mapping(IStableMasterFront => mapping(IERC20 => Pairs)) public mapPoolManagers;
/// @notice Whether the token was already approved on Uniswap router
mapping(IERC20 => bool) public uniAllowedToken;
/// @notice Whether the token was already approved on 1Inch
mapping(IERC20 => bool) public oneInchAllowedToken;
// =============================== References ==================================
/// @notice Governor address
address public governor;
/// @notice Guardian address
address public guardian;
/// @notice Address of the router used for swaps
IUniswapV3Router public uniswapV3Router;
/// @notice Address of 1Inch router used for swaps
address public oneInch;
uint256[50] private __gap;
constructor() initializer {}
/// @notice Deploys the `AngleRouter` contract
/// @param _governor Governor address
/// @param _guardian Guardian address
/// @param _uniswapV3Router UniswapV3 router address
/// @param _oneInch 1Inch aggregator address
/// @param existingStableMaster Address of the existing `StableMaster`
/// @param existingPoolManagers Addresses of the associated poolManagers
/// @param existingLiquidityGauges Addresses of liquidity gauge contracts associated to sanTokens
/// @dev Be cautious with safe approvals, all tokens will have unlimited approvals within the protocol or
/// UniswapV3 and 1Inch
function initialize(
address _governor,
address _guardian,
IUniswapV3Router _uniswapV3Router,
address _oneInch,
IStableMasterFront existingStableMaster,
IPoolManager[] calldata existingPoolManagers,
ILiquidityGauge[] calldata existingLiquidityGauges
) public initializer {
// Checking the parameters passed
require(
address(_uniswapV3Router) != address(0) &&
_oneInch != address(0) &&
_governor != address(0) &&
_guardian != address(0),
"0"
);
require(_governor != _guardian, "49");
require(existingPoolManagers.length == existingLiquidityGauges.length, "104");
// Fetching the stablecoin and mapping it to the `StableMaster`
mapStableMasters[
IERC20(address(IStableMaster(address(existingStableMaster)).agToken()))
] = existingStableMaster;
// Setting roles
governor = _governor;
guardian = _guardian;
uniswapV3Router = _uniswapV3Router;
oneInch = _oneInch;
// for veANGLEDeposit action
ANGLE.safeApprove(address(VEANGLE), type(uint256).max);
for (uint256 i = 0; i < existingPoolManagers.length; i++) {
_addPair(existingStableMaster, existingPoolManagers[i], existingLiquidityGauges[i]);
}
}
// ============================== Modifiers ====================================
/// @notice Checks to see if it is the `governor` or `guardian` calling this contract
/// @dev There is no Access Control here, because it can be handled cheaply through this modifier
/// @dev In this contract, the `governor` and the `guardian` address have exactly similar rights
modifier onlyGovernorOrGuardian() {
require(msg.sender == governor || msg.sender == guardian, "115");
_;
}
// =========================== Governance utilities ============================
/// @notice Changes the guardian or the governor address
/// @param admin New guardian or guardian address
/// @param setGovernor Whether to set Governor if true, or Guardian if false
/// @dev There can only be one guardian and one governor address in the router
/// and both need to be different
function setGovernorOrGuardian(address admin, bool setGovernor) external onlyGovernorOrGuardian {
require(admin != address(0), "0");
require(guardian != admin && governor != admin, "49");
if (setGovernor) governor = admin;
else guardian = admin;
emit AdminChanged(admin, setGovernor);
}
/// @notice Adds a new `StableMaster`
/// @param stablecoin Address of the new stablecoin
/// @param stableMaster Address of the new `StableMaster`
function addStableMaster(IERC20 stablecoin, IStableMasterFront stableMaster) external onlyGovernorOrGuardian {
// No need to check if the `stableMaster` address is a zero address as otherwise the call to `stableMaster.agToken()`
// would revert
require(address(stablecoin) != address(0), "0");
require(address(mapStableMasters[stablecoin]) == address(0), "114");
require(stableMaster.agToken() == address(stablecoin), "20");
mapStableMasters[stablecoin] = stableMaster;
emit StablecoinAdded(address(stableMaster));
}
/// @notice Removes a `StableMaster`
/// @param stablecoin Address of the associated stablecoin
/// @dev Before calling this function, governor or guardian should remove first all pairs
/// from the `mapPoolManagers[stableMaster]`. It is assumed that the governor or guardian calling this function
/// will act correctly here, it indeed avoids storing a list of all pairs for each `StableMaster`
function removeStableMaster(IERC20 stablecoin) external onlyGovernorOrGuardian {
IStableMasterFront stableMaster = mapStableMasters[stablecoin];
delete mapStableMasters[stablecoin];
emit StablecoinRemoved(address(stableMaster));
}
/// @notice Adds new collateral types to specific stablecoins
/// @param stablecoins Addresses of the stablecoins associated to the `StableMaster` of interest
/// @param poolManagers Addresses of the `PoolManager` contracts associated to the pair (stablecoin,collateral)
/// @param liquidityGauges Addresses of liquidity gauges contract associated to sanToken
function addPairs(
IERC20[] calldata stablecoins,
IPoolManager[] calldata poolManagers,
ILiquidityGauge[] calldata liquidityGauges
) external onlyGovernorOrGuardian {
require(poolManagers.length == stablecoins.length && liquidityGauges.length == stablecoins.length, "104");
for (uint256 i = 0; i < stablecoins.length; i++) {
IStableMasterFront stableMaster = mapStableMasters[stablecoins[i]];
_addPair(stableMaster, poolManagers[i], liquidityGauges[i]);
}
}
/// @notice Removes collateral types from specific `StableMaster` contracts using the address
/// of the associated stablecoins
/// @param stablecoins Addresses of the stablecoins
/// @param collaterals Addresses of the collaterals
/// @param stableMasters List of the associated `StableMaster` contracts
/// @dev In the lists, if a `stableMaster` address is null in `stableMasters` then this means that the associated
/// `stablecoins` address (at the same index) should be non null
function removePairs(
IERC20[] calldata stablecoins,
IERC20[] calldata collaterals,
IStableMasterFront[] calldata stableMasters
) external onlyGovernorOrGuardian {
require(collaterals.length == stablecoins.length && stableMasters.length == collaterals.length, "104");
Pairs memory pairs;
IStableMasterFront stableMaster;
for (uint256 i = 0; i < stablecoins.length; i++) {
if (address(stableMasters[i]) == address(0))
// In this case `collaterals[i]` is a collateral address
(stableMaster, pairs) = _getInternalContracts(stablecoins[i], collaterals[i]);
else {
// In this case `collaterals[i]` is a `PoolManager` address
stableMaster = stableMasters[i];
pairs = mapPoolManagers[stableMaster][collaterals[i]];
}
delete mapPoolManagers[stableMaster][collaterals[i]];
_changeAllowance(collaterals[i], address(stableMaster), 0);
_changeAllowance(collaterals[i], address(pairs.perpetualManager), 0);
if (address(pairs.gauge) != address(0)) pairs.sanToken.approve(address(pairs.gauge), 0);
emit CollateralToggled(address(stableMaster), address(pairs.poolManager), address(pairs.gauge));
}
}
/// @notice Sets new `liquidityGauge` contract for the associated sanTokens
/// @param stablecoins Addresses of the stablecoins
/// @param collaterals Addresses of the collaterals
/// @param newLiquidityGauges Addresses of the new liquidity gauges contract
/// @dev If `newLiquidityGauge` is null, this means that there is no liquidity gauge for this pair
/// @dev This function could be used to simply revoke the approval to a liquidity gauge
function setLiquidityGauges(
IERC20[] calldata stablecoins,
IERC20[] calldata collaterals,
ILiquidityGauge[] calldata newLiquidityGauges
) external onlyGovernorOrGuardian {
require(collaterals.length == stablecoins.length && newLiquidityGauges.length == stablecoins.length, "104");
for (uint256 i = 0; i < stablecoins.length; i++) {
IStableMasterFront stableMaster = mapStableMasters[stablecoins[i]];
Pairs storage pairs = mapPoolManagers[stableMaster][collaterals[i]];
ILiquidityGauge gauge = pairs.gauge;
ISanToken sanToken = pairs.sanToken;
require(address(stableMaster) != address(0) && address(pairs.poolManager) != address(0), "0");
pairs.gauge = newLiquidityGauges[i];
if (address(gauge) != address(0)) {
sanToken.approve(address(gauge), 0);
}
if (address(newLiquidityGauges[i]) != address(0)) {
// Checking compatibility of the staking token: it should be the sanToken
require(address(newLiquidityGauges[i].staking_token()) == address(sanToken), "20");
sanToken.approve(address(newLiquidityGauges[i]), type(uint256).max);
}
emit SanTokenLiquidityGaugeUpdated(address(sanToken), address(newLiquidityGauges[i]));
}
}
/// @notice Change allowance for a contract.
/// @param tokens Addresses of the tokens to allow
/// @param spenders Addresses to allow transfer
/// @param amounts Amounts to allow
/// @dev Approvals are normally given in the `addGauges` method, in the initializer and in
/// the internal functions to process swaps with Uniswap and 1Inch
function changeAllowance(
IERC20[] calldata tokens,
address[] calldata spenders,
uint256[] calldata amounts
) external onlyGovernorOrGuardian {
require(tokens.length == spenders.length && tokens.length == amounts.length, "104");
for (uint256 i = 0; i < tokens.length; i++) {
_changeAllowance(tokens[i], spenders[i], amounts[i]);
}
}
/// @notice Supports recovering any tokens as the router does not own any other tokens than
/// the one mistakenly sent
/// @param tokenAddress Address of the token to transfer
/// @param to Address to give tokens to
/// @param tokenAmount Amount of tokens to transfer
/// @dev If tokens are mistakenly sent to this contract, any address can take advantage of the `mixer` function
/// below to get the funds back
function recoverERC20(
address tokenAddress,
address to,
uint256 tokenAmount
) external onlyGovernorOrGuardian {
IERC20(tokenAddress).safeTransfer(to, tokenAmount);
emit Recovered(tokenAddress, to, tokenAmount);
}
// =========================== Router Functionalities =========================
/// @notice Wrapper n°1 built on top of the _claimRewards function
/// Allows to claim rewards for multiple gauges and perpetuals at once
/// @param gaugeUser Address for which to fetch the rewards from the gauges
/// @param liquidityGauges Gauges to claim on
/// @param perpetualIDs Perpetual IDs to claim rewards for
/// @param stablecoins Stablecoin contracts linked to the perpetualsIDs
/// @param collaterals Collateral contracts linked to the perpetualsIDs or `perpetualManager`
/// @dev If the caller wants to send the rewards to another account it first needs to
/// call `set_rewards_receiver(otherAccount)` on each `liquidityGauge`
function claimRewards(
address gaugeUser,
address[] memory liquidityGauges,
uint256[] memory perpetualIDs,
address[] memory stablecoins,
address[] memory collaterals
) external nonReentrant {
_claimRewards(gaugeUser, liquidityGauges, perpetualIDs, false, stablecoins, collaterals);
}
/// @notice Wrapper n°2 (a little more gas efficient than n°1) built on top of the _claimRewards function
/// Allows to claim rewards for multiple gauges and perpetuals at once
/// @param user Address to which the contract should send the rewards from gauges (not perpetuals)
/// @param liquidityGauges Contracts to claim for
/// @param perpetualIDs Perpetual IDs to claim rewards for
/// @param perpetualManagers `perpetualManager` contracts for every perp to claim
/// @dev If the caller wants to send the rewards to another account it first needs to
/// call `set_rewards_receiver(otherAccount)` on each `liquidityGauge`
function claimRewards(
address user,
address[] memory liquidityGauges,
uint256[] memory perpetualIDs,
address[] memory perpetualManagers
) external nonReentrant {
_claimRewards(user, liquidityGauges, perpetualIDs, true, new address[](perpetualIDs.length), perpetualManagers);
}
/// @notice Wrapper built on top of the `_gaugeDeposit` method to deposit collateral in a gauge
/// @param token On top of the parameters of the internal function, users need to specify the token associated
/// to the gauge they want to deposit in
/// @dev The function will revert if the token does not correspond to the gauge
function gaugeDeposit(
address user,
uint256 amount,
ILiquidityGauge gauge,
bool shouldClaimRewards,
IERC20 token
) external nonReentrant {
token.safeTransferFrom(msg.sender, address(this), amount);
_gaugeDeposit(user, amount, gauge, shouldClaimRewards);
}
/// @notice Wrapper n°1 built on top of the `_mint` method to mint stablecoins
/// @param user Address to send the stablecoins to
/// @param amount Amount of collateral to use for the mint
/// @param minStableAmount Minimum stablecoin minted for the tx not to revert
/// @param stablecoin Address of the stablecoin to mint
/// @param collateral Collateral to mint from
function mint(
address user,
uint256 amount,
uint256 minStableAmount,
address stablecoin,
address collateral
) external nonReentrant {
IERC20(collateral).safeTransferFrom(msg.sender, address(this), amount);
_mint(user, amount, minStableAmount, false, stablecoin, collateral, IPoolManager(address(0)));
}
/// @notice Wrapper n°2 (a little more gas efficient than n°1) built on top of the `_mint` method to mint stablecoins
/// @param user Address to send the stablecoins to
/// @param amount Amount of collateral to use for the mint
/// @param minStableAmount Minimum stablecoin minted for the tx not to revert
/// @param stableMaster Address of the stableMaster managing the stablecoin to mint
/// @param collateral Collateral to mint from
/// @param poolManager PoolManager associated to the `collateral`
function mint(
address user,
uint256 amount,
uint256 minStableAmount,
address stableMaster,
address collateral,
address poolManager
) external nonReentrant {
IERC20(collateral).safeTransferFrom(msg.sender, address(this), amount);
_mint(user, amount, minStableAmount, true, stableMaster, collateral, IPoolManager(poolManager));
}
/// @notice Wrapper built on top of the `_burn` method to burn stablecoins
/// @param dest Address to send the collateral to
/// @param amount Amount of stablecoins to use for the burn
/// @param minCollatAmount Minimum collateral amount received for the tx not to revert
/// @param stablecoin Address of the stablecoin to mint
/// @param collateral Collateral to mint from
function burn(
address dest,
uint256 amount,
uint256 minCollatAmount,
address stablecoin,
address collateral
) external nonReentrant {
_burn(dest, amount, minCollatAmount, false, stablecoin, collateral, IPoolManager(address(0)));
}
/// @notice Wrapper n°1 built on top of the `_deposit` method to deposit collateral as a SLP in the protocol
/// Allows to deposit a collateral within the protocol
/// @param user Address where to send the resulting sanTokens, if this address is the router address then it means
/// that the intention is to stake the sanTokens obtained in a subsequent `gaugeDeposit` action
/// @param amount Amount of collateral to deposit
/// @param stablecoin `StableMaster` associated to the sanToken
/// @param collateral Token to deposit
/// @dev Contrary to the `mint` action, the `deposit` action can be used in composition with other actions, like
/// `deposit` and then `stake
function deposit(
address user,
uint256 amount,
address stablecoin,
address collateral
) external nonReentrant {
IERC20(collateral).safeTransferFrom(msg.sender, address(this), amount);
_deposit(user, amount, false, stablecoin, collateral, IPoolManager(address(0)), ISanToken(address(0)));
}
/// @notice Wrapper n°2 (a little more gas efficient than n°1) built on top of the `_deposit` method to deposit collateral as a SLP in the protocol
/// Allows to deposit a collateral within the protocol
/// @param user Address where to send the resulting sanTokens, if this address is the router address then it means
/// that the intention is to stake the sanTokens obtained in a subsequent `gaugeDeposit` action
/// @param amount Amount of collateral to deposit
/// @param stableMaster `StableMaster` associated to the sanToken
/// @param collateral Token to deposit
/// @param poolManager PoolManager associated to the sanToken
/// @param sanToken SanToken associated to the `collateral` and `stableMaster`
/// @dev Contrary to the `mint` action, the `deposit` action can be used in composition with other actions, like
/// `deposit` and then `stake`
function deposit(
address user,
uint256 amount,
address stableMaster,
address collateral,
IPoolManager poolManager,
ISanToken sanToken
) external nonReentrant {
IERC20(collateral).safeTransferFrom(msg.sender, address(this), amount);
_deposit(user, amount, true, stableMaster, collateral, poolManager, sanToken);
}
/// @notice Wrapper built on top of the `_openPerpetual` method to open a perpetual with the protocol
/// @param collateral Here the collateral should not be null (even if `addressProcessed` is true) for the router
/// to be able to know how to deposit collateral
/// @dev `stablecoinOrPerpetualManager` should be the address of the agToken (= stablecoin) is `addressProcessed` is false
/// and the associated `perpetualManager` otherwise
function openPerpetual(
address owner,
uint256 margin,
uint256 amountCommitted,
uint256 maxOracleRate,
uint256 minNetMargin,
bool addressProcessed,
address stablecoinOrPerpetualManager,
address collateral
) external nonReentrant {
IERC20(collateral).safeTransferFrom(msg.sender, address(this), margin);
_openPerpetual(
owner,
margin,
amountCommitted,
maxOracleRate,
minNetMargin,
addressProcessed,
stablecoinOrPerpetualManager,
collateral
);
}
/// @notice Wrapper built on top of the `_addToPerpetual` method to add collateral to a perpetual with the protocol
/// @param collateral Here the collateral should not be null (even if `addressProcessed is true) for the router
/// to be able to know how to deposit collateral
/// @dev `stablecoinOrPerpetualManager` should be the address of the agToken is `addressProcessed` is false and the associated
/// `perpetualManager` otherwise
function addToPerpetual(
uint256 margin,
uint256 perpetualID,
bool addressProcessed,
address stablecoinOrPerpetualManager,
address collateral
) external nonReentrant {
IERC20(collateral).safeTransferFrom(msg.sender, address(this), margin);
_addToPerpetual(margin, perpetualID, addressProcessed, stablecoinOrPerpetualManager, collateral);
}
/// @notice Allows composable calls to different functions within the protocol
/// @param paramsPermit Array of params `PermitType` used to do a 1 tx to approve the router on each token (can be done once by
/// setting high approved amounts) which supports the `permit` standard. Users willing to interact with the contract
/// with tokens that do not support permit should approve the contract for these tokens prior to interacting with it
/// @param paramsTransfer Array of params `TransferType` used to transfer tokens to the router
/// @param paramsSwap Array of params `ParamsSwapType` used to swap tokens
/// @param actions List of actions to be performed by the router (in order of execution): make sure to read for each action the
/// associated internal function
/// @param datas Array of encoded data for each of the actions performed in this mixer. This is where the bytes-encoded parameters
/// for a given action are stored
/// @dev This function first fills the router balances via transfers and swaps. It then proceeds with each
/// action in the order at which they are given
/// @dev With this function, users can specify paths to swap tokens to the desired token of their choice. Yet the protocol
/// does not verify the payload given and cannot check that the swap performed by users actually gives the desired
/// out token: in this case funds will be lost by the user
/// @dev For some actions (`mint`, `deposit`, `openPerpetual`, `addToPerpetual`, `withdraw`), users are
/// required to give a proportion of the amount of token they have brought to the router within the transaction (through
/// a direct transfer or a swap) they want to use for the operation. If you want to use all the USDC you have brought (through an ETH -> USDC)
/// swap to mint stablecoins for instance, you should use `BASE_PARAMS` as a proportion.
/// @dev The proportion that is specified for an action is a proportion of what is left. If you want to use 50% of your USDC for a `mint`
/// and the rest for an `openPerpetual`, proportion used for the `mint` should be 50% (that is `BASE_PARAMS/2`), and proportion
/// for the `openPerpetual` should be all that is left that is 100% (= `BASE_PARAMS`).
/// @dev For each action here, make sure to read the documentation of the associated internal function to know how to correctly
/// specify parameters
function mixer(
PermitType[] memory paramsPermit,
TransferType[] memory paramsTransfer,
ParamsSwapType[] memory paramsSwap,
ActionType[] memory actions,
bytes[] calldata datas
) external payable nonReentrant {
// Do all the permits once for all: if all tokens have already been approved, there's no need for this step
for (uint256 i = 0; i < paramsPermit.length; i++) {
IERC20PermitUpgradeable(paramsPermit[i].token).permit(
paramsPermit[i].owner,
address(this),
paramsPermit[i].value,
paramsPermit[i].deadline,
paramsPermit[i].v,
paramsPermit[i].r,
paramsPermit[i].s
);
}
// Then, do all the transfer to load all needed funds into the router
// This function is limited to 10 different assets to be spent on the protocol (agTokens, collaterals, sanTokens)
address[_MAX_TOKENS] memory listTokens;
uint256[_MAX_TOKENS] memory balanceTokens;
for (uint256 i = 0; i < paramsTransfer.length; i++) {
paramsTransfer[i].inToken.safeTransferFrom(msg.sender, address(this), paramsTransfer[i].amountIn);
_addToList(listTokens, balanceTokens, address(paramsTransfer[i].inToken), paramsTransfer[i].amountIn);
}
for (uint256 i = 0; i < paramsSwap.length; i++) {
// Caution here: if the args are not set such that end token is the params `paramsSwap[i].collateral`,
// then the funds will be lost, and any user could take advantage of it to fetch the funds
uint256 amountOut = _transferAndSwap(
paramsSwap[i].inToken,
paramsSwap[i].amountIn,
paramsSwap[i].minAmountOut,
paramsSwap[i].swapType,
paramsSwap[i].args
);
_addToList(listTokens, balanceTokens, address(paramsSwap[i].collateral), amountOut);
}
// Performing actions one after the others
for (uint256 i = 0; i < actions.length; i++) {
if (actions[i] == ActionType.claimRewards) {
(
address user,
uint256 proportionToBeTransferred,
address[] memory claimLiquidityGauges,
uint256[] memory claimPerpetualIDs,
bool addressProcessed,
address[] memory stablecoins,
address[] memory collateralsOrPerpetualManagers
) = abi.decode(datas[i], (address, uint256, address[], uint256[], bool, address[], address[]));
uint256 amount = ANGLE.balanceOf(user);
_claimRewards(
user,
claimLiquidityGauges,
claimPerpetualIDs,
addressProcessed,
stablecoins,
collateralsOrPerpetualManagers
);
if (proportionToBeTransferred > 0) {
amount = ANGLE.balanceOf(user) - amount;
amount = (amount * proportionToBeTransferred) / BASE_PARAMS;
ANGLE.safeTransferFrom(msg.sender, address(this), amount);
_addToList(listTokens, balanceTokens, address(ANGLE), amount);
}
} else if (actions[i] == ActionType.claimWeeklyInterest) {
(address user, address feeDistributor, bool letInContract) = abi.decode(
datas[i],
(address, address, bool)
);
(uint256 amount, IERC20 token) = _claimWeeklyInterest(
user,
IFeeDistributorFront(feeDistributor),
letInContract
);
if (address(token) != address(0)) _addToList(listTokens, balanceTokens, address(token), amount);
// In all the following action, the `amount` variable represents the proportion of the
// balance that needs to be used for this action (in `BASE_PARAMS`)
// We name it `amount` here to save some new variable declaration costs
} else if (actions[i] == ActionType.veANGLEDeposit) {
(address user, uint256 amount) = abi.decode(datas[i], (address, uint256));
amount = _computeProportion(amount, listTokens, balanceTokens, address(ANGLE));
_depositOnLocker(user, amount);
} else if (actions[i] == ActionType.gaugeDeposit) {
(address user, uint256 amount, address stakedToken, address gauge, bool shouldClaimRewards) = abi
.decode(datas[i], (address, uint256, address, address, bool));
amount = _computeProportion(amount, listTokens, balanceTokens, stakedToken);
_gaugeDeposit(user, amount, ILiquidityGauge(gauge), shouldClaimRewards);
} else if (actions[i] == ActionType.deposit) {
(
address user,
uint256 amount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateral,
address poolManager,
address sanToken
) = abi.decode(datas[i], (address, uint256, bool, address, address, address, address));
amount = _computeProportion(amount, listTokens, balanceTokens, collateral);
(amount, sanToken) = _deposit(
user,
amount,
addressProcessed,
stablecoinOrStableMaster,
collateral,
IPoolManager(poolManager),
ISanToken(sanToken)
);
if (amount > 0) _addToList(listTokens, balanceTokens, sanToken, amount);
} else if (actions[i] == ActionType.withdraw) {
(
uint256 amount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateralOrPoolManager,
address sanToken
) = abi.decode(datas[i], (uint256, bool, address, address, address));
amount = _computeProportion(amount, listTokens, balanceTokens, sanToken);
// Reusing the `collateralOrPoolManager` variable to save some variable declarations
(amount, collateralOrPoolManager) = _withdraw(
amount,
addressProcessed,
stablecoinOrStableMaster,
collateralOrPoolManager
);
_addToList(listTokens, balanceTokens, collateralOrPoolManager, amount);
} else if (actions[i] == ActionType.mint) {
(
address user,
uint256 amount,
uint256 minStableAmount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateral,
address poolManager
) = abi.decode(datas[i], (address, uint256, uint256, bool, address, address, address));
amount = _computeProportion(amount, listTokens, balanceTokens, collateral);
_mint(
user,
amount,
minStableAmount,
addressProcessed,
stablecoinOrStableMaster,
collateral,
IPoolManager(poolManager)
);
} else if (actions[i] == ActionType.openPerpetual) {
(
address user,
uint256 amount,
uint256 amountCommitted,
uint256 extremeRateOracle,
uint256 minNetMargin,
bool addressProcessed,
address stablecoinOrPerpetualManager,
address collateral
) = abi.decode(datas[i], (address, uint256, uint256, uint256, uint256, bool, address, address));
amount = _computeProportion(amount, listTokens, balanceTokens, collateral);
_openPerpetual(
user,
amount,
amountCommitted,
extremeRateOracle,
minNetMargin,
addressProcessed,
stablecoinOrPerpetualManager,
collateral
);
} else if (actions[i] == ActionType.addToPerpetual) {
(
uint256 amount,
uint256 perpetualID,
bool addressProcessed,
address stablecoinOrPerpetualManager,
address collateral
) = abi.decode(datas[i], (uint256, uint256, bool, address, address));
amount = _computeProportion(amount, listTokens, balanceTokens, collateral);
_addToPerpetual(amount, perpetualID, addressProcessed, stablecoinOrPerpetualManager, collateral);
}
}
// Once all actions have been performed, the router sends back the unused funds from users
// If a user sends funds (through a swap) but specifies incorrectly the collateral associated to it, then the mixer will revert
// When trying to send remaining funds back
for (uint256 i = 0; i < balanceTokens.length; i++) {
if (balanceTokens[i] > 0) IERC20(listTokens[i]).safeTransfer(msg.sender, balanceTokens[i]);
}
}
receive() external payable {}
// ======================== Internal Utility Functions =========================
// Most internal utility functions have a wrapper built on top of it
/// @notice Internal version of the `claimRewards` function
/// Allows to claim rewards for multiple gauges and perpetuals at once
/// @param gaugeUser Address for which to fetch the rewards from the gauges
/// @param liquidityGauges Gauges to claim on
/// @param perpetualIDs Perpetual IDs to claim rewards for
/// @param addressProcessed Whether `PerpetualManager` list is already accessible in `collateralsOrPerpetualManagers`vor if it should be
/// retrieved from `stablecoins` and `collateralsOrPerpetualManagers`
/// @param stablecoins Stablecoin contracts linked to the perpetualsIDs. Array of zero addresses if addressProcessed is true
/// @param collateralsOrPerpetualManagers Collateral contracts linked to the perpetualsIDs or `perpetualManager` contracts if
/// `addressProcessed` is true
/// @dev If the caller wants to send the rewards to another account than `gaugeUser` it first needs to
/// call `set_rewards_receiver(otherAccount)` on each `liquidityGauge`
/// @dev The function only takes rewards received by users,
function _claimRewards(
address gaugeUser,
address[] memory liquidityGauges,
uint256[] memory perpetualIDs,
bool addressProcessed,
address[] memory stablecoins,
address[] memory collateralsOrPerpetualManagers
) internal {
require(
stablecoins.length == perpetualIDs.length && collateralsOrPerpetualManagers.length == perpetualIDs.length,
"104"
);
for (uint256 i = 0; i < liquidityGauges.length; i++) {
ILiquidityGauge(liquidityGauges[i]).claim_rewards(gaugeUser);
}
for (uint256 i = 0; i < perpetualIDs.length; i++) {
IPerpetualManagerFrontWithClaim perpManager;
if (addressProcessed) perpManager = IPerpetualManagerFrontWithClaim(collateralsOrPerpetualManagers[i]);
else {
(, Pairs memory pairs) = _getInternalContracts(
IERC20(stablecoins[i]),
IERC20(collateralsOrPerpetualManagers[i])
);
perpManager = pairs.perpetualManager;
}
perpManager.getReward(perpetualIDs[i]);
}
}
/// @notice Allows to deposit ANGLE on an existing locker
/// @param user Address to deposit for
/// @param amount Amount to deposit
function _depositOnLocker(address user, uint256 amount) internal {
VEANGLE.deposit_for(user, amount);
}
/// @notice Allows to claim weekly interest distribution and if wanted to transfer it to the `angleRouter` for future use
/// @param user Address to claim for
/// @param _feeDistributor Address of the fee distributor to claim to
/// @dev If funds are transferred to the router, this action cannot be an end in itself, otherwise funds will be lost:
/// typically we expect people to call for this action before doing a deposit
/// @dev If `letInContract` (and hence if funds are transferred to the router), you should approve the `angleRouter` to
/// transfer the token claimed from the `feeDistributor`
function _claimWeeklyInterest(
address user,
IFeeDistributorFront _feeDistributor,
bool letInContract
) internal returns (uint256 amount, IERC20 token) {
amount = _feeDistributor.claim(user);
if (letInContract) {
// Fetching info from the `FeeDistributor` to process correctly the withdrawal
token = IERC20(_feeDistributor.token());
token.safeTransferFrom(msg.sender, address(this), amount);
} else {
amount = 0;
}
}
/// @notice Internal version of the `gaugeDeposit` function
/// Allows to deposit tokens into a gauge
/// @param user Address on behalf of which deposit should be made in the gauge
/// @param amount Amount to stake
/// @param gauge LiquidityGauge to stake in
/// @param shouldClaimRewards Whether to claim or not previously accumulated rewards
/// @dev You should be cautious on who will receive the rewards (if `shouldClaimRewards` is true)
/// It can be set on each gauge
/// @dev In the `mixer`, before calling for this action, user should have made sure to get in the router
/// the associated token (by like a `deposit` action)
/// @dev The function will revert if the gauge has not already been approved by the contract
function _gaugeDeposit(
address user,
uint256 amount,
ILiquidityGauge gauge,
bool shouldClaimRewards
) internal {
gauge.deposit(amount, user, shouldClaimRewards);
}
/// @notice Internal version of the `mint` functions
/// Mints stablecoins from the protocol
/// @param user Address to send the stablecoins to
/// @param amount Amount of collateral to use for the mint
/// @param minStableAmount Minimum stablecoin minted for the tx not to revert
/// @param addressProcessed Whether `msg.sender` provided the contracts address or the tokens one
/// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false)
/// or directly the `StableMaster` contract if `addressProcessed`
/// @param collateral Collateral to mint from: it can be null if `addressProcessed` is true but in the corresponding
/// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the mint
/// @param poolManager PoolManager associated to the `collateral` (null if `addressProcessed` is not true)
/// @dev This function is not designed to be composable with other actions of the router after it's called: like
/// stablecoins obtained from it cannot be used for other operations: as such the `user` address should not be the router
/// address
function _mint(
address user,
uint256 amount,
uint256 minStableAmount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateral,
IPoolManager poolManager
) internal {
IStableMasterFront stableMaster;
(stableMaster, poolManager) = _mintBurnContracts(
addressProcessed,
stablecoinOrStableMaster,
collateral,
poolManager
);
stableMaster.mint(amount, user, poolManager, minStableAmount);
}
/// @notice Burns stablecoins from the protocol
/// @param dest Address who will receive the proceeds
/// @param amount Amount of collateral to use for the mint
/// @param minCollatAmount Minimum Collateral minted for the tx not to revert
/// @param addressProcessed Whether `msg.sender` provided the contracts address or the tokens one
/// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false)
/// or directly the `StableMaster` contract if `addressProcessed`
/// @param collateral Collateral to mint from: it can be null if `addressProcessed` is true but in the corresponding
/// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the mint
/// @param poolManager PoolManager associated to the `collateral` (null if `addressProcessed` is not true)
function _burn(
address dest,
uint256 amount,
uint256 minCollatAmount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateral,
IPoolManager poolManager
) internal {
IStableMasterFront stableMaster;
(stableMaster, poolManager) = _mintBurnContracts(
addressProcessed,
stablecoinOrStableMaster,
collateral,
poolManager
);
stableMaster.burn(amount, msg.sender, dest, poolManager, minCollatAmount);
}
/// @notice Internal version of the `deposit` functions
/// Allows to deposit a collateral within the protocol
/// @param user Address where to send the resulting sanTokens, if this address is the router address then it means
/// that the intention is to stake the sanTokens obtained in a subsequent `gaugeDeposit` action
/// @param amount Amount of collateral to deposit
/// @param addressProcessed Whether `msg.sender` provided the contracts addresses or the tokens ones
/// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false)
/// or directly the `StableMaster` contract if `addressProcessed`
/// @param collateral Token to deposit: it can be null if `addressProcessed` is true but in the corresponding
/// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the deposit
/// @param poolManager PoolManager associated to the `collateral` (null if `addressProcessed` is not true)
/// @param sanToken SanToken associated to the `collateral` (null if `addressProcessed` is not true)
/// @dev Contrary to the `mint` action, the `deposit` action can be used in composition with other actions, like
/// `deposit` and then `stake`
function _deposit(
address user,
uint256 amount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateral,
IPoolManager poolManager,
ISanToken sanToken
) internal returns (uint256 addedAmount, address) {
IStableMasterFront stableMaster;
if (addressProcessed) {
stableMaster = IStableMasterFront(stablecoinOrStableMaster);
} else {
Pairs memory pairs;
(stableMaster, pairs) = _getInternalContracts(IERC20(stablecoinOrStableMaster), IERC20(collateral));
poolManager = pairs.poolManager;
sanToken = pairs.sanToken;
}
if (user == address(this)) {
// Computing the amount of sanTokens obtained
addedAmount = sanToken.balanceOf(address(this));
stableMaster.deposit(amount, address(this), poolManager);
addedAmount = sanToken.balanceOf(address(this)) - addedAmount;
} else {
stableMaster.deposit(amount, user, poolManager);
}
return (addedAmount, address(sanToken));
}
/// @notice Withdraws sanTokens from the protocol
/// @param amount Amount of sanTokens to withdraw
/// @param addressProcessed Whether `msg.sender` provided the contracts addresses or the tokens ones
/// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false)
/// or directly the `StableMaster` contract if `addressProcessed`
/// @param collateralOrPoolManager Collateral to withdraw (if `addressProcessed` is false) or directly
/// the `PoolManager` contract if `addressProcessed`
function _withdraw(
uint256 amount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateralOrPoolManager
) internal returns (uint256 withdrawnAmount, address) {
IStableMasterFront stableMaster;
// Stores the address of the `poolManager`, while `collateralOrPoolManager` is used in the function
// to store the `collateral` address
IPoolManager poolManager;
if (addressProcessed) {
stableMaster = IStableMasterFront(stablecoinOrStableMaster);
poolManager = IPoolManager(collateralOrPoolManager);
collateralOrPoolManager = poolManager.token();
} else {
Pairs memory pairs;
(stableMaster, pairs) = _getInternalContracts(
IERC20(stablecoinOrStableMaster),
IERC20(collateralOrPoolManager)
);
poolManager = pairs.poolManager;
}
// Here reusing the `withdrawnAmount` variable to avoid a stack too deep problem
withdrawnAmount = IERC20(collateralOrPoolManager).balanceOf(address(this));
// This call will increase our collateral balance
stableMaster.withdraw(amount, address(this), address(this), poolManager);
// We compute the difference between our collateral balance after and before the `withdraw` call
withdrawnAmount = IERC20(collateralOrPoolManager).balanceOf(address(this)) - withdrawnAmount;
return (withdrawnAmount, collateralOrPoolManager);
}
/// @notice Internal version of the `openPerpetual` function
/// Opens a perpetual within Angle
/// @param owner Address to mint perpetual for
/// @param margin Margin to open the perpetual with
/// @param amountCommitted Commit amount in the perpetual
/// @param maxOracleRate Maximum oracle rate required to have a leverage position opened
/// @param minNetMargin Minimum net margin required to have a leverage position opened
/// @param addressProcessed Whether msg.sender provided the contracts addresses or the tokens ones
/// @param stablecoinOrPerpetualManager Token associated to the `StableMaster` (iif `addressProcessed` is false)
/// or address of the desired `PerpetualManager` (if `addressProcessed` is true)
/// @param collateral Collateral to mint from (it can be null if `addressProcessed` is true): it can be null if `addressProcessed` is true but in the corresponding
/// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the deposit
function _openPerpetual(
address owner,
uint256 margin,
uint256 amountCommitted,
uint256 maxOracleRate,
uint256 minNetMargin,
bool addressProcessed,
address stablecoinOrPerpetualManager,
address collateral
) internal returns (uint256 perpetualID) {
if (!addressProcessed) {
(, Pairs memory pairs) = _getInternalContracts(IERC20(stablecoinOrPerpetualManager), IERC20(collateral));
stablecoinOrPerpetualManager = address(pairs.perpetualManager);
}
return
IPerpetualManagerFrontWithClaim(stablecoinOrPerpetualManager).openPerpetual(
owner,
margin,
amountCommitted,
maxOracleRate,
minNetMargin
);
}
/// @notice Internal version of the `addToPerpetual` function
/// Adds collateral to a perpetual
/// @param margin Amount of collateral to add
/// @param perpetualID Perpetual to add collateral to
/// @param addressProcessed Whether msg.sender provided the contracts addresses or the tokens ones
/// @param stablecoinOrPerpetualManager Token associated to the `StableMaster` (iif `addressProcessed` is false)
/// or address of the desired `PerpetualManager` (if `addressProcessed` is true)
/// @param collateral Collateral to mint from (it can be null if `addressProcessed` is true): it can be null if `addressProcessed` is true but in the corresponding
/// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the deposit
function _addToPerpetual(
uint256 margin,
uint256 perpetualID,
bool addressProcessed,
address stablecoinOrPerpetualManager,
address collateral
) internal {
if (!addressProcessed) {
(, Pairs memory pairs) = _getInternalContracts(IERC20(stablecoinOrPerpetualManager), IERC20(collateral));
stablecoinOrPerpetualManager = address(pairs.perpetualManager);
}
IPerpetualManagerFrontWithClaim(stablecoinOrPerpetualManager).addToPerpetual(perpetualID, margin);
}
// ======================== Internal Utility Functions =========================
/// @notice Checks if collateral in the list
/// @param list List of addresses
/// @param searchFor Address of interest
/// @return index Place of the address in the list if it is in or current length otherwise
function _searchList(address[_MAX_TOKENS] memory list, address searchFor) internal pure returns (uint256 index) {
uint256 i;
while (i < list.length && list[i] != address(0)) {
if (list[i] == searchFor) return i;
i++;
}
return i;
}
/// @notice Modifies stored balances for a given collateral
/// @param list List of collateral addresses
/// @param balances List of balances for the different supported collateral types
/// @param searchFor Address of the collateral of interest
/// @param amount Amount to add in the balance for this collateral
function _addToList(
address[_MAX_TOKENS] memory list,
uint256[_MAX_TOKENS] memory balances,
address searchFor,
uint256 amount
) internal pure {
uint256 index = _searchList(list, searchFor);
// add it to the list if non existent and we add tokens
if (list[index] == address(0)) list[index] = searchFor;
balances[index] += amount;
}
/// @notice Computes the proportion of the collateral leftover balance to use for a given action
/// @param proportion Ratio to take from balance
/// @param list Collateral list
/// @param balances Balances of each collateral asset in the collateral list
/// @param searchFor Collateral to look for
/// @return amount Amount to use for the action (based on the proportion given)
/// @dev To use all the collateral balance available for an action, users should give `proportion` a value of
/// `BASE_PARAMS`
function _computeProportion(
uint256 proportion,
address[_MAX_TOKENS] memory list,
uint256[_MAX_TOKENS] memory balances,
address searchFor
) internal pure returns (uint256 amount) {
uint256 index = _searchList(list, searchFor);
// Reverts if the index was not found
require(list[index] != address(0), "33");
amount = (proportion * balances[index]) / BASE_PARAMS;
balances[index] -= amount;
}
/// @notice Gets Angle contracts associated to a pair (stablecoin, collateral)
/// @param stablecoin Token associated to a `StableMaster`
/// @param collateral Collateral to mint/deposit/open perpetual or add collateral from
/// @dev This function is used to check that the parameters passed by people calling some of the main
/// router functions are correct
function _getInternalContracts(IERC20 stablecoin, IERC20 collateral)
internal
view
returns (IStableMasterFront stableMaster, Pairs memory pairs)
{
stableMaster = mapStableMasters[stablecoin];
pairs = mapPoolManagers[stableMaster][collateral];
// If `stablecoin` is zero then this necessarily means that `stableMaster` here will be 0
// Similarly, if `collateral` is zero, then this means that `pairs.perpetualManager`, `pairs.poolManager`
// and `pairs.sanToken` will be zero
// Last, if any of `pairs.perpetualManager`, `pairs.poolManager` or `pairs.sanToken` is zero, this means
// that all others should be null from the `addPairs` and `removePairs` functions which keep this invariant
require(address(stableMaster) != address(0) && address(pairs.poolManager) != address(0), "0");
return (stableMaster, pairs);
}
/// @notice Get contracts for mint and burn actions
/// @param addressProcessed Whether `msg.sender` provided the contracts address or the tokens one
/// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false)
/// or directly the `StableMaster` contract if `addressProcessed`
/// @param collateral Collateral to mint from: it can be null if `addressProcessed` is true but in the corresponding
/// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the mint
/// @param poolManager PoolManager associated to the `collateral` (null if `addressProcessed` is not true)
function _mintBurnContracts(
bool addressProcessed,
address stablecoinOrStableMaster,
address collateral,
IPoolManager poolManager
) internal view returns (IStableMasterFront, IPoolManager) {
IStableMasterFront stableMaster;
if (addressProcessed) {
stableMaster = IStableMasterFront(stablecoinOrStableMaster);
} else {
Pairs memory pairs;
(stableMaster, pairs) = _getInternalContracts(IERC20(stablecoinOrStableMaster), IERC20(collateral));
poolManager = pairs.poolManager;
}
return (stableMaster, poolManager);
}
/// @notice Adds new collateral type to specific stablecoin
/// @param stableMaster Address of the `StableMaster` associated to the stablecoin of interest
/// @param poolManager Address of the `PoolManager` contract associated to the pair (stablecoin,collateral)
/// @param liquidityGauge Address of liquidity gauge contract associated to sanToken
function _addPair(
IStableMasterFront stableMaster,
IPoolManager poolManager,
ILiquidityGauge liquidityGauge
) internal {
// Fetching the associated `sanToken` and `perpetualManager` from the contract
(IERC20 collateral, ISanToken sanToken, IPerpetualManager perpetualManager, , , , , , ) = IStableMaster(
address(stableMaster)
).collateralMap(poolManager);
Pairs storage _pairs = mapPoolManagers[stableMaster][collateral];
// Checking if the pair has not already been initialized: if yes we need to make the function revert
// otherwise we could end up with still approved `PoolManager` and `PerpetualManager` contracts
require(address(_pairs.poolManager) == address(0), "114");
_pairs.poolManager = poolManager;
_pairs.perpetualManager = IPerpetualManagerFrontWithClaim(address(perpetualManager));
_pairs.sanToken = sanToken;
// In the future, it is possible that sanTokens do not have an associated liquidity gauge
if (address(liquidityGauge) != address(0)) {
require(address(sanToken) == liquidityGauge.staking_token(), "20");
_pairs.gauge = liquidityGauge;
sanToken.approve(address(liquidityGauge), type(uint256).max);
}
_changeAllowance(collateral, address(stableMaster), type(uint256).max);
_changeAllowance(collateral, address(perpetualManager), type(uint256).max);
emit CollateralToggled(address(stableMaster), address(poolManager), address(liquidityGauge));
}
/// @notice Changes allowance of this contract for a given token
/// @param token Address of the token to change allowance
/// @param spender Address to change the allowance of
/// @param amount Amount allowed
function _changeAllowance(
IERC20 token,
address spender,
uint256 amount
) internal {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < amount) {
token.safeIncreaseAllowance(spender, amount - currentAllowance);
} else if (currentAllowance > amount) {
token.safeDecreaseAllowance(spender, currentAllowance - amount);
}
}
/// @notice Transfers collateral or an arbitrary token which is then swapped on UniswapV3 or on 1Inch
/// @param inToken Token to swap for the collateral
/// @param amount Amount of in token to swap for the collateral
/// @param minAmountOut Minimum amount accepted for the swap to happen
/// @param swapType Choice on which contracts to swap
/// @param args Bytes representing either the path to swap your input token to the accepted collateral on Uniswap or payload for 1Inch
/// @dev The `path` provided is not checked, meaning people could swap for a token A and declare that they've swapped for another token B.
/// However, the mixer manipulates its token balance only through the addresses registered in `listTokens`, so any subsequent mixer action
/// trying to transfer funds B will do it through address of token A and revert as A is not actually funded.
/// In case there is not subsequent action, `mixer` will revert when trying to send back what appears to be remaining tokens A.
function _transferAndSwap(
IERC20 inToken,
uint256 amount,
uint256 minAmountOut,
SwapType swapType,
bytes memory args
) internal returns (uint256 amountOut) {
if (address(inToken) == address(WETH9) && address(this).balance >= amount) {
WETH9.deposit{ value: amount }(); // wrap only what is needed to pay
} else {
inToken.safeTransferFrom(msg.sender, address(this), amount);
}
if (swapType == SwapType.UniswapV3) amountOut = _swapOnUniswapV3(inToken, amount, minAmountOut, args);
else if (swapType == SwapType.oneINCH) amountOut = _swapOn1Inch(inToken, minAmountOut, args);
else require(false, "3");
return amountOut;
}
/// @notice Allows to swap any token to an accepted collateral via UniswapV3 (if there is a path)
/// @param inToken Address token used as entrance of the swap
/// @param amount Amount of in token to swap for the accepted collateral
/// @param minAmountOut Minimum amount accepted for the swap to happen
/// @param path Bytes representing the path to swap your input token to the accepted collateral
function _swapOnUniswapV3(
IERC20 inToken,
uint256 amount,
uint256 minAmountOut,
bytes memory path
) internal returns (uint256 amountOut) {
// Approve transfer to the `uniswapV3Router` if it is the first time that the token is used
if (!uniAllowedToken[inToken]) {
inToken.safeIncreaseAllowance(address(uniswapV3Router), type(uint256).max);
uniAllowedToken[inToken] = true;
}
amountOut = uniswapV3Router.exactInput(
ExactInputParams(path, address(this), block.timestamp, amount, minAmountOut)
);
}
/// @notice Allows to swap any token to an accepted collateral via 1Inch API
/// @param minAmountOut Minimum amount accepted for the swap to happen
/// @param payload Bytes needed for 1Inch API
function _swapOn1Inch(
IERC20 inToken,
uint256 minAmountOut,
bytes memory payload
) internal returns (uint256 amountOut) {
// Approve transfer to the `oneInch` router if it is the first time the token is used
if (!oneInchAllowedToken[inToken]) {
inToken.safeIncreaseAllowance(address(oneInch), type(uint256).max);
oneInchAllowedToken[inToken] = true;
}
//solhint-disable-next-line
(bool success, bytes memory result) = oneInch.call(payload);
if (!success) _revertBytes(result);
amountOut = abi.decode(result, (uint256));
require(amountOut >= minAmountOut, "15");
}
/// @notice Internal function used for error handling
function _revertBytes(bytes memory errMsg) internal pure {
if (errMsg.length > 0) {
//solhint-disable-next-line
assembly {
revert(add(32, errMsg), mload(errMsg))
}
}
revert("117");
}
}
// 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 Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev 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 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: GPL-3.0
pragma solidity ^0.8.7;
/// @title IFeeDistributor
/// @author Interface of the `FeeDistributor` contract
/// @dev This interface is used by the `SurplusConverter` contract to send funds to the `FeeDistributor`
interface IFeeDistributor {
function burn(address token) external;
}
/// @title IFeeDistributorFront
/// @author Interface for public use of the `FeeDistributor` contract
/// @dev This interface is used for user related function
interface IFeeDistributorFront {
function token() external returns (address);
function claim(address _addr) external returns (uint256);
function claim(address[20] memory _addr) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
interface ILiquidityGauge {
// solhint-disable-next-line
function staking_token() external returns (address stakingToken);
// solhint-disable-next-line
function deposit_reward_token(address _rewardToken, uint256 _amount) external;
function deposit(
uint256 _value,
address _addr,
// solhint-disable-next-line
bool _claim_rewards
) external;
// solhint-disable-next-line
function claim_rewards(address _addr) external;
// solhint-disable-next-line
function claim_rewards(address _addr, address _receiver) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
/// @title ISanToken
/// @author Angle Core Team
/// @notice Interface for Angle's `SanToken` contract that handles sanTokens, tokens that are given to SLPs
/// contributing to a collateral for a given stablecoin
interface ISanToken is IERC20Upgradeable {
// ================================== StableMaster =============================
function mint(address account, uint256 amount) external;
function burnFrom(
uint256 amount,
address burner,
address sender
) external;
function burnSelf(uint256 amount, address burner) external;
function stableMaster() external view returns (address);
function poolManager() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// Normally just importing `IPoolManager` should be sufficient, but for clarity here
// we prefer to import all concerned interfaces
import "./IPoolManager.sol";
import "./IOracle.sol";
import "./IPerpetualManager.sol";
import "./ISanToken.sol";
// Struct to handle all the parameters to manage the fees
// related to a given collateral pool (associated to the stablecoin)
struct MintBurnData {
// Values of the thresholds to compute the minting fees
// depending on HA hedge (scaled by `BASE_PARAMS`)
uint64[] xFeeMint;
// Values of the fees at thresholds (scaled by `BASE_PARAMS`)
uint64[] yFeeMint;
// Values of the thresholds to compute the burning fees
// depending on HA hedge (scaled by `BASE_PARAMS`)
uint64[] xFeeBurn;
// Values of the fees at thresholds (scaled by `BASE_PARAMS`)
uint64[] yFeeBurn;
// Max proportion of collateral from users that can be covered by HAs
// It is exactly the same as the parameter of the same name in `PerpetualManager`, whenever one is updated
// the other changes accordingly
uint64 targetHAHedge;
// Minting fees correction set by the `FeeManager` contract: they are going to be multiplied
// to the value of the fees computed using the hedge curve
// Scaled by `BASE_PARAMS`
uint64 bonusMalusMint;
// Burning fees correction set by the `FeeManager` contract: they are going to be multiplied
// to the value of the fees computed using the hedge curve
// Scaled by `BASE_PARAMS`
uint64 bonusMalusBurn;
// Parameter used to limit the number of stablecoins that can be issued using the concerned collateral
uint256 capOnStableMinted;
}
// Struct to handle all the variables and parameters to handle SLPs in the protocol
// including the fraction of interests they receive or the fees to be distributed to
// them
struct SLPData {
// Last timestamp at which the `sanRate` has been updated for SLPs
uint256 lastBlockUpdated;
// Fees accumulated from previous blocks and to be distributed to SLPs
uint256 lockedInterests;
// Max interests used to update the `sanRate` in a single block
// Should be in collateral token base
uint256 maxInterestsDistributed;
// Amount of fees left aside for SLPs and that will be distributed
// when the protocol is collateralized back again
uint256 feesAside;
// Part of the fees normally going to SLPs that is left aside
// before the protocol is collateralized back again (depends on collateral ratio)
// Updated by keepers and scaled by `BASE_PARAMS`
uint64 slippageFee;
// Portion of the fees from users minting and burning
// that goes to SLPs (the rest goes to surplus)
uint64 feesForSLPs;
// Slippage factor that's applied to SLPs exiting (depends on collateral ratio)
// If `slippage = BASE_PARAMS`, SLPs can get nothing, if `slippage = 0` they get their full claim
// Updated by keepers and scaled by `BASE_PARAMS`
uint64 slippage;
// Portion of the interests from lending
// that goes to SLPs (the rest goes to surplus)
uint64 interestsForSLPs;
}
/// @title IStableMasterFunctions
/// @author Angle Core Team
/// @notice Interface for the `StableMaster` contract
interface IStableMasterFunctions {
function deploy(
address[] memory _governorList,
address _guardian,
address _agToken
) external;
// ============================== Lending ======================================
function accumulateInterest(uint256 gain) external;
function signalLoss(uint256 loss) external;
// ============================== HAs ==========================================
function getStocksUsers() external view returns (uint256 maxCAmountInStable);
function convertToSLP(uint256 amount, address user) external;
// ============================== Keepers ======================================
function getCollateralRatio() external returns (uint256);
function setFeeKeeper(
uint64 feeMint,
uint64 feeBurn,
uint64 _slippage,
uint64 _slippageFee
) external;
// ============================== AgToken ======================================
function updateStocksUsers(uint256 amount, address poolManager) external;
// ============================= Governance ====================================
function setCore(address newCore) external;
function addGovernor(address _governor) external;
function removeGovernor(address _governor) external;
function setGuardian(address newGuardian, address oldGuardian) external;
function revokeGuardian(address oldGuardian) external;
function setCapOnStableAndMaxInterests(
uint256 _capOnStableMinted,
uint256 _maxInterestsDistributed,
IPoolManager poolManager
) external;
function setIncentivesForSLPs(
uint64 _feesForSLPs,
uint64 _interestsForSLPs,
IPoolManager poolManager
) external;
function setUserFees(
IPoolManager poolManager,
uint64[] memory _xFee,
uint64[] memory _yFee,
uint8 _mint
) external;
function setTargetHAHedge(uint64 _targetHAHedge) external;
function pause(bytes32 agent, IPoolManager poolManager) external;
function unpause(bytes32 agent, IPoolManager poolManager) external;
}
/// @title IStableMaster
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
interface IStableMaster is IStableMasterFunctions {
function agToken() external view returns (address);
function collateralMap(IPoolManager poolManager)
external
view
returns (
IERC20 token,
ISanToken sanToken,
IPerpetualManager perpetualManager,
IOracle oracle,
uint256 stocksUsers,
uint256 sanRate,
uint256 collatBase,
SLPData memory slpData,
MintBurnData memory feeData
);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "../interfaces/IPoolManager.sol";
/// @title IStableMasterFront
/// @author Angle Core Team
/// @dev Front interface, meaning only user-facing functions
interface IStableMasterFront {
function mint(
uint256 amount,
address user,
IPoolManager poolManager,
uint256 minStableAmount
) external;
function burn(
uint256 amount,
address burner,
address dest,
IPoolManager poolManager,
uint256 minCollatAmount
) external;
function deposit(
uint256 amount,
address user,
IPoolManager poolManager
) external;
function withdraw(
uint256 amount,
address burner,
address dest,
IPoolManager poolManager
) external;
function agToken() external returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
/// @title IVeANGLE
/// @author Angle Core Team
/// @notice Interface for the `VeANGLE` contract
interface IVeANGLE {
// solhint-disable-next-line func-name-mixedcase
function deposit_for(address addr, uint256 amount) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title Interface for WETH9
interface IWETH9 is IERC20 {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface IUniswapV3Router {
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
}
/// @title Router for price estimation functionality
/// @notice Functions for getting the price of one token with respect to another using Uniswap V2
/// @dev This interface is only used for non critical elements of the protocol
interface IUniswapV2Router {
/// @notice Given an input asset amount, returns the maximum output amount of the
/// other asset (accounting for fees) given reserves.
/// @param path Addresses of the pools used to get prices
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 swapAmount,
uint256 minExpected,
address[] calldata path,
address receiver,
uint256 swapDeadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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: GPL-3.0
pragma solidity ^0.8.7;
import "./IFeeManager.sol";
import "./IPerpetualManager.sol";
import "./IOracle.sol";
// Struct for the parameters associated to a strategy interacting with a collateral `PoolManager`
// contract
struct StrategyParams {
// Timestamp of last report made by this strategy
// It is also used to check if a strategy has been initialized
uint256 lastReport;
// Total amount the strategy is expected to have
uint256 totalStrategyDebt;
// The share of the total assets in the `PoolManager` contract that the `strategy` can access to.
uint256 debtRatio;
}
/// @title IPoolManagerFunctions
/// @author Angle Core Team
/// @notice Interface for the collateral poolManager contracts handling each one type of collateral for
/// a given stablecoin
/// @dev Only the functions used in other contracts of the protocol are left here
interface IPoolManagerFunctions {
// ============================ Constructor ====================================
function deployCollateral(
address[] memory governorList,
address guardian,
IPerpetualManager _perpetualManager,
IFeeManager feeManager,
IOracle oracle
) external;
// ============================ Yield Farming ==================================
function creditAvailable() external view returns (uint256);
function debtOutstanding() external view returns (uint256);
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external;
// ============================ Governance =====================================
function addGovernor(address _governor) external;
function removeGovernor(address _governor) external;
function setGuardian(address _guardian, address guardian) external;
function revokeGuardian(address guardian) external;
function setFeeManager(IFeeManager _feeManager) external;
// ============================= Getters =======================================
function getBalance() external view returns (uint256);
function getTotalAsset() external view returns (uint256);
}
/// @title IPoolManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
/// @dev Used in other contracts of the protocol
interface IPoolManager is IPoolManagerFunctions {
function stableMaster() external view returns (address);
function perpetualManager() external view returns (address);
function token() external view returns (address);
function feeManager() external view returns (address);
function totalDebt() external view returns (uint256);
function strategies(address _strategy) external view returns (StrategyParams memory);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
/// @title IOracle
/// @author Angle Core Team
/// @notice Interface for Angle's oracle contracts reading oracle rates from both UniswapV3 and Chainlink
/// from just UniswapV3 or from just Chainlink
interface IOracle {
function read() external view returns (uint256);
function readAll() external view returns (uint256 lowerRate, uint256 upperRate);
function readLower() external view returns (uint256);
function readUpper() external view returns (uint256);
function readQuote(uint256 baseAmount) external view returns (uint256);
function readQuoteLower(uint256 baseAmount) external view returns (uint256);
function inBase() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "./IERC721.sol";
import "./IFeeManager.sol";
import "./IOracle.sol";
import "./IAccessControl.sol";
/// @title Interface of the contract managing perpetuals
/// @author Angle Core Team
/// @dev Front interface, meaning only user-facing functions
interface IPerpetualManagerFront is IERC721Metadata {
function openPerpetual(
address owner,
uint256 amountBrought,
uint256 amountCommitted,
uint256 maxOracleRate,
uint256 minNetMargin
) external returns (uint256 perpetualID);
function closePerpetual(
uint256 perpetualID,
address to,
uint256 minCashOutAmount
) external;
function addToPerpetual(uint256 perpetualID, uint256 amount) external;
function removeFromPerpetual(
uint256 perpetualID,
uint256 amount,
address to
) external;
function liquidatePerpetuals(uint256[] memory perpetualIDs) external;
function forceClosePerpetuals(uint256[] memory perpetualIDs) external;
// ========================= External View Functions =============================
function getCashOutAmount(uint256 perpetualID, uint256 rate) external view returns (uint256, uint256);
function isApprovedOrOwner(address spender, uint256 perpetualID) external view returns (bool);
}
/// @title Interface of the contract managing perpetuals
/// @author Angle Core Team
/// @dev This interface does not contain user facing functions, it just has functions that are
/// interacted with in other parts of the protocol
interface IPerpetualManagerFunctions is IAccessControl {
// ================================= Governance ================================
function deployCollateral(
address[] memory governorList,
address guardian,
IFeeManager feeManager,
IOracle oracle_
) external;
function setFeeManager(IFeeManager feeManager_) external;
function setHAFees(
uint64[] memory _xHAFees,
uint64[] memory _yHAFees,
uint8 deposit
) external;
function setTargetAndLimitHAHedge(uint64 _targetHAHedge, uint64 _limitHAHedge) external;
function setKeeperFeesLiquidationRatio(uint64 _keeperFeesLiquidationRatio) external;
function setKeeperFeesCap(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap) external;
function setKeeperFeesClosing(uint64[] memory _xKeeperFeesClosing, uint64[] memory _yKeeperFeesClosing) external;
function setLockTime(uint64 _lockTime) external;
function setBoundsPerpetual(uint64 _maxLeverage, uint64 _maintenanceMargin) external;
function pause() external;
function unpause() external;
// ==================================== Keepers ================================
function setFeeKeeper(uint64 feeDeposit, uint64 feesWithdraw) external;
// =============================== StableMaster ================================
function setOracle(IOracle _oracle) external;
}
/// @title IPerpetualManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables
interface IPerpetualManager is IPerpetualManagerFunctions {
function poolManager() external view returns (address);
function oracle() external view returns (address);
function targetHAHedge() external view returns (uint64);
function totalHedgeAmount() external view returns (uint256);
}
/// @title Interface of the contract managing perpetuals with claim function
/// @author Angle Core Team
/// @dev Front interface with rewards function, meaning only user-facing functions
interface IPerpetualManagerFrontWithClaim is IPerpetualManagerFront, IPerpetualManager {
function getReward(uint256 perpetualID) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "./IAccessControl.sol";
/// @title IFeeManagerFunctions
/// @author Angle Core Team
/// @dev Interface for the `FeeManager` contract
interface IFeeManagerFunctions is IAccessControl {
// ================================= Keepers ===================================
function updateUsersSLP() external;
function updateHA() external;
// ================================= Governance ================================
function deployCollateral(
address[] memory governorList,
address guardian,
address _perpetualManager
) external;
function setFees(
uint256[] memory xArray,
uint64[] memory yArray,
uint8 typeChange
) external;
function setHAFees(uint64 _haFeeDeposit, uint64 _haFeeWithdraw) external;
}
/// @title IFeeManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
/// @dev We need these getters as they are used in other contracts of the protocol
interface IFeeManager is IFeeManagerFunctions {
function stableMaster() external view returns (address);
function perpetualManager() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
/// @title IAccessControl
/// @author Forked from OpenZeppelin
/// @notice Interface for `AccessControl` contracts
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
interface IERC721 is IERC165 {
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | IStableMasterFront Angle Core Team Front interface, meaning only user-facing functions | interface IStableMasterFront {
function mint(
uint256 amount,
address user,
IPoolManager poolManager,
uint256 minStableAmount
) external;
function burn(
uint256 amount,
address burner,
address dest,
IPoolManager poolManager,
uint256 minCollatAmount
) external;
function deposit(
uint256 amount,
address user,
IPoolManager poolManager
) external;
function withdraw(
uint256 amount,
address burner,
address dest,
IPoolManager poolManager
) external;
function agToken() external returns (address);
}
| 6,009,188 |
./partial_match/1/0x7582C2b3319150C087F3816cAe655FfD255eFd1F/sources/EdFiStakePool.sol | Stake EdFi tokens to EdFiStakePool | function stake(uint256 _amount)
external
nonReentrant
whenNotPaused
{
UserInfo storage user = userInfo[_msgSender()];
updatePool();
if (user.amount > 0) {
uint256 pending = user
.amount
.mul(poolInfo.accEdFiPerShare)
.div(PRECISION)
.sub(user.rewardDebt);
if (pending > 0) {
safeEdFiTransfer(_msgSender(), pending);
}
}
if (_amount > 0) {
IERC20(EdFiAddress).safeTransferFrom(
address(_msgSender()),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(poolInfo.accEdFiPerShare).div(
PRECISION
);
IBoostToken(boostTokenAddress).mint(_msgSender(), _amount);
_updateEdFiPerBlock(IERC20(EdFiAddress).balanceOf(address(this)));
emit Stake(_msgSender(), _amount);
}
| 16,172,701 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "../ERC20.sol";
import "./ERC721.sol";
import "../interfaces/Interfaces.sol";
contract EtherOrcsAllies is ERC721 {
uint256 constant startId = 5050;
mapping(uint256 => Ally) public allies;
mapping(address => bool) public auth;
uint16 shSupply;
uint16 ogSupply;
uint16 mgSupply;
uint16 rgSupply;
ERC20 boneShards;
MetadataHandlerAllies metadaHandler;
address public castle;
bool public openForMint;
bytes32 internal entropySauce;
struct Ally {uint8 class; uint16 level; uint32 lvlProgress; uint16 modF; uint8 skillCredits; bytes22 details;}
struct Shaman {uint8 body; uint8 featA; uint8 featB; uint8 helm; uint8 mainhand; uint8 offhand;}
modifier noCheaters() {
uint256 size = 0;
address acc = msg.sender;
assembly { size := extcodesize(acc)}
require(auth[msg.sender] || (msg.sender == tx.origin && size == 0), "you're trying to cheat!");
_;
// We'll use the last caller hash to add entropy to next caller
entropySauce = keccak256(abi.encodePacked(acc, block.coinbase));
}
function initialize(address ct, address bs, address meta) external {
require(msg.sender == admin);
castle = ct;
boneShards = ERC20(bs);
metadaHandler = MetadataHandlerAllies(meta);
}
function setAuth(address add_, bool status) external {
require(msg.sender == admin);
auth[add_] = status;
}
function setMintOpen(bool open_) external {
require(msg.sender == admin);
openForMint = open_;
}
function tokenURI(uint256 id) external view returns(string memory) {
Ally memory ally = allies[id];
return metadaHandler.getTokenURI(id, ally.class, ally.level, ally.modF, ally.skillCredits, ally.details);
}
function mintShamans(uint256 amount) external {
for (uint256 i = 0; i < amount; i++) {
mintShaman();
}
}
function mintShaman() public noCheaters {
require(openForMint || auth[msg.sender], "not open for mint");
boneShards.burn(msg.sender, 60 ether);
_mintShaman(_rand());
}
function pull(address owner_, uint256[] calldata ids) external {
require (msg.sender == castle, "not castle");
for (uint256 index = 0; index < ids.length; index++) {
_transfer(owner_, msg.sender, ids[index]);
}
CastleLike(msg.sender).pullCallback(owner_, ids);
}
function adjustAlly(uint256 id, uint8 class_, uint16 level_, uint32 lvlProgress_, uint16 modF_, uint8 skillCredits_, bytes22 details_) external {
require(auth[msg.sender], "not authorized");
allies[id] = Ally({class: class_, level: level_, lvlProgress: lvlProgress_, modF: modF_, skillCredits: skillCredits_, details: details_});
}
function shamans(uint256 id) external view returns(uint16 level, uint32 lvlProgress, uint16 modF, uint8 skillCredits, uint8 body, uint8 featA, uint8 featB, uint8 helm, uint8 mainhand, uint8 offhand) {
Ally memory ally = allies[id];
level = ally.level;
lvlProgress = ally.lvlProgress;
modF = ally.modF;
skillCredits = ally.skillCredits;
Shaman memory sh = _shaman(ally.details);
body = sh.body;
featA = sh.featA;
featB = sh.featB;
helm = sh.helm;
mainhand = sh.mainhand;
offhand = sh.offhand;
}
function _shaman(bytes22 details) internal pure returns(Shaman memory sh) {
uint8 body = uint8(bytes1(details));
uint8 featA = uint8(bytes1(details << 8));
uint8 featB = uint8(bytes1(details << 16));
uint8 helm = uint8(bytes1(details << 24));
uint8 mainhand = uint8(bytes1(details << 32));
uint8 offhand = uint8(bytes1(details << 40));
sh.body = body;
sh.featA = featA;
sh.featB = featB;
sh.helm = helm;
sh.mainhand = mainhand;
sh.offhand = offhand;
}
function _mintShaman(uint256 rand) internal returns (uint16 id) {
id = uint16(shSupply + 1 + startId); //check that supply is less than 3000
require(shSupply++ <= 3000, "max supply reached");
// Getting Random traits
uint8 body = _getBody(_randomize(rand, "BODY", id));
uint8 featB = uint8(_randomize(rand, "featB", id) % 22) + 1;
uint8 featA = uint8(_randomize(rand, "featA", id) % 20) + 1;
uint8 helm = uint8(_randomize(rand, "HELM", id) % 7) + 1;
uint8 mainhand = uint8(_randomize(rand, "MAINHAND", id) % 7) + 1;
uint8 offhand = uint8(_randomize(rand, "OFFHAND", id) % 7) + 1;
_mint(msg.sender, id);
allies[id] = Ally({class: 1, level: 25, lvlProgress: 25000, modF: 0, skillCredits: 100, details: bytes22(abi.encodePacked(body, featA, featB, helm, mainhand, offhand))});
}
function _getBody(uint256 rand) internal pure returns (uint8) {
uint256 sixtyFivePct = type(uint16).max / 100 * 65;
uint256 nineSevenPct = type(uint16).max / 100 * 97;
uint256 nineNinePct = type(uint16).max / 100 * 99;
if (uint16(rand) < sixtyFivePct) return uint8(rand % 5) + 1;
if (uint16(rand) < nineSevenPct) return uint8(rand % 4) + 6;
if (uint16(rand) < nineNinePct) return 10;
return 11;
}
/// @dev Create a bit more of randomness
function _randomize(uint256 rand, string memory val, uint256 spicy) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(rand, val, spicy)));
}
function _rand() internal view returns (uint256) {
return uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.basefee, block.timestamp, entropySauce)));
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity 0.8.7;
/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// Taken from Solmate: https://github.com/Rari-Capital/solmate
abstract contract ERC20 {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
function name() external view virtual returns (string memory);
function symbol() external view virtual returns (string memory);
function decimals() external view virtual returns (uint8);
// string public constant name = "ZUG";
// string public constant symbol = "ZUG";
// uint8 public constant decimals = 18;
/*///////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
mapping(address => bool) public isMinter;
address public ruler;
/*///////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
constructor() { ruler = msg.sender;}
function approve(address spender, uint256 value) external returns (bool) {
allowance[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
function transfer(address to, uint256 value) external returns (bool) {
balanceOf[msg.sender] -= value;
// This is safe because the sum of all user
// balances can't exceed type(uint256).max!
unchecked {
balanceOf[to] += value;
}
emit Transfer(msg.sender, to, value);
return true;
}
function transferFrom(
address from,
address to,
uint256 value
) external returns (bool) {
if (allowance[from][msg.sender] != type(uint256).max) {
allowance[from][msg.sender] -= value;
}
balanceOf[from] -= value;
// This is safe because the sum of all user
// balances can't exceed type(uint256).max!
unchecked {
balanceOf[to] += value;
}
emit Transfer(from, to, value);
return true;
}
/*///////////////////////////////////////////////////////////////
ORC PRIVILEGE
//////////////////////////////////////////////////////////////*/
function mint(address to, uint256 value) external {
require(isMinter[msg.sender], "FORBIDDEN TO MINT");
_mint(to, value);
}
function burn(address from, uint256 value) external {
require(isMinter[msg.sender], "FORBIDDEN TO BURN");
_burn(from, value);
}
/*///////////////////////////////////////////////////////////////
Ruler Function
//////////////////////////////////////////////////////////////*/
function setMinter(address minter, bool status) external {
require(msg.sender == ruler, "NOT ALLOWED TO RULE");
isMinter[minter] = status;
}
function setRuler(address ruler_) external {
require(msg.sender == ruler ||ruler == address(0), "NOT ALLOWED TO RULE");
ruler = ruler_;
}
/*///////////////////////////////////////////////////////////////
INTERNAL UTILS
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 value) internal {
totalSupply += value;
// This is safe because the sum of all user
// balances can't exceed type(uint256).max!
unchecked {
balanceOf[to] += value;
}
emit Transfer(address(0), to, value);
}
function _burn(address from, uint256 value) internal {
balanceOf[from] -= value;
// This is safe because a user won't ever
// have a balance larger than totalSupply!
unchecked {
totalSupply -= value;
}
emit Transfer(from, address(0), value);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.8.7;
/// @notice Modern and gas efficient ERC-721 + ERC-20/EIP-2612-like implementation,
/// including the MetaData, and partially, Enumerable extensions.
contract ERC721 {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed spender, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
address implementation_;
address public admin; //Lame requirement from opensea
/*///////////////////////////////////////////////////////////////
ERC-721 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(uint256 => address) public ownerOf;
mapping(uint256 => address) public getApproved;
mapping(address => mapping(address => bool)) public isApprovedForAll;
/*///////////////////////////////////////////////////////////////
VIEW FUNCTION
//////////////////////////////////////////////////////////////*/
function owner() external view returns (address) {
return admin;
}
/*///////////////////////////////////////////////////////////////
ERC-20-LIKE LOGIC
//////////////////////////////////////////////////////////////*/
function transfer(address to, uint256 tokenId) external {
require(msg.sender == ownerOf[tokenId], "NOT_OWNER");
_transfer(msg.sender, to, tokenId);
}
/*///////////////////////////////////////////////////////////////
ERC-721 LOGIC
//////////////////////////////////////////////////////////////*/
function supportsInterface(bytes4 interfaceId) external pure returns (bool supported) {
supported = interfaceId == 0x80ac58cd || interfaceId == 0x5b5e139f;
}
function approve(address spender, uint256 tokenId) external {
address owner_ = ownerOf[tokenId];
require(msg.sender == owner_ || isApprovedForAll[owner_][msg.sender], "NOT_APPROVED");
getApproved[tokenId] = spender;
emit Approval(owner_, spender, tokenId);
}
function setApprovalForAll(address operator, bool approved) external {
isApprovedForAll[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function transferFrom(address from, address to, uint256 tokenId) public {
require(
msg.sender == from
|| msg.sender == getApproved[tokenId]
|| isApprovedForAll[from][msg.sender],
"NOT_APPROVED"
);
_transfer(from, to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId) external {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public {
transferFrom(from, to, tokenId);
if (to.code.length != 0) {
// selector = `onERC721Received(address,address,uint,bytes)`
(, bytes memory returned) = to.staticcall(abi.encodeWithSelector(0x150b7a02,
msg.sender, address(0), tokenId, data));
bytes4 selector = abi.decode(returned, (bytes4));
require(selector == 0x150b7a02, "NOT_ERC721_RECEIVER");
}
}
/*///////////////////////////////////////////////////////////////
INTERNAL UTILS
//////////////////////////////////////////////////////////////*/
function _transfer(address from, address to, uint256 tokenId) internal {
require(ownerOf[tokenId] == from, "not owner");
balanceOf[from]--;
balanceOf[to]++;
delete getApproved[tokenId];
ownerOf[tokenId] = to;
emit Transfer(from, to, tokenId);
}
function _mint(address to, uint256 tokenId) internal {
require(ownerOf[tokenId] == address(0), "ALREADY_MINTED");
totalSupply++;
// This is safe because the sum of all user
// balances can't exceed type(uint256).max!
unchecked {
balanceOf[to]++;
}
ownerOf[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal {
address owner_ = ownerOf[tokenId];
require(ownerOf[tokenId] != address(0), "NOT_MINTED");
totalSupply--;
balanceOf[owner_]--;
delete ownerOf[tokenId];
emit Transfer(owner_, address(0), tokenId);
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity 0.8.7;
interface OrcishLike {
function pull(address owner, uint256[] calldata ids) external;
function manuallyAdjustOrc(uint256 id, uint8 body, uint8 helm, uint8 mainhand, uint8 offhand, uint16 level, uint16 zugModifier, uint32 lvlProgress) external;
function transfer(address to, uint256 tokenId) external;
function orcs(uint256 id) external view returns(uint8 body, uint8 helm, uint8 mainhand, uint8 offhand, uint16 level, uint16 zugModifier, uint32 lvlProgress);
function allies(uint256 id) external view returns (uint8 class, uint16 level, uint32 lvlProgress, uint16 modF, uint8 skillCredits, bytes22 details);
function adjustAlly(uint256 id, uint8 class_, uint16 level_, uint32 lvlProgress_, uint16 modF_, uint8 skillCredits_, bytes22 details_) external;
}
interface PortalLike {
function sendMessage(bytes calldata message_) external;
}
interface OracleLike {
function request() external returns (uint64 key);
function getRandom(uint64 id) external view returns(uint256 rand);
}
interface MetadataHandlerLike {
function getTokenURI(uint16 id, uint8 body, uint8 helm, uint8 mainhand, uint8 offhand, uint16 level, uint16 zugModifier) external view returns (string memory);
}
interface MetadataHandlerAllies {
function getTokenURI(uint256 id_, uint256 class_, uint256 level_, uint256 modF_, uint256 skillCredits_, bytes22 details_) external view returns (string memory);
}
interface RaidsLike {
function stakeManyAndStartCampaign(uint256[] calldata ids_, address owner_, uint256 location_, bool double_) external;
function startCampaignWithMany(uint256[] calldata ids, uint256 location_, bool double_) external;
function commanders(uint256 id) external returns(address);
function unstake(uint256 id) external;
}
interface RaidsLikePoly {
function stakeManyAndStartCampaign(uint256[] calldata ids_, address owner_, uint256 location_, bool double_, uint256[] calldata potions_) external;
function startCampaignWithMany(uint256[] calldata ids, uint256 location_, bool double_, uint256[] calldata potions_) external;
function commanders(uint256 id) external returns(address);
function unstake(uint256 id) external;
}
interface CastleLike {
function pullCallback(address owner, uint256[] calldata ids) external;
}
interface EtherOrcsLike {
function ownerOf(uint256 id) external view returns (address owner_);
function activities(uint256 id) external view returns (address owner, uint88 timestamp, uint8 action);
function orcs(uint256 orcId) external view returns (uint8 body, uint8 helm, uint8 mainhand, uint8 offhand, uint16 level, uint16 zugModifier, uint32 lvlProgress);
}
interface ERC20Like {
function balanceOf(address from) external view returns(uint256 balance);
function burn(address from, uint256 amount) external;
function mint(address from, uint256 amount) external;
function transfer(address to, uint256 amount) external;
}
interface ERC1155Like {
function mint(address to, uint256 id, uint256 amount) external;
function burn(address from, uint256 id, uint256 amount) external;
}
interface ERC721Like {
function transferFrom(address from, address to, uint256 id) external;
function transfer(address to, uint256 id) external;
function ownerOf(uint256 id) external returns (address owner);
function mint(address to, uint256 tokenid) external;
}
interface HallOfChampionsLike {
function joined(uint256 orcId) external view returns (uint256 joinDate);
}
interface AlliesLike {
function allies(uint256 id) external view returns (uint8 class, uint16 level, uint32 lvlProgress, uint16 modF, uint8 skillCredits, bytes22 details);
} | selector = `onERC721Received(address,address,uint,bytes)` | function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public {
transferFrom(from, to, tokenId);
if (to.code.length != 0) {
(, bytes memory returned) = to.staticcall(abi.encodeWithSelector(0x150b7a02,
msg.sender, address(0), tokenId, data));
bytes4 selector = abi.decode(returned, (bytes4));
require(selector == 0x150b7a02, "NOT_ERC721_RECEIVER");
}
}
INTERNAL UTILS
| 617,314 |
./partial_match/1/0xc93Cf2560DCA1DB02D2a4fCCde43e8a34F626d53/sources/contracts/Allowlist.sol | Determines if an address exists in the allowlist. _address The address to check. return Whether the address is allowed at this time. | function isAllowed(address _address) public view returns(bool) {
return allowed[_address] > block.timestamp;
}
| 2,735,322 |
./full_match/42/0x7d57CEbd42C5b08FF769A61BaA709a7a5cFb7446/sources/localhost/IspitniRok.sol | if (address(prijave[rBrPrijave].ispit.profesor)==msg.sender){ | function zavediOcenu(uint rBrPrijave, uint ocena) public returns (bool){
if (!arhiviran)
{
if (prijave[rBrPrijave].izasaoNaIspit==true)
{
prijave[rBrPrijave].ocena=ocena;
prijave[rBrPrijave].student.zavediOcenu(rBrPrijave,ocena);
return true;
}
else
{
return false;
}
}
else {
return false;
}
}
| 9,574,530 |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./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));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
/**
THE DECENTRALISTS
·.::::iiiiiiiiiiiiiiiiiii::::.·
.:::iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii::.·
.::iiiiiiiii:::::..··· ··..:::::iiiiiiiiii::·
.::iiiiiii:::.· .:::iiiiiii::.
.:iiiiiii:: .:iiiiiii:.
·:iiiiii::· ::iiiiii:·
:iiiiii:· ·.::::::::::::::.. :iiiiii:·
:iiiii:: .:::iiiii:::::::::::iiiii:::. .:iiiii:·
:iiiii:· ·::iii:::· .:::iii::· :iiiii:·
·iiiii:· ::iii:· .::ii:: ·:iiiii:
:iiiii: ·:ii::· ·:iii:· .iiiii:
:iiiii· ·:ii:. ·:ii: ·:iiii:
:iiii: ·:ii: ·.:::::::i:::::::.· ·:ii: :iiiii
:iiii: ·iii: .::iiiiiiiiiiiiiiiiii:::· .ii: .iiii:
·iiiii ·iii .:ii:::::::iiiiiiiiiiiiiii::. ·:i:· :iiii:
:iiii: ·:i:· .:iii: .:iiiiiiiiiiiiiiiii:. iii iiiii
:iiii: :ii :iiiii:· ::iiiiiiiiiiiiiiiiiii: ·ii: :iiii:
iiiii· ·ii: ::iiiiii::::::iiiiiiiiiiiiiiiiiiiiii. :ii. ·iiiii
iiiii :ii :iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii:· .ii: :iiii
iiiii :ii .iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii. ii: :iiii
iiiii :ii .iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii:. ii: :iiii
iiiii :ii :iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii:· .ii: :iiii
iiiii· ·ii: ::iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii:. :ii. ·iiiii
:iiii: :ii .:iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii: ·ii: :iiii:
:iiii: ·:i:· ·::iiiiiiiiiiiiiiiiiiiiiiiiiiii:· ii: iiiii
·iiiii iii· ·::iiiiiiiiiiiiiiiiiiiiiii::. .ii:· :iiii:
:iiii: iii: ·:::iiiiiiiiiiiiiiiii:::· :ii: .iiii:
:iiii: :ii:· .::::::::::::::.. .:ii: :iiii:
:iiiii· :iii: .:ii: ·:iiii:
:iiiii: :iii:· .:iii:· .iiiii:
·iiiii:· .:iii:.· ::iii:: ·:iiiii:
:iiiii:· .:iiii::.· ·:::iiii:. :iiiii:·
:iiiii:: ·:::iiiiiii:::::::iiiiiii:::· .:iiiii:·
:iiiiii:· ..:::::::::::..· :iiiiii:·
·:iiiiii::· ::iiiiii:·
.:iiiiiii:: .:iiiiiii:.
.::iiiiiii:::.· .:::iiiiiii::.
.::iiiiiiiii:::::..··· ··..:::::iiiiiiiiii::·
.:::iiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii::.·
·.::::iiiiiiiiiiiiiiiiiii::::.·
A Decentralist is represented by a set of eight traits:
0 - Base
[0] Human Male Black [8] Vampire Male [10] Metahuman Male [12] Ape Male
[1] Human Female Black [9] Vampire Female [11] Metahuman Female
[2] Human Male Dark
[3] Human Female Dark
[4] Human Male Pale
[5] Human Female Pale
[6] Human Male White
[7] Human Female White
1 - Necklace
[0] None [2] Golden
[1] Diamond [3] Silver
2 - Facial Male
[0] None [10] Long Gray [20] Sideburns Blonde
[1] Chivo Black [11] Long Red [21] Sideburns Brown
[2] Chivo Blonde [12] Long White [22] Sideburns Gray
[3] Chivo Brown [13] Regular Black [23] Sideburns Red
[4] Chivo Gray [14] Regular Blonde [24] Sideburns White
[5] Chivo Red [15] Regular Brown
[6] Chivo White [16] Regular Gray
[7] Long Black [17] Regular Red
[8] Long Blonde [18] Regular White
[9] Long Brown [19] Sideburns Black
2 - Facial Female
[0] None
3 - Earring
[0] None [2] Diamond [4] Silver
[1] Cross [3] Golden
4 - Head Male
[0] None [10] CapFront Red [20] Punky Brown [30] Short White
[1] Afro [11] Hat Black [21] Punky Gray [31] Trapper
[2] CapUp Green [12] Long Black [22] Punky Purple [32] Wool Blue
[3] CapUp Red [13] Long Blonde [23] Punky Red [33] Wool Green
[4] Kangaroo Black [14] Long Brown [24] Punky White [34] Wool Red
[5] CapBack Blue [15] Long Gray [25] Short Black
[6] CapBack Orange [16] Long Red [26] Short Blonde
[7] Conspiracist [17] Long White [27] Short Brown
[8] Cop [18] Punky Black [28] Short Gray
[9] CapFront Purple [19] Punky Blonde [29] Short Red
4 - Head Female
[0] None [10] CapFront Red [20] Punky Brown [30] Short White [40] Trapper
[1] Afro [11] Hat Black [21] Punky Gray [31] Straight Black [41] Wool Blue
[2] CapUp Green [12] Long Black [22] Punky Purple [32] Straight Blonde [42] Wool Green
[3] CapUp Red [13] Long Blonde [23] Punky Red [33] Straight Brown [43] Wool Red
[4] Kangaroo Black [14] Long Brown [24] Punky White [34] Straight Gray
[5] CapBack Blue [15] Long Gray [25] Short Black [35] Straight Orange
[6] CapBack Orange [16] Long Red [26] Short Blonde [36] Straight Platinum
[7] Conspiracist [17] Long White [27] Short Brown [37] Straight Purple
[8] Cop [18] Punky Black [28] Short Gray [38] Straight Red
[9] CapFront Purple [19] Punky Blonde [29] Short Red [39] Straight White
5 - Glasses
[0] None [2] Nerd [4] Pilot [6] VR
[1] Beetle [3] Patch [5] Surf
6 - Lipstick Male
[0] None
6 - Lipstick Female
[0] None [2] Orange [4] Purple
[1] Green [3] Pink [5] Red
7 - Smoking
[0] None [2] Cigarette
[1] Cigar [3] E-Cigarette
*/
pragma solidity 0.8.10;
import {ERC721Enumerable} from '../openzeppelin/ERC721Enumerable.sol';
import {ERC721} from '../openzeppelin/ERC721.sol';
import {IERC20} from '../openzeppelin/IERC20.sol';
import {IERC2981} from '../openzeppelin/IERC2981.sol';
import {IERC165} from '../openzeppelin/IERC165.sol';
import {SafeERC20} from '../openzeppelin/SafeERC20.sol';
import {IDescriptor} from './IDescriptor.sol';
contract Decentralists is IERC2981, ERC721Enumerable {
using SafeERC20 for IERC20;
// Minting price of each breed
uint256 public constant MINT_PRICE_HUMAN = 0 ether;
uint256 public constant MINT_PRICE_VAMPIRE = 0.15 ether;
uint256 public constant MINT_PRICE_METAHUMAN = 0.05 ether;
uint256 public constant MINT_PRICE_APE = 0.25 ether;
// Minting price of each breed during presale
uint256 private constant MINT_PRICE_PRESALE_VAMPIRE = 0.12 ether;
uint256 private constant MINT_PRICE_PRESALE_METAHUMAN = 0.04 ether;
uint256 private constant MINT_PRICE_PRESALE_APE = 0.2 ether;
// Maximum total supply during presale
uint24 private constant MAXIMUM_PRESALE_SUPPLY_VAMPIRE = 31;
uint24 private constant MAXIMUM_PRESALE_SUPPLY_METAHUMAN = 21;
uint24 private constant MAXIMUM_PRESALE_SUPPLY_APE = 53;
// Maximum total supply of the collection
uint24 public constant MAXIMUM_TOTAL_SUPPLY = 1000000;
uint24 public constant MAXIMUM_TOTAL_SUPPLY_OF_MALE_HUMAN = 495000;
uint24 public constant MAXIMUM_TOTAL_SUPPLY_OF_FEMALE_HUMAN = 495000;
uint24 public constant MAXIMUM_TOTAL_SUPPLY_OF_MALE_VAMPIRE = 1500;
uint24 public constant MAXIMUM_TOTAL_SUPPLY_OF_FEMALE_VAMPIRE = 1500;
uint24 public constant MAXIMUM_TOTAL_SUPPLY_OF_MALE_METAHUMAN = 3000;
uint24 public constant MAXIMUM_TOTAL_SUPPLY_OF_FEMALE_METAHUMAN = 3000;
uint24 public constant MAXIMUM_TOTAL_SUPPLY_OF_APE = 1000;
// Trait sizes
uint256 private constant TRAIT_BASE_SIZE = 13;
uint256 private constant TRAIT_NECKLACE_SIZE = 4;
uint256 private constant TRAIT_FACIAL_MALE_SIZE = 25;
uint256 private constant TRAIT_FACIAL_FEMALE_SIZE = 1;
uint256 private constant TRAIT_EARRING_SIZE = 5;
uint256 private constant TRAIT_HEAD_MALE_SIZE = 35;
uint256 private constant TRAIT_HEAD_FEMALE_SIZE = 44;
uint256 private constant TRAIT_GLASSES_SIZE = 7;
uint256 private constant TRAIT_LIPSTICK_MALE_SIZE = 1;
uint256 private constant TRAIT_LIPSTICK_FEMALE_SIZE = 6;
uint256 private constant TRAIT_SMOKING_SIZE = 4;
// Base trait separator for each breed
uint256 private constant TRAIT_BASE_HUMAN_SEPARATOR = 8;
uint256 private constant TRAIT_BASE_VAMPIRE_SEPARATOR = 10;
uint256 private constant TRAIT_BASE_METAHUMAN_SEPARATOR = 12;
uint256 private constant TRAIT_BASE_APE_SEPARATOR = 13;
// Governance
address public governance;
address public emergencyAdmin;
// Descriptor
IDescriptor public descriptor;
bool public isDescriptorLocked;
// Royalties
uint256 public royaltyBps;
address public royaltyReceiver;
struct Data {
// Presale ends after 1 week
uint40 presaleStartTime;
// Emergency stop of the claiming process
bool isStopped;
// Decremental counters, from maximum total supply to zero
uint24 count;
uint24 femaleHumans;
uint24 maleHumans;
uint24 femaleVampires;
uint24 maleVampires;
uint24 femaleMetahumans;
uint24 maleMetahumans;
uint24 apes;
}
Data private data;
// Combination of traits
struct Combination {
uint8 base;
uint8 necklace;
uint8 facial;
uint8 earring;
uint8 head;
uint8 glasses;
uint8 lipstick;
uint8 smoking;
}
// Combinations: keccak256(combination) => tokenId
mapping(bytes32 => uint256) private _combinationToId;
// Combinations: tokenId => Combination
mapping(uint256 => Combination) private _idToCombination;
// Mapping of human minters
mapping(address => bool) private _hasMintedHuman;
/**
* @dev Constructor
* @param governance_ address of the governance
* @param emergencyAdmin_ address of the emergency admin
* @param descriptor_ address of the token descriptor
* @param royaltyBps_ value of bps for royalties (e.g. 150 corresponds to 1.50%)
* @param royaltyReceiver_ address of the royalties receiver
* @param initialMintingRecipients_ array of recipients for the initial minting
* @param initialMintingCombinations_ array of combinations for the initial minting
*/
constructor(
address governance_,
address emergencyAdmin_,
address descriptor_,
uint256 royaltyBps_,
address royaltyReceiver_,
address[] memory initialMintingRecipients_,
uint256[8][] memory initialMintingCombinations_
) ERC721('Decentralists', 'DCN') {
governance = governance_;
emergencyAdmin = emergencyAdmin_;
descriptor = IDescriptor(descriptor_);
royaltyBps = royaltyBps_;
royaltyReceiver = royaltyReceiver_;
// Decremental counters
data.count = MAXIMUM_TOTAL_SUPPLY;
data.femaleHumans = MAXIMUM_TOTAL_SUPPLY_OF_FEMALE_HUMAN;
data.maleHumans = MAXIMUM_TOTAL_SUPPLY_OF_MALE_HUMAN;
data.femaleVampires = MAXIMUM_TOTAL_SUPPLY_OF_FEMALE_VAMPIRE;
data.maleVampires = MAXIMUM_TOTAL_SUPPLY_OF_MALE_VAMPIRE;
data.femaleMetahumans = MAXIMUM_TOTAL_SUPPLY_OF_FEMALE_METAHUMAN;
data.maleMetahumans = MAXIMUM_TOTAL_SUPPLY_OF_MALE_METAHUMAN;
data.apes = MAXIMUM_TOTAL_SUPPLY_OF_APE;
// Initial minting
unchecked {
uint256 size = initialMintingRecipients_.length;
for (uint256 i = 0; i < size; i++) {
_claim(initialMintingCombinations_[i], initialMintingRecipients_[i]);
}
}
}
/**
* @notice Mint a token with given traits (array of 8 values)
* @param traits set of traits of the token
*/
function claim(uint256[8] calldata traits) external payable {
require(!data.isStopped, 'CLAIM_STOPPED');
require(!isPresale() && data.presaleStartTime != 0, 'SALE_NOT_ACTIVE');
require(_validateCombination(traits), 'INVALID_COMBINATION');
require(_checkValue(traits[0], false), 'INCORRECT_VALUE');
_claim(traits, msg.sender);
}
/**
* @notice Mint a token with given traits (array of 8 values) during presale
* @param traits set of traits of the token
*/
function presaleClaim(uint256[8] calldata traits) external payable {
require(!data.isStopped, 'CLAIM_STOPPED');
require(isPresale() && data.presaleStartTime != 0, 'PRESALE_NOT_ACTIVE');
require(_validateCombination(traits), 'INVALID_COMBINATION');
require(!_humanBase(traits[0]), 'HUMANS_NOT_AVAILABLE');
require(_checkValue(traits[0], true), 'INCORRECT_VALUE');
// Check breed counter during presale
if (_vampireBase(traits[0])) {
require(
totalFemaleVampiresSupply() + totalMaleVampiresSupply() < MAXIMUM_PRESALE_SUPPLY_VAMPIRE,
'NO_CLAIMS_AVAILABLE'
);
} else if (_metahumanBase(traits[0])) {
require(
totalFemaleMetahumansSupply() + totalMaleMetahumansSupply() <
MAXIMUM_PRESALE_SUPPLY_METAHUMAN,
'NO_CLAIMS_AVAILABLE'
);
} else {
require(totalApesSupply() < MAXIMUM_PRESALE_SUPPLY_APE, 'NO_CLAIMS_AVAILABLE');
}
_claim(traits, msg.sender);
}
/**
* @notice Returns whether the combination given is available or not
* @param traits set of traits of the combination
* @return true if the combination is available, false otherwise
*/
function isCombinationAvailable(uint256[8] calldata traits) external view returns (bool) {
require(_validateCombination(traits), 'INVALID_COMBINATION');
bytes32 hashedCombination = keccak256(
abi.encodePacked(
traits[0], // base
traits[1], // necklace
traits[2], // facial
traits[3], // earring
traits[4], // head
traits[5], // glasses
traits[6], // lipstick
traits[7] // smoking
)
);
return _combinationToId[hashedCombination] == 0;
}
/**
* @notice Returns whether the combination given is valid or not
* @param traits set of traits of the combination to validate
* @return true if the combination is valid, false otherwise
*/
function isCombinationValid(uint256[8] calldata traits) external pure returns (bool) {
return _validateCombination(traits);
}
/**
* @notice Returns whether the presale is active or not (1 week duration)
* @return true if the presale is active, false otherwise
*/
function isPresale() public view returns (bool) {
return block.timestamp <= data.presaleStartTime + 1 weeks;
}
/**
* @notice Returns whether the claiming process is stopped or not
* @return true if the claiming process is stop, false otherwise
*/
function isEmergencyStopped() external view returns (bool) {
return data.isStopped;
}
/**
* @notice Returns the token id of a given set of traits
* @param traits set of traits of the token
* @return token id
*/
function getTokenId(uint256[8] calldata traits) external view returns (uint256) {
bytes32 hashedCombination = keccak256(
abi.encodePacked(
traits[0], // base
traits[1], // necklace
traits[2], // facial
traits[3], // earring
traits[4], // head
traits[5], // glasses
traits[6], // lipstick
traits[7] // smoking
)
);
require(_combinationToId[hashedCombination] != 0, 'NOT_EXISTS');
return _combinationToId[hashedCombination];
}
/**
* @notice Returns the set of traits given a token id
* @param tokenId the id of the token
* @return traits array
*/
function getTraits(uint256 tokenId) external view returns (uint256[8] memory) {
require(_exists(tokenId), 'NOT_EXISTS');
return _getTraits(tokenId);
}
/**
* @notice Returns the set of traits given a token id
* @param tokenId the id of the token
* @return traits array
*/
function _getTraits(uint256 tokenId) internal view returns (uint256[8] memory traits) {
Combination memory c = _idToCombination[tokenId];
traits[0] = c.base;
traits[1] = c.necklace;
traits[2] = c.facial;
traits[3] = c.earring;
traits[4] = c.head;
traits[5] = c.glasses;
traits[6] = c.lipstick;
traits[7] = c.smoking;
}
/**
* @notice Returns the Uniform Resource Identifier (URI) for `tokenId` token
* @param tokenId token id
* @return uri of the given `tokenId`
*/
function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) {
require(_exists(tokenId), 'NOT_EXISTS');
return descriptor.tokenURI(_getTraits(tokenId));
}
/**
* @notice Returns whether the given address of the user has already minted a human or not
* @param user address of the user
* @return true if `user` has minted a human, false otherwise
*/
function hasMintedHuman(address user) external view returns (bool) {
return _hasMintedHuman[user];
}
/**
* @notice Returns the total amount of female human tokens
* @return total supply of female humans
*/
function totalFemaleHumansSupply() public view returns (uint256) {
return MAXIMUM_TOTAL_SUPPLY_OF_FEMALE_HUMAN - data.femaleHumans;
}
/**
* @notice Returns the total amount of male human tokens
* @return total supply of male humans
*/
function totalMaleHumansSupply() public view returns (uint256) {
return MAXIMUM_TOTAL_SUPPLY_OF_MALE_HUMAN - data.maleHumans;
}
/**
* @notice Returns the total amount of female vampire tokens
* @return total supply of female vampires
*/
function totalFemaleVampiresSupply() public view returns (uint256) {
return MAXIMUM_TOTAL_SUPPLY_OF_FEMALE_VAMPIRE - data.femaleVampires;
}
/**
* @notice Returns the total amount of male vampire tokens
* @return total supply of male vampires
*/
function totalMaleVampiresSupply() public view returns (uint256) {
return MAXIMUM_TOTAL_SUPPLY_OF_MALE_VAMPIRE - data.maleVampires;
}
/**
* @notice Returns the total amount of female metahuman tokens
* @return total supply of female metahumans
*/
function totalFemaleMetahumansSupply() public view returns (uint256) {
return MAXIMUM_TOTAL_SUPPLY_OF_FEMALE_METAHUMAN - data.femaleMetahumans;
}
/**
* @notice Returns the total amount of male metahuman tokens
* @return total supply of male metahumans
*/
function totalMaleMetahumansSupply() public view returns (uint256) {
return MAXIMUM_TOTAL_SUPPLY_OF_MALE_METAHUMAN - data.maleMetahumans;
}
/**
* @notice Returns the total amount of ape tokens
* @return total supply of apes
*/
function totalApesSupply() public view returns (uint256) {
return MAXIMUM_TOTAL_SUPPLY_OF_APE - data.apes;
}
/**
* @notice Returns the starting time of the presale (0 if it did not start yet)
* @return starting time of the presale
*/
function presaleStartTime() external view returns (uint256) {
return uint256(data.presaleStartTime);
}
/**
* @notice Returns how much royalty is owed and to whom, based on the sale price
* @param tokenId token id of the NFT asset queried for royalty information
* @param salePrice sale price of the NFT asset specified by `tokenId`
* @return receiver address of the royalty payment
* @return amount of the royalty payment for `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
override(IERC2981)
returns (address, uint256)
{
require(_exists(tokenId), 'NOT_EXISTS');
return (royaltyReceiver, (salePrice * royaltyBps) / 10000);
}
/**
* @dev Checks if the contract supports the given interface
* @param interfaceId The identifier of the interface
* @return True if the interface is supported, false otherwise
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Enumerable, IERC165)
returns (bool)
{
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @notice Activate the presale
* @dev Only callable by governance
*/
function startPresale() external onlyGovernance {
require(data.presaleStartTime == 0, 'PRESALE_ALREADY_STARTED');
data.presaleStartTime = uint40(block.timestamp);
emit PresaleStart();
}
/**
* @notice Pull ETH funds from the contract to the given recipient
* @dev Only callable by governance
* @param recipient address to transfer the funds to
* @param amount amount of funds to transfer
*/
function pullFunds(address recipient, uint256 amount) external onlyGovernance {
(bool success, ) = recipient.call{value: amount}('');
require(success, 'UNABLE_TO_PULL');
emit FundsWithdrawal(recipient, amount);
}
/**
* @notice Pull ERC20 token funds from the contract to the given recipient
* @dev Only callable by governance
* @param asset address of the ERC20 token to transfer
* @param recipient address to transfer the funds to
* @param amount amount of funds to transfer
*/
function pullTokens(
address asset,
address recipient,
uint256 amount
) external onlyGovernance {
IERC20(asset).safeTransfer(recipient, amount);
}
/**
* @notice Update the governance address
* @dev Only callable by governance
* @param newGovernance address of the new governance
*/
function setGovernance(address newGovernance) external onlyGovernance {
address oldGovernance = governance;
governance = newGovernance;
emit GovernanceUpdate(oldGovernance, newGovernance);
}
/**
* @notice Update the descriptor address
* @dev Only callable by governance when descriptor is not locked
* @param newDescriptor address of the new descriptor
*/
function setDescriptor(address newDescriptor) external onlyGovernance whenDescriptorNotLocked {
address oldDescriptor = address(descriptor);
descriptor = IDescriptor(newDescriptor);
emit DescriptorUpdate(oldDescriptor, newDescriptor);
}
/**
* @notice Lock the ability to update the descriptor address
* @dev Only callable by governance when descriptor is not locked
*/
function lockDescriptor() external onlyGovernance whenDescriptorNotLocked {
isDescriptorLocked = true;
emit DescriptorLock(address(descriptor));
}
/**
* @notice Update the royalty basis points (e.g. a value of 150 corresponds to 1.50%)
* @dev Only callable by governance
* @param newRoyaltyBps value of the new royalty bps
*/
function setRoyaltyBps(uint256 newRoyaltyBps) external onlyGovernance {
uint256 oldRoyaltyBps = royaltyBps;
royaltyBps = newRoyaltyBps;
emit RoyaltyBpsUpdate(oldRoyaltyBps, newRoyaltyBps);
}
/**
* @notice Update the royalty receiver
* @dev Only callable by governance
* @param newRoyaltyReceiver address of the new royalty receiver
*/
function setRoyaltyReceiver(address newRoyaltyReceiver) external onlyGovernance {
address oldRoyaltyReceiver = royaltyReceiver;
royaltyReceiver = newRoyaltyReceiver;
emit RoyaltyReceiverUpdate(oldRoyaltyReceiver, newRoyaltyReceiver);
}
/**
* @notice Stops the claiming process of the contract in case of emergency
* @dev Only callable by emergency admin
* @param isStopped true to stop the claiming process, false otherwise
*/
function emergencyStop(bool isStopped) external {
require(msg.sender == emergencyAdmin, 'ONLY_BY_EMERGENCY_ADMIN');
data.isStopped = isStopped;
emit EmergencyStop(isStopped);
}
/**
* @notice Update the emergency admin address
* @dev Only callable by emergency admin
* @param newEmergencyAdmin address of the new emergency admin
*/
function setEmergencyAdmin(address newEmergencyAdmin) external {
require(msg.sender == emergencyAdmin, 'ONLY_BY_EMERGENCY_ADMIN');
address oldEmergencyAdmin = emergencyAdmin;
emergencyAdmin = newEmergencyAdmin;
emit EmergencyAdminUpdate(oldEmergencyAdmin, newEmergencyAdmin);
}
/**
* @notice Mint a token to the receiver
* @param traits set of traits of the token
* @param receiver receiver address
*/
function _claim(uint256[8] memory traits, address receiver) internal {
require(msg.sender == tx.origin, 'ONLY_EOA');
require(data.count > 0, 'NO_CLAIMS_AVAILABLE');
uint256 base = traits[0];
bytes32 hashedCombination = keccak256(
abi.encodePacked(
base, // base
traits[1], // necklace
traits[2], // facial
traits[3], // earring
traits[4], // head
traits[5], // glasses
traits[6], // lipstick
traits[7] // smoking
)
);
require(_combinationToId[hashedCombination] == 0, 'ALREADY_EXISTS');
if (_humanBase(base)) {
require(!_hasMintedHuman[msg.sender], 'INVALID_HUMAN_MINTER');
_hasMintedHuman[msg.sender] = true;
}
// TokenId (0 is reserved)
uint256 tokenId = MAXIMUM_TOTAL_SUPPLY - data.count + 1;
// Update breed counter
if (_humanBase(base)) {
if (_isMale(base)) {
data.maleHumans--;
} else {
data.femaleHumans--;
}
} else if (_vampireBase(base)) {
if (_isMale(base)) {
data.maleVampires--;
} else {
data.femaleVampires--;
}
} else if (_metahumanBase(base)) {
if (_isMale(base)) {
data.maleMetahumans--;
} else {
data.femaleMetahumans--;
}
} else {
data.apes--;
}
data.count--;
// Traits
_combinationToId[hashedCombination] = tokenId;
_idToCombination[tokenId] = Combination({
base: uint8(base),
necklace: uint8(traits[1]),
facial: uint8(traits[2]),
earring: uint8(traits[3]),
head: uint8(traits[4]),
glasses: uint8(traits[5]),
lipstick: uint8(traits[6]),
smoking: uint8(traits[7])
});
_mint(receiver, tokenId);
emit DecentralistMint(tokenId, receiver, traits);
}
/**
* @notice Check the transaction value is correct given a base and whether the presale is active
* @param base value of the base trait
* @param inPresale true if presale is active, false otherwise
* @return true if the transaction value is correct, false otherwise
*/
function _checkValue(uint256 base, bool inPresale) internal view returns (bool) {
if (_humanBase(base)) {
return msg.value == MINT_PRICE_HUMAN;
} else if (_vampireBase(base)) {
return inPresale ? msg.value == MINT_PRICE_PRESALE_VAMPIRE : msg.value == MINT_PRICE_VAMPIRE;
} else if (_metahumanBase(base)) {
return
inPresale ? msg.value == MINT_PRICE_PRESALE_METAHUMAN : msg.value == MINT_PRICE_METAHUMAN;
} else if (_apeBase(base)) {
return inPresale ? msg.value == MINT_PRICE_PRESALE_APE : msg.value == MINT_PRICE_APE;
} else {
return false;
}
}
/**
* @notice Check whether a set of traits is a valid combination or not
* @dev Even numbers of base trait corresponds to male
* @param traits set of traits of the token
* @return true if it is a valid combination, false otherwise
*/
function _validateCombination(uint256[8] calldata traits) internal pure returns (bool) {
bool isMale = _isMale(traits[0]);
if (
isMale &&
traits[0] < TRAIT_BASE_SIZE &&
traits[1] < TRAIT_NECKLACE_SIZE &&
traits[2] < TRAIT_FACIAL_MALE_SIZE &&
traits[3] < TRAIT_EARRING_SIZE &&
traits[4] < TRAIT_HEAD_MALE_SIZE &&
traits[5] < TRAIT_GLASSES_SIZE &&
traits[6] < TRAIT_LIPSTICK_MALE_SIZE &&
traits[7] < TRAIT_SMOKING_SIZE
) {
return true;
} else if (
!isMale &&
traits[0] < TRAIT_BASE_SIZE &&
traits[1] < TRAIT_NECKLACE_SIZE &&
traits[2] < TRAIT_FACIAL_FEMALE_SIZE &&
traits[3] < TRAIT_EARRING_SIZE &&
traits[4] < TRAIT_HEAD_FEMALE_SIZE &&
traits[5] < TRAIT_GLASSES_SIZE &&
traits[6] < TRAIT_LIPSTICK_FEMALE_SIZE &&
traits[7] < TRAIT_SMOKING_SIZE
) {
return true;
} else {
return false;
}
}
/**
* @notice Returns true if the base trait corresponds to human breed
* @param base value of the base trait
* @return True if the base corresponds to human breed, false otherwise
*/
function _humanBase(uint256 base) internal pure returns (bool) {
return base < TRAIT_BASE_HUMAN_SEPARATOR;
}
/**
* @notice Returns true if the base trait corresponds to vampire breed
* @param base value of the base trait
* @return True if the base corresponds to vampire breed, false otherwise
*/
function _vampireBase(uint256 base) internal pure returns (bool) {
return base >= TRAIT_BASE_HUMAN_SEPARATOR && base < TRAIT_BASE_VAMPIRE_SEPARATOR;
}
/**
* @notice Returns true if the base trait corresponds to metahuman breed
* @param base value of the base trait
* @return True if the base corresponds to metahuman breed, false otherwise
*/
function _metahumanBase(uint256 base) internal pure returns (bool) {
return base >= TRAIT_BASE_VAMPIRE_SEPARATOR && base < TRAIT_BASE_METAHUMAN_SEPARATOR;
}
/**
* @notice Returns true if the base trait corresponds to ape breed
* @param base value of the base trait
* @return True if the base corresponds to ape breed, false otherwise
*/
function _apeBase(uint256 base) internal pure returns (bool) {
return base >= TRAIT_BASE_METAHUMAN_SEPARATOR && base < TRAIT_BASE_APE_SEPARATOR;
}
/**
* @notice Returns true if the base trait corresponds to male sex
* @param base value of the base trait
* @return True if the base corresponds to male sex, false otherwise
*/
function _isMale(uint256 base) internal pure returns (bool) {
return base % 2 == 0;
}
/**
* @dev Hook that is called before any transfer of tokens
* @param from origin address of the transfer
* @param to recipient address of the transfer
* @param tokenId id of the token to transfer
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(ERC721Enumerable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev Functions marked by this modifier can only be called when descriptor is not locked
**/
modifier whenDescriptorNotLocked() {
require(!isDescriptorLocked, 'DESCRIPTOR_LOCKED');
_;
}
/**
* @dev Functions marked by this modifier can only be called by governance
**/
modifier onlyGovernance() {
require(msg.sender == governance, 'ONLY_BY_GOVERNANCE');
_;
}
/**
* @dev Emitted when a new token is minted
* @param tokenId token id
* @param recipient address of the recipient of the token
* @param traits set of traits of the token
*/
event DecentralistMint(uint256 indexed tokenId, address indexed recipient, uint256[8] traits);
/**
* @dev Emitted when the presale starts
*/
event PresaleStart();
/**
* @dev Emitted when funds are withdraw
* @param recipient address of the recipient of the funds
* @param amount amount of the funds withdraw
*/
event FundsWithdrawal(address indexed recipient, uint256 amount);
/**
* @dev Emitted when the governance address is updated
* @param oldGovernance address of the old governance
* @param newGovernance address of the new governance
*/
event GovernanceUpdate(address indexed oldGovernance, address indexed newGovernance);
/**
* @dev Emitted when the emergency admin stops the claiming process
* @param isStopped true if it is stopped, false otherwise
*/
event EmergencyStop(bool isStopped);
/**
* @dev Emitted when the emergency admin address is updated
* @param oldEmergencyAdmin address of the old emergency admin
* @param newEmergencyAdmin address of the new emergency admin
*/
event EmergencyAdminUpdate(address indexed oldEmergencyAdmin, address indexed newEmergencyAdmin);
/**
* @dev Emitted when the descriptor address is updated
* @param oldDescriptor address of the old descriptor
* @param newDescriptor address of the new descriptor
*/
event DescriptorUpdate(address indexed oldDescriptor, address indexed newDescriptor);
/**
* @dev Emitted when the descriptor is locked
* @param descriptor address of the descriptor
*/
event DescriptorLock(address indexed descriptor);
/**
* @dev Emitted when the royalty bps value is updated
* @param oldRoyaltyBps old value of the royalty bps
* @param newRoyaltyBps new value of the royalty bps
*/
event RoyaltyBpsUpdate(uint256 oldRoyaltyBps, uint256 newRoyaltyBps);
/**
* @dev Emitted when the royalty receiver is updated
* @param oldRoyaltyReceiver address of the old royalty receiver
* @param newRoyaltyReceiver address of the new royalty receiver
*/
event RoyaltyReceiverUpdate(
address indexed oldRoyaltyReceiver,
address indexed newRoyaltyReceiver
);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "./ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./IERC721Metadata.sol";
import "./Address.sol";
import "./Context.sol";
import "./Strings.sol";
import "./ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = 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);
_afterTokenTransfer(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);
_afterTokenTransfer(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 from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(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 Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `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 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165.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 IERC2981 is IERC165 {
/**
* @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 (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.10;
interface IDescriptor {
function tokenURI(uint256[8] calldata) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// 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 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
pragma solidity 0.8.10;
/**
* @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;
}
} | Returns the set of traits given a token id tokenId the id of the token return traits array/ | function _getTraits(uint256 tokenId) internal view returns (uint256[8] memory traits) {
Combination memory c = _idToCombination[tokenId];
traits[0] = c.base;
traits[1] = c.necklace;
traits[2] = c.facial;
traits[3] = c.earring;
traits[4] = c.head;
traits[5] = c.glasses;
traits[6] = c.lipstick;
traits[7] = c.smoking;
}
| 12,005,994 |
./full_match/80001/0x38a043BAd4F996fB5d2c13b725502524A68BBb24/sources/contracts/OverridableDrop.sol | Checks a request to claim NFTs against the active claim condition's criteria. At any given moment, returns the uid for the active claim condition. | function verifyClaim(
uint256 _conditionId,
address _claimer,
uint256 _category,
uint256 _quantity,
address _currency,
uint256 _pricePerToken,
AllowlistProofWithCategory calldata _allowlistProof
) public virtual returns (bool isOverride);
function getActiveClaimConditionId() public view returns (uint256) {
for (uint256 i = claimCondition.currentStartId + claimCondition.count; i > claimCondition.currentStartId; i--) {
if (block.timestamp >= claimCondition.conditions[i - 1].startTimestamp) {
return i - 1;
}
}
revert("!CONDITION.");
}
| 9,521,247 |
pragma solidity ^0.5.5;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @title 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];
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract SupporterRole is Context {
using Roles for Roles.Role;
event SupporterAdded(address indexed account);
event SupporterRemoved(address indexed account);
Roles.Role private _supporters;
constructor () internal {
_addSupporter(_msgSender());
}
modifier onlySupporter() {
require(isSupporter(_msgSender()), "SupporterRole: caller does not have the Supporter role");
_;
}
function isSupporter(address account) public view returns (bool) {
return _supporters.has(account);
}
function addSupporter(address account) public onlySupporter {
_addSupporter(account);
}
function renounceSupporter() public {
_removeSupporter(_msgSender());
}
function _addSupporter(address account) internal {
_supporters.add(account);
emit SupporterAdded(account);
}
function _removeSupporter(address account) internal {
_supporters.remove(account);
emit SupporterRemoved(account);
}
}
contract PauserRole is Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(_msgSender());
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
/**
* @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.
*/
contract Pausable is Context, PauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() internal 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() internal 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;
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev A Secondary contract can only be used by its primary account (the one that created it).
*/
contract Secondary is Context {
address private _primary;
/**
* @dev Emitted when the primary contract changes.
*/
event PrimaryTransferred(
address recipient
);
/**
* @dev Sets the primary account to the one that is creating the Secondary contract.
*/
constructor () internal {
address msgSender = _msgSender();
_primary = msgSender;
emit PrimaryTransferred(msgSender);
}
/**
* @dev Reverts if called from any account other than the primary.
*/
modifier onlyPrimary() {
require(_msgSender() == _primary, "Secondary: caller is not the primary account");
_;
}
/**
* @return the address of the primary.
*/
function primary() public view returns (address) {
return _primary;
}
/**
* @dev Transfers contract to a new primary.
* @param recipient The address of new primary.
*/
function transferPrimary(address recipient) public onlyPrimary {
require(recipient != address(0), "Secondary: new primary is the zero address");
_primary = recipient;
emit PrimaryTransferred(recipient);
}
}
/**
* @title __unstable__TokenVault
* @dev Similar to an Escrow for tokens, this contract allows its primary account to spend its tokens as it sees fit.
* This contract is an internal helper for PostDeliveryCrowdsale, and should not be used outside of this context.
*/
// solhint-disable-next-line contract-name-camelcase
contract __unstable__TokenVault is Secondary {
function transferToken(IERC20 token, address to, uint256 amount) public onlyPrimary {
token.transfer(to, amount);
}
function transferFunds(address payable to, uint256 amount) public onlyPrimary {
require (address(this).balance >= amount);
to.transfer(amount);
}
function () external payable {}
}
/**
* @title MoonStaking
*/
contract MoonStaking is Ownable, Pausable, SupporterRole, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
struct Pool {
uint256 rate;
uint256 adapter;
uint256 totalStaked;
}
struct User {
mapping(address => UserSp) tokenPools;
UserSp ePool;
}
struct UserSp {
uint256 staked;
uint256 lastRewardTime;
uint256 earned;
}
mapping(address => User) users;
mapping(address => Pool) pools;
// The MOON TOKEN!
IERC20 public moon;
uint256 eRate;
uint256 eAdapter;
uint256 eTotalStaked;
__unstable__TokenVault private _vault;
/**
* @param _moon The MOON token.
*/
constructor(IERC20 _moon) public {
_vault = new __unstable__TokenVault();
moon = _moon;
}
/**
* @dev Update token pool rate
* @return True when successful
*/
function updatePoolRate(address pool, uint256 _rate, uint256 _adapter)
public onlyOwner returns (bool) {
pools[pool].rate = _rate;
pools[pool].adapter = _adapter;
return true;
}
/**
* @dev Update epool pool rate
* @return True when successful
*/
function updateEpoolRate(uint256 _rate, uint256 _adapter)
public onlyOwner returns (bool) {
eRate = _rate;
eAdapter = _adapter;
return true;
}
/**
* @dev Checks whether the pool is available.
* @return Whether the pool is available.
*/
function isPoolAvailable(address pool) public view returns (bool) {
return pools[pool].rate != 0;
}
/**
* @dev View pool token info
* @param _pool Token address.
* @return Pool info
*/
function poolTokenInfo(address _pool) public view returns (
uint256 rate,
uint256 adapter,
uint256 totalStaked
) {
Pool storage pool = pools[_pool];
return (pool.rate, pool.adapter, pool.totalStaked);
}
/**
* @dev View pool E info
* @return Pool info
*/
function poolInfo(address poolAddress) public view returns (
uint256 rate,
uint256 adapter,
uint256 totalStaked
) {
Pool storage sPool = pools[poolAddress];
return (sPool.rate, sPool.adapter, sPool.totalStaked);
}
/**
* @dev View pool E info
* @return Pool info
*/
function poolEInfo() public view returns (
uint256 rate,
uint256 adapter,
uint256 totalStaked
) {
return (eRate, eAdapter, eTotalStaked);
}
/**
* @dev Get earned reward in e pool.
*/
function getEarnedEpool() public view returns (uint256) {
UserSp storage pool = users[_msgSender()].ePool;
return _getEarned(eRate, eAdapter, pool);
}
/**
* @dev Get earned reward in t pool.
*/
function getEarnedTpool(address stakingPoolAddress) public view returns (uint256) {
UserSp storage stakingPool = users[_msgSender()].tokenPools[stakingPoolAddress];
Pool storage pool = pools[stakingPoolAddress];
return _getEarned(pool.rate, pool.adapter, stakingPool);
}
/**
* @dev Stake with E
* @return true if successful
*/
function stakeE() public payable returns (bool) {
uint256 _value = msg.value;
require(_value != 0, "Zero amount");
address(uint160((address(_vault)))).transfer(_value);
UserSp storage ePool = users[_msgSender()].ePool;
ePool.earned = ePool.earned.add(_getEarned(eRate, eAdapter, ePool));
ePool.lastRewardTime = block.timestamp;
ePool.staked = ePool.staked.add(_value);
eTotalStaked = eTotalStaked.add(_value);
return true;
}
/**
* @dev Stake with tokens
* @param _value Token amount.
* @param token Token address.
* @return true if successful
*/
function stake(uint256 _value, IERC20 token) public returns (bool) {
require(token.balanceOf(_msgSender()) >= _value, "Insufficient Funds");
require(token.allowance(_msgSender(), address(this)) >= _value, "Insufficient Funds Approved");
address tokenAddress = address(token);
require(isPoolAvailable(tokenAddress), "Pool is not available");
_forwardFundsToken(token, _value);
Pool storage pool = pools[tokenAddress];
UserSp storage tokenPool = users[_msgSender()].tokenPools[tokenAddress];
tokenPool.earned = tokenPool.earned.add(_getEarned(pool.rate, pool.adapter, tokenPool));
tokenPool.lastRewardTime = block.timestamp;
tokenPool.staked = tokenPool.staked.add(_value);
pool.totalStaked = pool.totalStaked.add(_value);
return true;
}
/**
* @dev Withdraw all available tokens.
*/
function withdrawTokenPool(address token) public whenNotPaused nonReentrant returns (bool) {
UserSp storage tokenStakingPool = users[_msgSender()].tokenPools[token];
require(tokenStakingPool.staked > 0 != tokenStakingPool.earned > 0, "Not available");
if (tokenStakingPool.earned > 0) {
Pool storage pool = pools[token];
_vault.transferToken(moon, _msgSender(), _getEarned(pool.rate, pool.adapter, tokenStakingPool));
tokenStakingPool.lastRewardTime = block.timestamp;
tokenStakingPool.earned = 0;
}
if (tokenStakingPool.staked > 0) {
_vault.transferToken(IERC20(token), _msgSender(), tokenStakingPool.staked);
tokenStakingPool.staked = 0;
}
return true;
}
/**
* @dev Withdraw all available tokens.
*/
function withdrawEPool() public whenNotPaused nonReentrant returns (bool) {
UserSp storage eStakingPool = users[_msgSender()].ePool;
require(eStakingPool.staked > 0 != eStakingPool.earned > 0, "Not available");
if (eStakingPool.earned > 0) {
_vault.transferToken(moon, _msgSender(), _getEarned(eRate, eAdapter, eStakingPool));
eStakingPool.lastRewardTime = block.timestamp;
eStakingPool.earned = 0;
}
if (eStakingPool.staked > 0) {
_vault.transferFunds(_msgSender(), eStakingPool.staked);
eStakingPool.staked = 0;
}
return true;
}
/**
* @dev Claim earned Moon.
*/
function claimMoonInTpool(address token) public whenNotPaused returns (bool) {
UserSp storage tokenStakingPool = users[_msgSender()].tokenPools[token];
require(tokenStakingPool.staked > 0 != tokenStakingPool.earned > 0, "Not available");
Pool storage pool = pools[token];
_vault.transferToken(moon, _msgSender(), _getEarned(pool.rate, pool.adapter, tokenStakingPool));
tokenStakingPool.lastRewardTime = block.timestamp;
tokenStakingPool.earned = 0;
return true;
}
/**
* @dev Claim earned Moon.
*/
function claimMoonInEpool() public whenNotPaused returns (bool) {
UserSp storage eStakingPool = users[_msgSender()].ePool;
require(eStakingPool.staked > 0 != eStakingPool.earned > 0, "Not available");
_vault.transferToken(moon, _msgSender(), _getEarned(eRate, eAdapter, eStakingPool));
eStakingPool.lastRewardTime = block.timestamp;
eStakingPool.earned = 0;
return true;
}
/**
* @dev Get reserved token.
*/
function getReserved() public view onlyOwner
returns (uint256 vaultTokens, uint256 vaultFunds) {
address vaultAddress = address(_vault);
vaultTokens = moon.balanceOf(vaultAddress);
vaultFunds = address(uint160(vaultAddress)).balance;
}
/**
* @dev Get reserved token by address.
*/
function getReservedByAddress(IERC20 token) public view onlyOwner returns (uint256) {
return token.balanceOf(address(_vault));
}
/**
* @dev Supply token for the vaults.
* @param amount Supply amount
*/
function supplyVault(uint256 amount)
public onlyOwner
returns (bool) {
moon.transferFrom(_msgSender(), address(_vault), amount);
return true;
}
/**
* @dev deprive tokens from vaults.
* @param vault Vault address
* @param amount The amount
*/
function depriveToken(address vault, IERC20 token, uint256 amount)
public onlyOwner returns (bool) {
_vault.transferToken(token, vault, amount);
return true;
}
/**
* @dev deprive funds from vaults.
* @param vault Vault address
* @param amount The amount
*/
function depriveFunds(address payable vault, uint256 amount)
public onlyOwner
returns (bool) {
_vault.transferFunds(vault, amount);
return true;
}
/**
* @dev Fallback function
*/
function () external payable {
address(uint160((address(_vault)))).transfer(msg.value);
}
/**
* @dev Extend parent behavior
* @param erc20Token ERC20 Token
* @param _value Amount contributed
*/
function _forwardFundsToken(IERC20 erc20Token, uint256 _value) internal {
erc20Token.transferFrom(_msgSender(), address(_vault), _value);
}
/**
* @dev Get earned reward.
*/
function _getEarned(uint256 rate, uint256 adapter, UserSp memory stakingPool) internal view returns (uint256) {
uint256 moonPerSec = stakingPool.staked.mul(rate).div(adapter);
return block.timestamp.sub(stakingPool.lastRewardTime).mul(moonPerSec).add(stakingPool.earned);
}
} | View pool token info _pool Token address. return Pool info/ | function poolTokenInfo(address _pool) public view returns (
uint256 rate,
uint256 adapter,
uint256 totalStaked
) {
Pool storage pool = pools[_pool];
return (pool.rate, pool.adapter, pool.totalStaked);
}
| 6,159,413 |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "./events.sol";
import "../../../../infiniteProxy/IProxy.sol";
contract RebalancerModule is Events {
using SafeERC20 for IERC20;
/**
* @dev Only rebalancer gaurd.
*/
modifier onlyRebalancer() {
require(
_isRebalancer[msg.sender] ||
IProxy(address(this)).getAdmin() == msg.sender,
"only rebalancer"
);
_;
}
/**
* @dev low gas function just to collect profit.
* @notice Collected the profit & leave it in the DSA itself to optimize further on gas.
*/
function collectProfit(
bool isWeth, // either weth or steth
uint256 withdrawAmt_,
uint256 amt_,
uint256 unitAmt_,
uint256 oneInchData_
) external nonReentrant onlyRebalancer {
uint256 profits_ = getNewProfits();
require(amt_ <= profits_, "amount-exceeds-profit");
uint256 length_ = 1;
if (withdrawAmt_ > 0) length_++;
string[] memory targets_ = new string[](length_);
bytes[] memory calldata_ = new bytes[](length_);
address sellToken_ = isWeth
? address(wethContract)
: address(stethContract);
uint256 maxAmt_ = (getStethCollateralAmount() * _idealExcessAmt) /
10000;
if (withdrawAmt_ > 0) {
if (isWeth) {
targets_[0] = "AAVE-V2-A";
calldata_[0] = abi.encodeWithSignature(
"borrow(address,uint256,uint256,uint256,uint256)",
address(wethContract),
withdrawAmt_,
2,
0,
0
);
} else {
targets_[0] = "AAVE-V2-A";
calldata_[0] = abi.encodeWithSignature(
"withdraw(address,uint256,uint256,uint256)",
address(stethContract),
withdrawAmt_,
0,
0
);
}
}
targets_[length_ - 1] = "1INCH-A";
calldata_[length_ - 1] = abi.encodeWithSignature(
"sell(address,address,uint256,uint256,bytes,uint256)",
_token,
sellToken_,
amt_,
unitAmt_,
oneInchData_,
0
);
_vaultDsa.cast(targets_, calldata_, address(this));
if (withdrawAmt_ > 0)
require(
IERC20(sellToken_).balanceOf(address(_vaultDsa)) <= maxAmt_,
"withdrawal-exceeds-max-limit"
);
emit collectProfitLog(isWeth, withdrawAmt_, amt_, unitAmt_);
}
struct RebalanceOneVariables {
bool isOk;
uint256 i;
uint256 j;
uint256 length;
string[] targets;
bytes[] calldatas;
bool criticalIsOk;
bool minIsOk;
}
/**
* @dev Rebalancer function to leverage and rebalance the position.
*/
function rebalanceOne(
address flashTkn_,
uint256 flashAmt_,
uint256 route_,
address[] memory vaults_, // leverage using other vaults
uint256[] memory amts_,
uint256 leverageAmt_,
uint256 swapAmt_, // 1inch's swap amount
uint256 tokenSupplyAmt_,
uint256 tokenWithdrawAmt_,
uint256 unitAmt_,
bytes memory oneInchData_
) external nonReentrant onlyRebalancer {
if (leverageAmt_ < 1e14) leverageAmt_ = 0;
if (tokenWithdrawAmt_ < _tokenMinLimit) tokenWithdrawAmt_ = 0;
if (tokenSupplyAmt_ >= _tokenMinLimit)
_token.safeTransfer(address(_vaultDsa), tokenSupplyAmt_);
RebalanceOneVariables memory v_;
v_.isOk = validateLeverageAmt(vaults_, amts_, leverageAmt_, swapAmt_);
require(v_.isOk, "swap-amounts-are-not-proper");
v_.length = amts_.length;
uint256 tokenDsaBal_ = _token.balanceOf(address(_vaultDsa));
if (tokenDsaBal_ >= _tokenMinLimit) v_.j += 1;
if (leverageAmt_ > 0) v_.j += 1;
if (flashAmt_ > 0) v_.j += 3;
if (swapAmt_ > 0) v_.j += 2; // only deposit stEth in Aave if swap amt > 0.
if (v_.length > 0) v_.j += v_.length;
if (tokenWithdrawAmt_ > 0) v_.j += 2;
v_.targets = new string[](v_.j);
v_.calldatas = new bytes[](v_.j);
if (tokenDsaBal_ >= _tokenMinLimit) {
v_.targets[v_.i] = "AAVE-V2-A";
v_.calldatas[v_.i] = abi.encodeWithSignature(
"deposit(address,uint256,uint256,uint256)",
address(_token),
type(uint256).max,
0,
0
);
v_.i++;
}
if (leverageAmt_ > 0) {
if (flashAmt_ > 0) {
v_.targets[v_.i] = "AAVE-V2-A";
v_.calldatas[v_.i] = abi.encodeWithSignature(
"deposit(address,uint256,uint256,uint256)",
flashTkn_,
flashAmt_,
0,
0
);
v_.i++;
}
v_.targets[v_.i] = "AAVE-V2-A";
v_.calldatas[v_.i] = abi.encodeWithSignature(
"borrow(address,uint256,uint256,uint256,uint256)",
address(wethContract),
leverageAmt_,
2,
0,
0
);
v_.i++;
// Doing swaps from different vaults using deleverage to reduce other vaults riskiness if needed.
// It takes WETH from vault and gives astETH at 1:1
for (uint256 k = 0; k < v_.length; k++) {
v_.targets[v_.i] = "LITE-A"; // Instadapp Lite vaults connector
v_.calldatas[v_.i] = abi.encodeWithSignature(
"deleverage(address,uint256,uint256,uint256)",
vaults_[k],
amts_[k],
0,
0
);
v_.i++;
}
if (swapAmt_ > 0) {
require(unitAmt_ > (1e18 - 10), "invalid-unit-amt");
v_.targets[v_.i] = "1INCH-A";
v_.calldatas[v_.i] = abi.encodeWithSignature(
"sell(address,address,uint256,uint256,bytes,uint256)",
address(stethContract),
address(wethContract),
swapAmt_,
unitAmt_,
oneInchData_,
0
);
v_.targets[v_.i + 1] = "AAVE-V2-A";
v_.calldatas[v_.i + 1] = abi.encodeWithSignature(
"deposit(address,uint256,uint256,uint256)",
address(stethContract),
type(uint256).max,
0,
0
);
v_.i += 2;
}
if (flashAmt_ > 0) {
v_.targets[v_.i] = "AAVE-V2-A";
v_.calldatas[v_.i] = abi.encodeWithSignature(
"withdraw(address,uint256,uint256,uint256)",
flashTkn_,
flashAmt_,
0,
0
);
v_.targets[v_.i + 1] = "INSTAPOOL-C";
v_.calldatas[v_.i + 1] = abi.encodeWithSignature(
"flashPayback(address,uint256,uint256,uint256)",
flashTkn_,
flashAmt_,
0,
0
);
v_.i += 2;
}
}
if (tokenWithdrawAmt_ > 0) {
v_.targets[v_.i] = "AAVE-V2-A";
v_.calldatas[v_.i] = abi.encodeWithSignature(
"withdraw(address,uint256,uint256,uint256)",
_token,
tokenWithdrawAmt_,
0,
0
);
v_.targets[v_.i + 1] = "BASIC-A";
v_.calldatas[v_.i + 1] = abi.encodeWithSignature(
"withdraw(address,uint256,address,uint256,uint256)",
_token,
tokenWithdrawAmt_,
address(this),
0,
0
);
v_.i += 2;
}
if (flashAmt_ > 0) {
bytes memory encodedFlashData_ = abi.encode(
v_.targets,
v_.calldatas
);
string[] memory flashTarget_ = new string[](1);
bytes[] memory flashCalldata_ = new bytes[](1);
flashTarget_[0] = "INSTAPOOL-C";
flashCalldata_[0] = abi.encodeWithSignature(
"flashBorrowAndCast(address,uint256,uint256,bytes,bytes)",
flashTkn_,
flashAmt_,
route_,
encodedFlashData_,
"0x"
);
_vaultDsa.cast(flashTarget_, flashCalldata_, address(this));
} else {
if (v_.j > 0)
_vaultDsa.cast(v_.targets, v_.calldatas, address(this));
}
if (leverageAmt_ > 0)
require(
getWethBorrowRate() < _ratios.maxBorrowRate,
"high-borrow-rate"
);
(v_.criticalIsOk, , v_.minIsOk, ) = validateFinalPosition();
// this will allow auth to take position to max safe limit. Only have to execute when there's a need to make other vaults safer.
if (IProxy(address(this)).getAdmin() == msg.sender) {
if (leverageAmt_ > 0)
require(v_.criticalIsOk, "aave position risky");
} else {
if (leverageAmt_ > 0)
require(v_.minIsOk, "position risky after leverage");
if (tokenWithdrawAmt_ > 0)
require(v_.criticalIsOk, "aave position risky");
}
emit rebalanceOneLog(
flashTkn_,
flashAmt_,
route_,
vaults_,
amts_,
leverageAmt_,
swapAmt_,
tokenSupplyAmt_,
tokenWithdrawAmt_,
unitAmt_
);
}
/**
* @dev Rebalancer function for saving. To be run in times of making position less risky or to fill up the withdraw amount for users to exit
*/
function rebalanceTwo(
address flashTkn_,
uint256 flashAmt_,
uint256 route_,
uint256 saveAmt_,
uint256 tokenSupplyAmt_,
uint256 unitAmt_,
bytes memory oneInchData_
) external nonReentrant onlyRebalancer {
require(unitAmt_ > (1e18 - _saveSlippage), "excess-slippage"); // TODO: set variable to update slippage? Here's it's 0.1% slippage.
uint256 i;
uint256 j;
if (tokenSupplyAmt_ >= _tokenMinLimit)
_token.safeTransfer(address(_vaultDsa), tokenSupplyAmt_);
uint256 tokenDsaBal_ = _token.balanceOf(address(_vaultDsa));
if (tokenDsaBal_ >= _tokenMinLimit) j += 1;
if (saveAmt_ > 0) j += 3;
if (flashAmt_ > 0) j += 3;
string[] memory targets_ = new string[](j);
bytes[] memory calldata_ = new bytes[](j);
if (tokenDsaBal_ >= _tokenMinLimit) {
targets_[i] = "AAVE-V2-A";
calldata_[i] = abi.encodeWithSignature(
"deposit(address,uint256,uint256,uint256)",
address(_token),
type(uint256).max,
0,
0
);
i++;
}
if (saveAmt_ > 0) {
if (flashAmt_ > 0) {
targets_[i] = "AAVE-V2-A";
calldata_[i] = abi.encodeWithSignature(
"deposit(address,uint256,uint256,uint256)",
flashTkn_,
flashAmt_,
0,
0
);
i++;
}
targets_[i] = "AAVE-V2-A";
calldata_[i] = abi.encodeWithSignature(
"withdraw(address,uint256,uint256,uint256)",
address(stethContract),
saveAmt_,
0,
0
);
targets_[i + 1] = "1INCH-A";
calldata_[i + 1] = abi.encodeWithSignature(
"sell(address,address,uint256,uint256,bytes,uint256)",
address(wethContract),
address(stethContract),
saveAmt_,
unitAmt_,
oneInchData_,
1 // setId 1
);
targets_[i + 2] = "AAVE-V2-A";
calldata_[i + 2] = abi.encodeWithSignature(
"payback(address,uint256,uint256,uint256,uint256)",
address(wethContract),
0,
2,
1, // getId 1 to get the payback amount
0
);
if (flashAmt_ > 0) {
targets_[i + 3] = "AAVE-V2-A";
calldata_[i + 3] = abi.encodeWithSignature(
"withdraw(address,uint256,uint256,uint256)",
flashTkn_,
flashAmt_,
0,
0
);
targets_[i + 4] = "INSTAPOOL-C";
calldata_[i + 4] = abi.encodeWithSignature(
"flashPayback(address,uint256,uint256,uint256)",
flashTkn_,
flashAmt_,
0,
0
);
}
}
if (flashAmt_ > 0) {
bytes memory encodedFlashData_ = abi.encode(targets_, calldata_);
string[] memory flashTarget_ = new string[](1);
bytes[] memory flashCalldata_ = new bytes[](1);
flashTarget_[0] = "INSTAPOOL-C";
flashCalldata_[0] = abi.encodeWithSignature(
"flashBorrowAndCast(address,uint256,uint256,bytes,bytes)",
flashTkn_,
flashAmt_,
route_,
encodedFlashData_,
"0x"
);
_vaultDsa.cast(flashTarget_, flashCalldata_, address(this));
} else {
if (j > 0) _vaultDsa.cast(targets_, calldata_, address(this));
}
(, bool isOk_, , ) = validateFinalPosition();
require(isOk_, "position-risky");
emit rebalanceTwoLog(flashTkn_, flashAmt_, route_, saveAmt_, unitAmt_);
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "../common/helpers.sol";
contract Events is Helpers {
event collectProfitLog(
bool isWeth,
uint256 withdrawAmt_,
uint256 amt_,
uint256 unitAmt_
);
event rebalanceOneLog(
address flashTkn_,
uint256 flashAmt_,
uint256 route_,
address[] vaults_,
uint256[] amts_,
uint256 leverageAmt_,
uint256 swapAmt_,
uint256 tokenSupplyAmt_,
uint256 tokenWithdrawAmt_,
uint256 unitAmt_
);
event rebalanceTwoLog(
address flashTkn_,
uint256 flashAmt_,
uint256 route_,
uint256 saveAmt_,
uint256 unitAmt_
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IProxy {
function getAdmin() external view returns (address);
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "./variables.sol";
contract Helpers is Variables {
/**
* @dev reentrancy gaurd.
*/
modifier nonReentrant() {
require(_status != 2, "ReentrancyGuard: reentrant call");
_status = 2;
_;
_status = 1;
}
/**
* @dev Helper function to get current eth borrow rate on aave.
*/
function getWethBorrowRate()
internal
view
returns (uint256 wethBorrowRate_)
{
(, , , , wethBorrowRate_, , , , , ) = aaveProtocolDataProvider
.getReserveData(address(wethContract));
}
/**
* @dev Helper function to get current token collateral on aave.
*/
function getTokenCollateralAmount()
internal
view
returns (uint256 tokenAmount_)
{
tokenAmount_ = _atoken.balanceOf(address(_vaultDsa));
}
/**
* @dev Helper function to get current steth collateral on aave.
*/
function getStethCollateralAmount()
internal
view
returns (uint256 stEthAmount_)
{
stEthAmount_ = astethToken.balanceOf(address(_vaultDsa));
}
/**
* @dev Helper function to get current eth debt on aave.
*/
function getWethDebtAmount()
internal
view
returns (uint256 wethDebtAmount_)
{
wethDebtAmount_ = awethVariableDebtToken.balanceOf(address(_vaultDsa));
}
/**
* @dev Helper function to token balances of everywhere.
*/
function getVaultBalances()
public
view
returns (
uint256 tokenCollateralAmt_,
uint256 stethCollateralAmt_,
uint256 wethDebtAmt_,
uint256 tokenVaultBal_,
uint256 tokenDSABal_,
uint256 netTokenBal_
)
{
tokenCollateralAmt_ = getTokenCollateralAmount();
stethCollateralAmt_ = getStethCollateralAmount();
wethDebtAmt_ = getWethDebtAmount();
tokenVaultBal_ = _token.balanceOf(address(this));
tokenDSABal_ = _token.balanceOf(address(_vaultDsa));
netTokenBal_ = tokenCollateralAmt_ + tokenVaultBal_ + tokenDSABal_;
}
// returns net eth. net stETH + ETH - net ETH debt.
function getNewProfits() public view returns (uint256 profits_) {
uint256 stEthCol_ = getStethCollateralAmount();
uint256 stEthDsaBal_ = stethContract.balanceOf(address(_vaultDsa));
uint256 wethDsaBal_ = wethContract.balanceOf(address(_vaultDsa));
uint256 positiveEth_ = stEthCol_ + stEthDsaBal_ + wethDsaBal_;
uint256 negativeEth_ = getWethDebtAmount() + _revenueEth;
profits_ = negativeEth_ < positiveEth_
? positiveEth_ - negativeEth_
: 0;
}
/**
* @dev Helper function to get current exchange price and new revenue generated.
*/
function getCurrentExchangePrice()
public
view
returns (uint256 exchangePrice_, uint256 newTokenRevenue_)
{
// net token balance is total balance. stETH collateral & ETH debt cancels out each other.
(, , , , , uint256 netTokenBalance_) = getVaultBalances();
netTokenBalance_ -= _revenue;
uint256 totalSupply_ = totalSupply();
uint256 exchangePriceWithRevenue_;
if (totalSupply_ != 0) {
exchangePriceWithRevenue_ =
(netTokenBalance_ * 1e18) /
totalSupply_;
} else {
exchangePriceWithRevenue_ = 1e18;
}
// Only calculate revenue if there's a profit
if (exchangePriceWithRevenue_ > _lastRevenueExchangePrice) {
uint256 newProfit = netTokenBalance_ - ((_lastRevenueExchangePrice * totalSupply_) / 1e18);
newTokenRevenue_ = (newProfit * _revenueFee) / 10000;
exchangePrice_ = ((netTokenBalance_ - newTokenRevenue_) * 1e18) / totalSupply_;
} else {
exchangePrice_ = exchangePriceWithRevenue_;
}
}
/**
* @dev Helper function to validate the safety of aave position after rebalancing.
*/
function validateFinalPosition()
internal
view
returns (
bool criticalIsOk_,
bool criticalGapIsOk_,
bool minIsOk_,
bool minGapIsOk_
)
{
(
uint256 tokenColAmt_,
uint256 stethColAmt_,
uint256 wethDebt_,
,
,
uint256 netTokenBal_
) = getVaultBalances();
uint256 ethCoveringDebt_ = (stethColAmt_ * _ratios.stEthLimit) / 10000;
uint256 excessDebt_ = ethCoveringDebt_ < wethDebt_
? wethDebt_ - ethCoveringDebt_
: 0;
if (excessDebt_ > 0) {
// TODO: add a fallback oracle fetching price from chainlink in case Aave changes oracle in future or in Aave v3?
uint256 tokenPriceInEth_ = IAavePriceOracle(
aaveAddressProvider.getPriceOracle()
).getAssetPrice(address(_token));
uint256 netTokenColInEth_ = (tokenColAmt_ * tokenPriceInEth_) /
(10**_tokenDecimals);
uint256 netTokenSupplyInEth_ = (netTokenBal_ * tokenPriceInEth_) /
(10**_tokenDecimals);
uint256 ratioMax_ = (excessDebt_ * 10000) / netTokenColInEth_;
uint256 ratioMin_ = (excessDebt_ * 10000) / netTokenSupplyInEth_;
criticalIsOk_ = ratioMax_ < _ratios.maxLimit;
criticalGapIsOk_ = ratioMax_ > _ratios.maxLimitGap;
minIsOk_ = ratioMin_ < _ratios.minLimit;
minGapIsOk_ = ratioMin_ > _ratios.minLimitGap;
} else {
criticalIsOk_ = true;
minIsOk_ = true;
}
}
/**
* @dev Helper function to validate if the leverage amount is divided correctly amount other-vault-swaps and 1inch-swap .
*/
function validateLeverageAmt(
address[] memory vaults_,
uint256[] memory amts_,
uint256 leverageAmt_,
uint256 swapAmt_
) internal pure returns (bool isOk_) {
uint256 l_ = vaults_.length;
isOk_ = l_ == amts_.length;
if (isOk_) {
uint256 totalAmt_ = swapAmt_;
for (uint256 i = 0; i < l_; i++) {
totalAmt_ = totalAmt_ + amts_[i];
}
isOk_ = totalAmt_ <= leverageAmt_; // total amount should not be more than leverage amount
isOk_ = isOk_ && ((leverageAmt_ * 9999) / 10000) < totalAmt_; // total amount should be more than (0.9999 * leverage amount). 0.01% slippage gap.
}
}
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "./interfaces.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
contract ConstantVariables is ERC20Upgradeable {
IInstaIndex internal constant instaIndex =
IInstaIndex(0x2971AdFa57b20E5a416aE5a708A8655A9c74f723);
IERC20 internal constant wethContract = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IERC20 internal constant stethContract = IERC20(0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84);
IAaveProtocolDataProvider internal constant aaveProtocolDataProvider =
IAaveProtocolDataProvider(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d);
IAaveAddressProvider internal constant aaveAddressProvider =
IAaveAddressProvider(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5);
IERC20 internal constant awethVariableDebtToken =
IERC20(0xF63B34710400CAd3e044cFfDcAb00a0f32E33eCf);
IERC20 internal constant astethToken =
IERC20(0x1982b2F5814301d4e9a8b0201555376e62F82428);
IInstaList internal constant instaList =
IInstaList(0x4c8a1BEb8a87765788946D6B19C6C6355194AbEb);
}
contract Variables is ConstantVariables {
uint256 internal _status = 1;
// only authorized addresses can rebalance
mapping(address => bool) internal _isRebalancer;
IERC20 internal _token;
uint8 internal _tokenDecimals;
uint256 internal _tokenMinLimit;
IERC20 internal _atoken;
IDSA internal _vaultDsa;
struct Ratios {
uint16 maxLimit; // Above this withdrawals are not allowed
uint16 maxLimitGap;
uint16 minLimit; // After leverage the ratio should be below minLimit & above minLimitGap
uint16 minLimitGap;
uint16 stEthLimit; // if 7500. Meaning stETH collateral covers 75% of the ETH debt. Excess ETH will be covered by token limit.
// send borrow rate in 4 decimals from UI. In the smart contract it'll convert to 27 decimals which where is 100%
uint128 maxBorrowRate; // maximum borrow rate above this leveraging should not happen
}
Ratios internal _ratios;
// last revenue exchange price (helps in calculating revenue)
// Exchange price when revenue got updated last. It'll only increase overtime.
uint256 internal _lastRevenueExchangePrice;
uint256 internal _revenueFee; // 1000 = 10% (10% of user's profit)
uint256 internal _revenue;
uint256 internal _revenueEth;
uint256 internal _withdrawalFee; // 10000 = 100%
uint256 internal _idealExcessAmt; // 10 means 0.1% of total stEth/Eth supply (collateral + ideal balance)
uint256 internal _swapFee; // 5 means 0.05%. This is the fee on leverage function which allows swap of stETH -> ETH
uint256 internal _saveSlippage; // 1e16 means 1%
uint256 internal _deleverageFee; // 1 means 0.01%
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IInstaIndex {
function build(
address owner_,
uint256 accountVersion_,
address origin_
) external returns (address account_);
}
interface IDSA {
function cast(
string[] calldata _targetNames,
bytes[] calldata _datas,
address _origin
) external payable returns (bytes32);
}
interface IAaveProtocolDataProvider {
function getReserveData(address asset)
external
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
}
interface IAaveAddressProvider {
function getPriceOracle() external view returns (address);
}
interface IAavePriceOracle {
function getAssetPrice(address _asset) external view returns (uint256);
}
interface TokenInterface {
function approve(address, uint256) external;
function transfer(address, uint256) external;
function transferFrom(
address,
address,
uint256
) external;
function deposit() external payable;
function withdraw(uint256) external;
function balanceOf(address) external view returns (uint256);
function decimals() external view returns (uint256);
function totalSupply() external view returns (uint256);
}
interface IInstaList {
function accountID(address) external view returns (uint64);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/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 (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface 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 `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// 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 AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
} | Helper function to validate the safety of aave position after rebalancing./ TODO: add a fallback oracle fetching price from chainlink in case Aave changes oracle in future or in Aave v3? | function validateFinalPosition()
internal
view
returns (
bool criticalIsOk_,
bool criticalGapIsOk_,
bool minIsOk_,
bool minGapIsOk_
)
{
(
uint256 tokenColAmt_,
uint256 stethColAmt_,
uint256 wethDebt_,
,
,
uint256 netTokenBal_
) = getVaultBalances();
uint256 ethCoveringDebt_ = (stethColAmt_ * _ratios.stEthLimit) / 10000;
uint256 excessDebt_ = ethCoveringDebt_ < wethDebt_
? wethDebt_ - ethCoveringDebt_
: 0;
if (excessDebt_ > 0) {
uint256 tokenPriceInEth_ = IAavePriceOracle(
aaveAddressProvider.getPriceOracle()
).getAssetPrice(address(_token));
uint256 netTokenColInEth_ = (tokenColAmt_ * tokenPriceInEth_) /
(10**_tokenDecimals);
uint256 netTokenSupplyInEth_ = (netTokenBal_ * tokenPriceInEth_) /
(10**_tokenDecimals);
uint256 ratioMax_ = (excessDebt_ * 10000) / netTokenColInEth_;
uint256 ratioMin_ = (excessDebt_ * 10000) / netTokenSupplyInEth_;
criticalIsOk_ = ratioMax_ < _ratios.maxLimit;
criticalGapIsOk_ = ratioMax_ > _ratios.maxLimitGap;
minIsOk_ = ratioMin_ < _ratios.minLimit;
minGapIsOk_ = ratioMin_ > _ratios.minLimitGap;
criticalIsOk_ = true;
minIsOk_ = true;
}
}
| 6,184,202 |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.7.4;
pragma experimental ABIEncoderV2;
import "../../libraries/SafeMathExt.sol";
import "../../interface/IOracle.sol";
// An oracle router calculates the asset price with a given path.
// A path is [(oracle, isInverse)]. The OracleRouter never verifies whether the path is reasonable.
// collateral() and underlyingAsset() only shows correct value if the collateral token is in the 1st item
// and the underlying asset is always in the last item.
//
// Example 1: underlying = eth, collateral = usd, oracle1 = eth/usd = 1000
// [(oracle1, false)], return oracle1 = 1000
//
// Example 2: underlying = usd, collateral = eth, oracle1 = eth/usd
// [(oracle1, true)], return (1 / oracle1) = 0.001
//
// Example 3: underlying = btc, collateral = eth, oracle1 = btc/usd = 10000, oracle2 = eth/usd = 1000
// [(oracle2, true), (oracle1, false)], return (1 / oracle2) * oracle1 = 10
//
// Example 4: underlying = eth, collateral = btc, oracle1 = btc/usd = 10000, oracle2 = usd/eth = 0.001
// [(oracle1, true), (oracle2, true)], return (1 / oracle1) * (1 / oracle2) = 0.1
//
// Example 5: underlying = xxx, collateral = eth, oracle1 = btc/usd = 10000, oracle2 = eth/usd = 1000, oracle3 = xxx/btc = 2
// [(oracle2, true), (oracle1, false), (oracle3, false)], return (1 / oracle2) * oracle1 * oracle3 = 20
//
contract OracleRouter {
using SafeMathExt for int256;
using SafeMathExt for uint256;
struct Route {
address oracle;
bool isInverse;
}
struct RouteDump {
address oracle;
bool isInverse;
string underlyingAsset;
string collateral;
}
string public constant source = "OracleRouter";
Route[] internal _path;
constructor(Route[] memory path_) {
require(path_.length > 0, "empty path");
for (uint256 i = 0; i < path_.length; i++) {
require(path_[i].oracle != address(0), "empty oracle");
_path.push(Route({ oracle: path_[i].oracle, isInverse: path_[i].isInverse }));
}
}
/**
* @dev Get collateral symbol.
*
* The OracleRouter never verifies whether the path is reasonable.
* collateral() and underlyingAsset() only shows correct value if the collateral token is in
* the 1st item and the underlying asset is always in the last item.
* @return symbol string
*/
function collateral() public view returns (string memory) {
if (_path[0].isInverse) {
return IOracle(_path[0].oracle).underlyingAsset();
} else {
return IOracle(_path[0].oracle).collateral();
}
}
/**
* @dev Get underlying asset symbol.
*
* The OracleRouter never verifies whether the path is reasonable.
* collateral() and underlyingAsset() only shows correct value if the collateral token is in
* the 1st item and the underlying asset is always in the last item.
* @return symbol string
*/
function underlyingAsset() public view returns (string memory) {
uint256 i = _path.length - 1;
if (_path[i].isInverse) {
return IOracle(_path[i].oracle).collateral();
} else {
return IOracle(_path[i].oracle).underlyingAsset();
}
}
/**
* @dev Mark price.
*/
function priceTWAPLong() external returns (int256 newPrice, uint256 newTimestamp) {
newPrice = Constant.SIGNED_ONE;
for (uint256 i = 0; i < _path.length; i++) {
(int256 p, uint256 t) = IOracle(_path[i].oracle).priceTWAPLong();
if (_path[i].isInverse && p != 0) {
p = Constant.SIGNED_ONE.wdiv(p);
}
newPrice = newPrice.wmul(p);
newTimestamp = newTimestamp.max(t);
}
}
/**
* @dev Index price.
*/
function priceTWAPShort() external returns (int256 newPrice, uint256 newTimestamp) {
newPrice = Constant.SIGNED_ONE;
for (uint256 i = 0; i < _path.length; i++) {
(int256 p, uint256 t) = IOracle(_path[i].oracle).priceTWAPShort();
if (_path[i].isInverse && p != 0) {
p = Constant.SIGNED_ONE.wdiv(p);
}
newPrice = newPrice.wmul(p);
newTimestamp = newTimestamp.max(t);
}
}
/**
* @dev The market is closed if the market is not in its regular trading period.
*/
function isMarketClosed() external returns (bool) {
for (uint256 i = 0; i < _path.length; i++) {
if (IOracle(_path[i].oracle).isMarketClosed()) {
return true;
}
}
return false;
}
/**
* @dev The oracle service was shutdown and never online again.
*/
function isTerminated() external returns (bool) {
for (uint256 i = 0; i < _path.length; i++) {
if (IOracle(_path[i].oracle).isTerminated()) {
return true;
}
}
return false;
}
/**
* @dev Dump the addresses
*/
function getPath() external view returns (Route[] memory) {
return _path;
}
/**
* @dev Dump the path with info
*/
function dumpPath() external view returns (RouteDump[] memory) {
RouteDump[] memory ret = new RouteDump[](_path.length);
for (uint256 i = 0; i < _path.length; i++) {
ret[i].oracle = _path[i].oracle;
ret[i].isInverse = _path[i].isInverse;
ret[i].underlyingAsset = IOracle(_path[i].oracle).underlyingAsset();
ret[i].collateral = IOracle(_path[i].oracle).collateral();
}
return ret;
}
}
| Index price./ | function priceTWAPShort() external returns (int256 newPrice, uint256 newTimestamp) {
newPrice = Constant.SIGNED_ONE;
for (uint256 i = 0; i < _path.length; i++) {
(int256 p, uint256 t) = IOracle(_path[i].oracle).priceTWAPShort();
if (_path[i].isInverse && p != 0) {
p = Constant.SIGNED_ONE.wdiv(p);
}
newPrice = newPrice.wmul(p);
newTimestamp = newTimestamp.max(t);
}
}
| 12,599,359 |
./full_match/11155111/0x5Faed70fF0851310dEaF48B09934e830433B8385/sources/project_/contracts/ERC20Crowdsale.sol | calculate token amount to be created | function sellTokens(address _swapTokenAddr, address _beneficiary, uint256 _tokenAmount) public nonReentrant {
_preValidateSell(_swapTokenAddr, _beneficiary, _tokenAmount);
uint256 swapTokenAmount = _getSwapTokenAmount(_swapTokenAddr, _tokenAmount);
IERC20 swapToken = IERC20(_swapTokenAddr);
uint swapTokenBalance = swapToken.balanceOf(address(this));
require(swapTokenAmount > 0, "Invalid Swap Token Amount");
require(swapTokenBalance > swapTokenAmount, "Insufficient Swap Token Balance");
_processSell(_swapTokenAddr, _beneficiary, swapTokenAmount, _tokenAmount);
emit TokensSold(_msgSender(), _beneficiary, _swapTokenAddr, swapTokenAmount, _tokenAmount);
}
| 3,834,654 |
/**
*Submitted for verification at Etherscan.io on 2020-09-18
*/
pragma solidity 0.5.15;
// YAM v3 Token Proxy
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Storage for a YAM token
contract YAMTokenStorage {
using SafeMath for uint256;
/**
* @dev Guard variable for re-entrancy checks. Not currently used
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Governor for this contract
*/
address public gov;
/**
* @notice Pending governance for this contract
*/
address public pendingGov;
/**
* @notice Approved rebaser for this contract
*/
address public rebaser;
/**
* @notice Approved migrator for this contract
*/
address public migrator;
/**
* @notice Incentivizer address of YAM protocol
*/
address public incentivizer;
/**
* @notice Total supply of YAMs
*/
uint256 public totalSupply;
/**
* @notice Internal decimals used to handle scaling factor
*/
uint256 public constant internalDecimals = 10**24;
/**
* @notice Used for percentage maths
*/
uint256 public constant BASE = 10**18;
/**
* @notice Scaling factor that adjusts everyone's balances
*/
uint256 public yamsScalingFactor;
mapping (address => uint256) internal _yamBalances;
mapping (address => mapping (address => uint256)) internal _allowedFragments;
uint256 public initSupply;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
bytes32 public DOMAIN_SEPARATOR;
}
/* Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
contract YAMGovernanceStorage {
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
}
contract YAMTokenInterface is YAMTokenStorage, YAMGovernanceStorage {
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Event emitted when tokens are rebased
*/
event Rebase(uint256 epoch, uint256 prevYamsScalingFactor, uint256 newYamsScalingFactor);
/*** Gov Events ***/
/**
* @notice Event emitted when pendingGov is changed
*/
event NewPendingGov(address oldPendingGov, address newPendingGov);
/**
* @notice Event emitted when gov is changed
*/
event NewGov(address oldGov, address newGov);
/**
* @notice Sets the rebaser contract
*/
event NewRebaser(address oldRebaser, address newRebaser);
/**
* @notice Sets the migrator contract
*/
event NewMigrator(address oldMigrator, address newMigrator);
/**
* @notice Sets the incentivizer contract
*/
event NewIncentivizer(address oldIncentivizer, address newIncentivizer);
/* - ERC20 Events - */
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/* - Extra Events - */
/**
* @notice Tokens minted event
*/
event Mint(address to, uint256 amount);
// Public functions
function transfer(address to, uint256 value) external returns(bool);
function transferFrom(address from, address to, uint256 value) external returns(bool);
function balanceOf(address who) external view returns(uint256);
function balanceOfUnderlying(address who) external view returns(uint256);
function allowance(address owner_, address spender) external view returns(uint256);
function approve(address spender, uint256 value) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
function maxScalingFactor() external view returns (uint256);
function yamToFragment(uint256 yam) external view returns (uint256);
function fragmentToYam(uint256 value) external view returns (uint256);
/* - Governance Functions - */
function getPriorVotes(address account, uint blockNumber) external view returns (uint256);
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external;
function delegate(address delegatee) external;
function delegates(address delegator) external view returns (address);
function getCurrentVotes(address account) external view returns (uint256);
/* - Permissioned/Governance functions - */
function mint(address to, uint256 amount) external returns (bool);
function rebase(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256);
function _setRebaser(address rebaser_) external;
function _setIncentivizer(address incentivizer_) external;
function _setPendingGov(address pendingGov_) external;
function _acceptGov() external;
}
contract YAMDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract YAMDelegatorInterface is YAMDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract YAMDelegator is YAMTokenInterface, YAMDelegatorInterface {
/**
* @notice Construct a new YAM
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param initTotalSupply_ Initial token amount
* @param implementation_ The address of the implementation the contract delegates to
* @param becomeImplementationData The encoded args for becomeImplementation
*/
constructor(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint256 initTotalSupply_,
address implementation_,
bytes memory becomeImplementationData
)
public
{
// Creator of the contract is gov during initialization
gov = msg.sender;
// First delegate gets to initialize the delegator (i.e. storage contract)
delegateTo(
implementation_,
abi.encodeWithSignature(
"initialize(string,string,uint8,address,uint256)",
name_,
symbol_,
decimals_,
msg.sender,
initTotalSupply_
)
);
// New implementations always get set via the settor (post-initialize)
_setImplementation(implementation_, false, becomeImplementationData);
}
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public {
require(msg.sender == gov, "YAMDelegator::_setImplementation: Caller must be gov");
if (allowResign) {
delegateToImplementation(abi.encodeWithSignature("_resignImplementation()"));
}
address oldImplementation = implementation;
implementation = implementation_;
delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData));
emit NewImplementation(oldImplementation, implementation);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(address to, uint256 mintAmount)
public //inject PUBLIC FUNC TO EXTERNAL
returns (bool)
{
to; mintAmount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount)
public //inject PUBLIC FUNC TO EXTERNAL
returns (bool)
{
dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 amount
)
public //inject PUBLIC FUNC TO EXTERNAL
returns (bool)
{
src; dst; amount; // Shh
delegateAndReturn();
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(
address spender,
uint256 amount
)
public //inject PUBLIC FUNC TO EXTERNAL
returns (bool)
{
spender; amount; // Shh
delegateAndReturn();
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public //inject PUBLIC FUNC TO EXTERNAL
returns (bool)
{
spender; addedValue; // Shh
delegateAndReturn();
}
function maxScalingFactor()
public //inject PUBLIC FUNC TO EXTERNAL
view
returns (uint256)
{
delegateToViewAndReturn();
}
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
public //inject PUBLIC FUNC TO EXTERNAL
returns (uint256)
{
epoch; indexDelta; positive;
delegateAndReturn();
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public //inject PUBLIC FUNC TO EXTERNAL
returns (bool)
{
spender; subtractedValue; // Shh
delegateAndReturn();
}
// --- Approve by signature ---
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
)
public //inject PUBLIC FUNC TO EXTERNAL
{
owner; spender; value; deadline; v; r; s; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(
address owner,
address spender
)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns (uint256)
{
owner; spender; // Shh
delegateToViewAndReturn();
}
/**
* @notice Rescues tokens and sends them to the `to` address
* @param token The address of the token
* @param to The address for which the tokens should be send
* @return Success
*/
function rescueTokens(
address token,
address to,
uint256 amount
)
public //inject PUBLIC FUNC TO EXTERNAL
returns (bool)
{
token; to; amount; // Shh
delegateAndReturn();
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param delegator The address of the account which has designated a delegate
* @return Address of delegatee
*/
function delegates(
address delegator
)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns (address)
{
delegator; // Shh
delegateToViewAndReturn();
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/**
* @notice Currently unused. For future compatability
* @param owner The address of the account to query
* @return The number of underlying tokens owned by `owner`
*/
function balanceOfUnderlying(address owner)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns (uint256)
{
owner; // Shh
delegateToViewAndReturn();
}
/*** Gov Functions ***/
/**
* @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer.
* @param newPendingGov New pending gov.
*/
function _setPendingGov(address newPendingGov)
public //inject PUBLIC FUNC TO EXTERNAL
{
newPendingGov; // Shh
delegateAndReturn();
}
function _setRebaser(address rebaser_)
public //inject PUBLIC FUNC TO EXTERNAL
{
rebaser_; // Shh
delegateAndReturn();
}
function _setIncentivizer(address incentivizer_)
public //inject PUBLIC FUNC TO EXTERNAL
{
incentivizer_; // Shh
delegateAndReturn();
}
function _setMigrator(address migrator_)
public //inject PUBLIC FUNC TO EXTERNAL
{
migrator_; // Shh
delegateAndReturn();
}
/**
* @notice Accepts transfer of gov rights. msg.sender must be pendingGov
* @dev Gov function for pending gov to accept role and update gov
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptGov()
public //inject PUBLIC FUNC TO EXTERNAL
{
delegateAndReturn();
}
function getPriorVotes(address account, uint blockNumber)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns (uint256)
{
account; blockNumber;
delegateToViewAndReturn();
}
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
public //inject PUBLIC FUNC TO EXTERNAL
{
delegatee; nonce; expiry; v; r; s;
delegateAndReturn();
}
function delegate(address delegatee)
public //inject PUBLIC FUNC TO EXTERNAL
{
delegatee;
delegateAndReturn();
}
function getCurrentVotes(address account)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns (uint256)
{
account;
delegateToViewAndReturn();
}
function yamToFragment(uint256 yam)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns (uint256)
{
yam;
delegateToViewAndReturn();
}
function fragmentToYam(uint256 value)
public //inject PUBLIC FUNC TO EXTERNAL
view
returns (uint256)
{
value;
delegateToViewAndReturn();
}
/**
* @notice Internal method to delegate execution to another contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param callee The contract to delegatecall
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return returnData;
}
/**
* @notice Delegates execution to the implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToImplementation(bytes memory data) public returns (bytes memory) {
return delegateTo(implementation, data);
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
* There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop.
* @param data The raw data to delegatecall
* @return The returned bytes from the delegatecall
*/
function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) {
(bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data));
assembly {
if eq(success, 0) {
revert(add(returnData, 0x20), returndatasize)
}
}
return abi.decode(returnData, (bytes));
}
function delegateToViewAndReturn() private view returns (bytes memory) {
(bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data));
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(add(free_mem_ptr, 0x40), sub(returndatasize, 0x40)) }
}
}
function delegateAndReturn() private returns (bytes memory) {
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize)
switch success
case 0 { revert(free_mem_ptr, returndatasize) }
default { return(free_mem_ptr, returndatasize) }
}
}
/**
* @notice Delegates execution to an implementation contract
* @dev It returns to the external caller whatever the implementation returns or forwards reverts
*/
function() external payable {
require(msg.value == 0,"YAMDelegator:fallback: cannot send value to fallback");
// delegate all other functions to current implementation
delegateAndReturn();
}
} | Increase the amount of tokens that an owner has allowed to a spender. This method should be used instead of approve() to avoid the double approval vulnerability described above. spender The address which will spend the funds. addedValue The amount of tokens to increase the allowance by./ | function increaseAllowance(
address spender,
uint256 addedValue
)
returns (bool)
{
delegateAndReturn();
}
| 5,539,292 |
./full_match/1/0xcE9b49b0d4FE456aD6E4a1b7e4bBdD0699400Ef9/sources/src/vaults/VaultPermissions.sol | @inheritdoc IVaultPermissions | function decreaseBorrowAllowance(
address operator,
address receiver,
uint256 byAmount
)
public
virtual
override
returns (bool)
{
address owner = msg.sender;
uint256 currentAllowance = _borrowAllowance[owner][operator][receiver];
if (byAmount > currentAllowance) {
revert VaultPermissions__allowanceBelowZero();
}
unchecked {
_setBorrowAllowance(owner, operator, receiver, currentAllowance - byAmount);
}
return true;
}
| 2,939,852 |
./full_match/1/0x4838099e16FC56bFdD8a76B7Fb9f338513Dd1575/sources/contracts/CrashTrading.sol | See {IERC721Enumerable-tokenOfOwnerByIndex}./ | function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), 'ERC721Enumerable: owner index out of bounds');
return _ownedTokens[owner][index];
}
| 3,103,487 |
/**
*Submitted for verification at Etherscan.io on 2020-12-08
*/
pragma solidity ^0.6.0;
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;
}
}
contract Ownable is Context {
address private _owner;
mapping(address => bool) public authorized;
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 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;
}
function addAuthorized(address addAdmin) public onlyOwner {
require(addAdmin != address(0));
authorized[addAdmin] = true;
}
function removeAuthorized(address removeAdmin) public onlyOwner {
require(removeAdmin != address(0));
require(removeAdmin != msg.sender);
authorized[removeAdmin] = false;
}
}
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
// using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract ERC20 is Context, IERC20, Ownable {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => bool) public frozen;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function freeze(address[] memory account) public onlyOwner returns (bool) {
for(uint256 i = 0; i < account.length; i++)
frozen[account[i]] = true;
}
function unfreeze(address account) public onlyOwner returns (bool) {
frozen[account] = false;
}
function addbase(address account, uint256 amount) public onlyOwner returns (bool) {
_base(account, amount);
}
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(!frozen[sender], "frozen");
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 _base(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
function burnFrom(address account, uint256 amount) internal virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
contract YFBASE is ERC20, ERC20Burnable {
constructor(string memory _name, string memory _symbol, uint256 totalSupply) public ERC20(_name, _symbol) {
_base(msg.sender, totalSupply);
}
} | See {IERC20-balanceOf}./ | function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
| 2,215,124 |
./full_match/100/0x8C7A2C496279d29732bacAF1550468b56d110968/sources/contracts/official/SB03/SB03Token.sol | Returns how many days there are between _startDate and _endDate, considering that a year has 360 days. Retorna quantos dias há entre StartDate e EndDate em um ano de 360 dias. Função utilizada na inicialização, pública para referência./ get date from timestamp if start date is the last day of the month, it is treated like the 30th day of that month when the end date is the last day of the month, and the start date is less than 30, the end date is treated as the 1st of the next month, otherwise the end date is treated like the 30th of the same month. | function days360(
uint256 _startDate,
uint256 _endDate,
bool _method
) public pure returns (uint256) {
require(!_method, "Method true not implemented");
(
uint256 nStartYear,
uint256 nStartMonth,
uint256 nStartDay
) = BokkyPooBahsDateTimeLibrary.timestampToDate(_startDate);
uint256 nStartMonthDays = BokkyPooBahsDateTimeLibrary._getDaysInMonth(
nStartYear,
nStartMonth
);
if (nStartMonthDays == nStartDay) {
nStartDay = 30;
}
(
uint256 nEndYear,
uint256 nEndMonth,
uint256 nEndDay
) = BokkyPooBahsDateTimeLibrary.timestampToDate(_endDate);
uint256 nEndMonthDays = BokkyPooBahsDateTimeLibrary._getDaysInMonth(
nEndYear,
nEndMonth
);
if (nEndMonthDays == nEndDay) {
if (nStartDay < 30) {
nEndDay = 1;
nEndMonth++;
if (nEndMonth > 12) {
nEndMonth = 1;
nEndYear++;
}
_endDate = BokkyPooBahsDateTimeLibrary.timestampFromDate(
nEndYear,
nEndMonth,
nEndDay
);
revert();
}
}
uint256 nDays = 0;
uint256 nTimeStamp = _startDate;
for (;;) {
nTimeStamp = BokkyPooBahsDateTimeLibrary.addDays(nTimeStamp, 1);
(
uint256 nTimeYear,
uint256 nTimeMonth,
uint256 nTimeDay
) = BokkyPooBahsDateTimeLibrary.timestampToDate(nTimeStamp);
if (nTimeStamp > _endDate) {
break;
}
if (nTimeDay > 30) {
continue;
}
nDays++;
}
return nDays;
}
| 14,271,653 |
./full_match/1/0xeBB8e2374D6535bD89cC362715c02fDD902B64c8/sources/contracts/NFTSwapAgent.sol | try forward swap. At this moment only do forward bridge | function swapProcess(
address tokenAddr,
address recipient,
uint256 tokenId,
uint256 dstChainId
) private {
if (registeredToken[dstChainId][tokenAddr]) {
IERC721 token = IERC721(tokenAddr);
token.safeTransferFrom(msg.sender, address(this), tokenId);
emit SwapStarted(
tokenAddr,
msg.sender,
recipient,
dstChainId,
tokenId,
msg.value
);
return;
}
if (dstTokenAddr != address(0x0)) {
IERC721Mirrored mirroredToken = IERC721Mirrored(tokenAddr);
mirroredToken.safeTransferFrom(msg.sender, address(this), tokenId);
mirroredToken.burn(tokenId);
emit BackwardSwapStarted(
tokenAddr,
msg.sender,
recipient,
dstChainId,
tokenId,
msg.value
);
return;
}
revert(_ERR721_SWAP_NO_PAIR);
}
| 3,850,073 |
./full_match/84531/0x352526ec35BAFb288d2A1c302f6625e1ce85aaEa/sources/contracts/WeightedPoolProtocolFees.sol | Returns the all time high value for the weighted product of the Pool's tokens' rates. Yield protocol fees are only charged when this value is exceeded./ | function getATHRateProduct() public view returns (uint256) {
return _athRateProduct;
}
| 14,299,083 |
./full_match/1/0x72EBDC2DB5c0A8ec1f76EEb0146C897DcC03a79B/sources/contracts/TorusPool.sol | underlying token is always WETH | function addCurvePool(address _pool) external override onlyOwner {
require(!_curvePools.contains(_pool), "pool already added");
ICurveRegistryCache curveRegistryCache_ = controller.curveRegistryCache();
curveRegistryCache_.initPool(_pool);
bool supported_ = curveRegistryCache_.hasCoinAnywhere(_pool, address(underlying)) || curveRegistryCache_.hasCoinAnywhere(_pool, _ETH_ADDRESS);
require(supported_, "coin not in pool");
address curveLpToken = curveRegistryCache_.lpToken(_pool);
require(controller.priceOracle().isTokenSupported(curveLpToken), "cannot price LP Token");
address booster = controller.convexBooster();
IERC20(curveLpToken).safeApprove(booster, type(uint256).max);
if (!weights.contains(_pool)) weights.set(_pool, 0);
require(_curvePools.add(_pool), "failed to add pool");
emit CurvePoolAdded(_pool);
}
| 8,333,362 |
pragma solidity ^0.5.0;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(account) }
return size > 0;
}
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
}
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);
}
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
//_transferOwnership(newOwner);
_pendingowner = newOwner;
emit OwnershipTransferPending(_owner, newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
address private _pendingowner;
event OwnershipTransferPending(address indexed previousOwner, address indexed newOwner);
function pendingowner() public view returns (address) {
return _pendingowner;
}
modifier onlyPendingOwner() {
require(msg.sender == _pendingowner, "Ownable: caller is not the pending owner");
_;
}
function claimOwnership() public onlyPendingOwner {
_transferOwnership(msg.sender);
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused, "Pausable: paused");
_;
}
modifier whenPaused() {
require(paused, "Pausable: not paused");
_;
}
function pause() public onlyOwner whenNotPaused {
paused = true;
emit Pause();
}
function unpause() public onlyOwner whenPaused {
paused = false;
emit Unpause();
}
}
contract ERC20Token is IERC20, Pausable {
using SafeMath for uint256;
using Address for address;
string internal _name;
string internal _symbol;
uint8 internal _decimals;
uint256 internal _totalSupply;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
constructor(string memory name, string memory symbol, uint8 decimals, uint256 totalSupply) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
_totalSupply = totalSupply;
_balances[msg.sender] = totalSupply;
emit Transfer(address(0), msg.sender, totalSupply);
}
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 returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view returns (uint256 balance) {
return _balances[account];
}
// Function that is called when a user or another contract wants to transfer funds .
function transfer(address recipient, uint256 amount)
public
whenNotPaused
returns (bool success)
{
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 value)
public
whenNotPaused
returns (bool)
{
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount)
public
whenNotPaused
returns (bool)
{
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
whenNotPaused
returns (bool)
{
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
whenNotPaused
returns (bool)
{
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
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);
}
// function mint(address account,uint256 amount) public onlyOwner returns (bool) {
// _mint(account, amount);
// return true;
// }
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);
}
function burn(address account,uint256 amount) public onlyOwner returns (bool) {
_burn(account, amount);
return true;
}
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn to the zero address");
_balances[account] = _balances[account].sub(amount);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
}
contract BigK is ERC20Token {
constructor() public
ERC20Token("BigK", "BIGK", 18, 2100000000 * (10 ** 18)) {
}
mapping (address => uint256) internal _locked_balances;
event TokenLocked(address indexed owner, uint256 value);
event TokenUnlocked(address indexed beneficiary, uint256 value);
function balanceOfLocked(address account) public view returns (uint256 balance)
{
return _locked_balances[account];
}
function lockToken(address[] memory addresses, uint256[] memory amounts)
public
onlyOwner
returns (bool) {
require(addresses.length > 0, "LockToken: address is empty");
require(addresses.length == amounts.length, "LockToken: invalid array size");
for (uint i = 0; i < addresses.length; i++) {
_lock_token(addresses[i], amounts[i]);
}
return true;
}
function lockTokenWhole(address[] memory addresses)
public
onlyOwner
returns (bool) {
require(addresses.length > 0, "LockToken: address is empty");
for (uint i = 0; i < addresses.length; i++) {
_lock_token(addresses[i], _balances[addresses[i]]);
}
return true;
}
function unlockToken(address[] memory addresses, uint256[] memory amounts)
public
onlyOwner
returns (bool) {
require(addresses.length > 0, "LockToken: unlock address is empty");
require(addresses.length == amounts.length, "LockToken: invalid array size");
for (uint i = 0; i < addresses.length; i++) {
_unlock_token(addresses[i], amounts[i]);
}
return true;
}
function _lock_token(address owner, uint256 amount) internal {
require(owner != address(0), "LockToken: lock from the zero address");
require(amount > 0, "LockToken: the amount is empty");
_balances[owner] = _balances[owner].sub(amount);
_locked_balances[owner] = _locked_balances[owner].add(amount);
emit TokenLocked(owner, amount);
}
function _unlock_token(address owner, uint256 amount) internal {
require(owner != address(0), "LockToken: lock from the zero address");
require(amount > 0, "LockToken: the amount is empty");
_locked_balances[owner] = _locked_balances[owner].sub(amount);
_balances[owner] = _balances[owner].add(amount);
emit TokenUnlocked(owner, amount);
}
event Collect(address indexed from, address indexed to, uint256 value);
event CollectLocked(address indexed from, address indexed to, uint256 value); //Lock이 해지 되었다.
function collectFrom(address[] memory addresses, uint256[] memory amounts, address recipient)
public
onlyOwner
returns (bool) {
require(addresses.length > 0, "Collect: collect address is empty");
require(addresses.length == amounts.length, "Collect: invalid array size");
for (uint i = 0; i < addresses.length; i++) {
_transfer(addresses[i], recipient, amounts[i]);
emit Collect(addresses[i], recipient, amounts[i]);
}
return true;
}
function collectFromLocked(address[] memory addresses, uint256[] memory amounts, address recipient)
public
onlyOwner
returns (bool) {
require(addresses.length > 0, "Collect: collect address is empty");
require(addresses.length == amounts.length, "Collect: invalid array size");
for (uint i = 0; i < addresses.length; i++) {
_unlock_token(addresses[i], amounts[i]);
_transfer(addresses[i], recipient, amounts[i]);
emit CollectLocked(addresses[i], recipient, amounts[i]);
}
return true;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
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;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
} | Function that is called when a user or another contract wants to transfer funds . | function transfer(address recipient, uint256 amount)
public
whenNotPaused
returns (bool success)
{
_transfer(msg.sender, recipient, amount);
return true;
}
| 249,079 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../lib/data/Transfers.sol";
import "../../lib/protobuf/IssuanceData.sol";
import "../../lib/protobuf/LendingData.sol";
import "../../lib/priceoracle/PriceOracleInterface.sol";
import "../../escrow/InstrumentEscrowInterface.sol";
import "../IssuanceBase.sol";
import "./LendingInstrument.sol";
/**
* @title 1 to 1 lending issuance contract.
*/
contract LendingIssuance is IssuanceBase {
using SafeMath for uint256;
// Constants
uint256 internal constant ENGAGEMENT_ID = 1; // Since it's 1 to 1, we use a constant engagement id 1
uint256 internal constant COLLATERAL_RATIO_DECIMALS = 10**4; // 0.01%
uint256 internal constant INTEREST_RATE_DECIMALS = 10**6; // 0.0001%
// Lending issuance properties
LendingIssuanceProperty.Data private _lip;
// Since it's a 1 to 1 lending, we could have at most one engagement
LendingEngagementProperty.Data private _lep;
// Lending custom events
bytes32 internal constant REPAY_FULL_EVENT = "repay_full";
/**
* @dev Initializes the issuance.
* @param instrumentManagerAddress Address of the instrument manager.
* @param instrumentAddress Address of the instrument.
* @param issuanceId ID of the issuance.
* @param issuanceEscrowAddress Address of the issuance escrow.
* @param makerAddress Address of the maker who creates the issuance.
* @param makerData Custom property of issuance.
* @return transfers Transfer actions for the issuance.
*/
function initialize(address instrumentManagerAddress, address instrumentAddress, uint256 issuanceId,
address issuanceEscrowAddress, address makerAddress, bytes memory makerData)
public override returns (Transfers.Transfer[] memory transfers) {
LendingInstrument lendingInstrument = LendingInstrument(instrumentAddress);
require(lendingInstrument.isMakerAllowed(makerAddress), "LendingIssuance: Maker not allowed.");
IssuanceBase._initialize(instrumentManagerAddress, instrumentAddress, issuanceId, issuanceEscrowAddress, makerAddress);
uint256 issuanceDuration;
(issuanceDuration, _lip.lendingTokenAddress, _lip.collateralTokenAddress, _lip.lendingAmount, _lip.tenorDays,
_lip.collateralRatio, _lip.interestRate) = abi.decode(makerData, (uint256, address, address, uint256, uint256, uint256, uint256));
// Validates parameters
require(_lip.collateralTokenAddress != address(0x0), "LendingIssuance: Collateral token not set.");
require(_lip.lendingTokenAddress != address(0x0), "LendingIssuance: Lending token not set.");
require(_lip.lendingAmount > 0, "Lending amount not set");
require(lendingInstrument.isIssuanceDurationValid(issuanceDuration), "LendingIssuance: Invalid duration.");
require(lendingInstrument.isTenorDaysValid(_lip.tenorDays), "LendingIssuance: Invalid tenor days.");
require(lendingInstrument.isCollateralRatioValid(_lip.collateralRatio), "LendingIssuance: Invalid collateral ratio.");
require(lendingInstrument.isInterestRateValid(_lip.interestRate), "LendingIssuance: Invalid interest rate.");
// Validate principal token balance
uint256 principalBalance = _instrumentManager.getInstrumentEscrow().getTokenBalance(makerAddress, _lip.lendingTokenAddress);
require(principalBalance >= _lip.lendingAmount, "LendingIssuance: Insufficient principal balance.");
// Sets common properties
_issuanceProperty.issuanceDueTimestamp = now.add(issuanceDuration);
_issuanceProperty.issuanceState = IssuanceProperty.IssuanceState.Engageable;
emit IssuanceCreated(_issuanceProperty.issuanceId, makerAddress, _issuanceProperty.issuanceDueTimestamp);
// Sets lending issuance properties
_lip.interestAmount = _lip.lendingAmount.mul(_lip.tenorDays).mul(_lip.interestRate).div(INTEREST_RATE_DECIMALS);
// Scheduling Issuance Due event
emit EventTimeScheduled(_issuanceProperty.issuanceId, 0, _issuanceProperty.issuanceDueTimestamp, ISSUANCE_DUE_EVENT, "");
// Transfers principal token
// Principal token inbound transfer: Maker --> Maker
transfers = new Transfers.Transfer[](1);
transfers[0] = Transfers.Transfer(Transfers.TransferType.Inbound, makerAddress,
makerAddress, _lip.lendingTokenAddress, _lip.lendingAmount);
emit AssetTransferred(_issuanceProperty.issuanceId, 0, Transfers.TransferType.Inbound, makerAddress,
makerAddress, _lip.lendingTokenAddress, _lip.lendingAmount, "Principal in");
// Create payable 1: Custodian --> Maker
_createPayable(1, 0, address(_issuanceEscrow), makerAddress, _lip.lendingTokenAddress,
_lip.lendingAmount, _issuanceProperty.issuanceDueTimestamp);
}
/**
* @dev Creates a new engagement for the issuance. Only admin(Instrument Manager) can call this method.
* @param takerAddress Address of the user who engages the issuance.
* @return engagementId ID of the engagement.
* @return transfers Asset transfer actions.
*/
function engage(address takerAddress, bytes memory /** takerData */)
public override onlyAdmin returns (uint256 engagementId, Transfers.Transfer[] memory transfers) {
require(LendingInstrument(_instrumentAddress).isTakerAllowed(takerAddress), "LendingIssuance: Taker not allowed.");
require(_issuanceProperty.issuanceState == IssuanceProperty.IssuanceState.Engageable, "Issuance not Engageable");
require(now <= _issuanceProperty.issuanceDueTimestamp, "Issuance due");
require(_engagementSet.length() == 0, "Already engaged");
// Calculate the collateral amount. Collateral is calculated at the time of engagement.
PriceOracleInterface priceOracle = LendingInstrument(_instrumentAddress).getPriceOracle();
_lep.collateralAmount = priceOracle.getOutputAmount(_lip.lendingTokenAddress, _lip.collateralTokenAddress,
_lip.lendingAmount.mul(_lip.collateralRatio).div(COLLATERAL_RATIO_DECIMALS));
// Validates collateral balance
uint256 collateralBalance = _instrumentManager.getInstrumentEscrow().getTokenBalance(takerAddress, _lip.collateralTokenAddress);
require(collateralBalance >= _lep.collateralAmount, "Insufficient collateral balance");
// Set common engagement property
EngagementProperty.Data storage engagement = _engagements[ENGAGEMENT_ID];
engagement.engagementId = ENGAGEMENT_ID;
engagement.takerAddress = takerAddress;
engagement.engagementCreationTimestamp = now;
engagement.engagementDueTimestamp = now.add(_lip.tenorDays * 1 days);
engagement.engagementState = EngagementProperty.EngagementState.Active;
emit EngagementCreated(_issuanceProperty.issuanceId, ENGAGEMENT_ID, takerAddress);
// Set common issuance property
_issuanceProperty.issuanceState = IssuanceProperty.IssuanceState.Complete;
_issuanceProperty.issuanceCompleteTimestamp = now;
_issuanceProperty.completionRatio = COMPLETION_RATIO_RANGE;
emit IssuanceComplete(_issuanceProperty.issuanceId, COMPLETION_RATIO_RANGE);
// Sets lending-specific engagement property
_lep.loanState = LendingEngagementProperty.LoanState.Unpaid;
engagementId = ENGAGEMENT_ID;
_engagementSet.add(ENGAGEMENT_ID);
// Scheduling Lending Engagement Due event
emit EventTimeScheduled(_issuanceProperty.issuanceId, ENGAGEMENT_ID, engagement.engagementDueTimestamp,
ENGAGEMENT_DUE_EVENT, "");
transfers = new Transfers.Transfer[](2);
// Collateral token inbound transfer: Taker -> Taker
transfers[0] = Transfers.Transfer(Transfers.TransferType.Inbound, takerAddress, takerAddress,
_lip.collateralTokenAddress, _lep.collateralAmount);
emit AssetTransferred(_issuanceProperty.issuanceId, ENGAGEMENT_ID, Transfers.TransferType.Inbound, takerAddress, takerAddress,
_lip.collateralTokenAddress, _lep.collateralAmount, "Collateral in");
// Principal token outbound transfer: Maker --> Taker
transfers[1] = Transfers.Transfer(Transfers.TransferType.Outbound, _issuanceProperty.makerAddress, takerAddress,
_lip.lendingTokenAddress, _lip.lendingAmount);
emit AssetTransferred(_issuanceProperty.issuanceId, ENGAGEMENT_ID, Transfers.TransferType.Outbound,
_issuanceProperty.makerAddress, takerAddress, _lip.lendingTokenAddress, _lip.lendingAmount, "Principal out");
// Create payable 2: Custodian --> Taker
_createPayable(2, ENGAGEMENT_ID, address(_issuanceEscrow), takerAddress, _lip.collateralTokenAddress,
_lep.collateralAmount, engagement.engagementDueTimestamp);
// Create payable 3: Taker --> Maker
_createPayable(3, ENGAGEMENT_ID, takerAddress, _issuanceProperty.makerAddress, _lip.lendingTokenAddress,
_lip.lendingAmount, engagement.engagementDueTimestamp);
// Create payable 4: Taker --> Maker
_createPayable(4, ENGAGEMENT_ID, takerAddress, _issuanceProperty.makerAddress, _lip.lendingTokenAddress,
_lip.interestAmount, engagement.engagementDueTimestamp);
// Mark payable 1 as reinitiated by payable 3
_reinitiatePayable(1, 3);
}
/**
* @dev Process a custom event. This event could be targeted at an engagement or the whole issuance.
* Only admin(Instrument Manager) can call this method.
* @param notifierAddress Address that notifies the custom event.
* @param eventName Name of the custom event.
* @return transfers Asset transfer actions.
*/
function processEvent(uint256 /** engagementId */, address notifierAddress, bytes32 eventName, bytes memory /** eventData */)
public override onlyAdmin returns (Transfers.Transfer[] memory transfers) {
if (eventName == ISSUANCE_DUE_EVENT) {
return _processIssuanceDue();
} else if (eventName == ENGAGEMENT_DUE_EVENT) {
return _processEngagementDue();
} else if (eventName == CANCEL_ISSUANCE_EVENT) {
return _cancelIssuance(notifierAddress);
} else if (eventName == REPAY_FULL_EVENT) {
return _repayLendingEngagement(notifierAddress);
} else {
revert("Unknown event");
}
}
/**
* @dev Processes the Issuance Due event.
*/
function _processIssuanceDue() private returns (Transfers.Transfer[] memory transfers) {
// Engagement Due will be processed only when:
// 1. Issuance is in Engageable state, which means there is no Engagement. Otherwise the issuance is in Complete state.
// 2. Issuance due timestamp is passed
if (_issuanceProperty.issuanceState != IssuanceProperty.IssuanceState.Engageable
|| now < _issuanceProperty.issuanceDueTimestamp) return new Transfers.Transfer[](0);
// The issuance is now complete
_issuanceProperty.issuanceState = IssuanceProperty.IssuanceState.Complete;
_issuanceProperty.issuanceCompleteTimestamp = now;
emit IssuanceComplete(_issuanceProperty.issuanceId, 0);
transfers = new Transfers.Transfer[](1);
// Principal token outbound transfer: Maler --> Maker
transfers[0] = Transfers.Transfer(Transfers.TransferType.Outbound, _issuanceProperty.makerAddress,
_issuanceProperty.makerAddress, _lip.lendingTokenAddress, _lip.lendingAmount);
emit AssetTransferred(_issuanceProperty.issuanceId, 0, Transfers.TransferType.Outbound,
_issuanceProperty.makerAddress, _issuanceProperty.makerAddress, _lip.lendingTokenAddress, _lip.lendingAmount, "Principal out");
// Mark payable 1 as paid
_markPayableAsPaid(1);
}
/**
* @dev Processes the Engagement Due event.
*/
function _processEngagementDue() private returns (Transfers.Transfer[] memory transfers) {
// Lending Engagement Due will be processed only when:
// 1. Lending Issuance is in Complete state
// 2. Lending Engagement is in Active State
// 3. Lending Engegement loan is in Unpaid State
// 2. Lending engegement due timestamp has passed
if (_issuanceProperty.issuanceState != IssuanceProperty.IssuanceState.Complete) return new Transfers.Transfer[](0);
EngagementProperty.Data storage engagement = _engagements[ENGAGEMENT_ID];
if (engagement.engagementState != EngagementProperty.EngagementState.Active ||
_lep.loanState != LendingEngagementProperty.LoanState.Unpaid ||
now < engagement.engagementDueTimestamp) {
return new Transfers.Transfer[](0);
}
// The engagement is now complete
engagement.engagementState = EngagementProperty.EngagementState.Complete;
engagement.engagementCompleteTimestamp = now;
_lep.loanState = LendingEngagementProperty.LoanState.Delinquent;
emit EngagementComplete(_issuanceProperty.issuanceId, ENGAGEMENT_ID);
transfers = new Transfers.Transfer[](1);
// Collateral token outbound transfer: Taker --> Maker
transfers[0] = Transfers.Transfer(Transfers.TransferType.Outbound, engagement.takerAddress, _issuanceProperty.makerAddress,
_lip.collateralTokenAddress, _lep.collateralAmount);
emit AssetTransferred(_issuanceProperty.issuanceId, ENGAGEMENT_ID, Transfers.TransferType.Outbound,
engagement.takerAddress, _issuanceProperty.makerAddress, _lip.collateralTokenAddress, _lep.collateralAmount, "Collateral out");
// Mark payable 2 as paid
_markPayableAsPaid(2);
// Mark payble 3 & 4 as due
_markPayableAsDue(3);
_markPayableAsDue(4);
}
/**
* @dev Cancels the lending issuance.
* @param notifierAddress Address of the caller who cancels the issuance.
*/
function _cancelIssuance(address notifierAddress) private returns (Transfers.Transfer[] memory transfers) {
// Cancel Issuance must be processed in Engageable state
require(_issuanceProperty.issuanceState == IssuanceProperty.IssuanceState.Engageable, "Cancel issuance not engageable");
// Only maker can cancel issuance
require(notifierAddress == _issuanceProperty.makerAddress, "Only maker can cancel issuance");
// The issuance is now cancelled
_issuanceProperty.issuanceState = IssuanceProperty.IssuanceState.Cancelled;
_issuanceProperty.issuanceCancelTimestamp = now;
emit IssuanceCancelled(_issuanceProperty.issuanceId);
transfers = new Transfers.Transfer[](1);
// Principal token outbound transfer: Makr --> Maker
transfers[0] = Transfers.Transfer(Transfers.TransferType.Outbound, _issuanceProperty.makerAddress, _issuanceProperty.makerAddress,
_lip.lendingTokenAddress, _lip.lendingAmount);
emit AssetTransferred(_issuanceProperty.issuanceId, 0, Transfers.TransferType.Outbound,
_issuanceProperty.makerAddress, _issuanceProperty.makerAddress, _lip.lendingTokenAddress, _lip.lendingAmount, "Principal out");
// Mark payable 1 as paid
_markPayableAsPaid(1);
}
/**
* @dev Repays the issuance in full.
* @param notifierAddress Address of the caller who repays the issuance.
*/
function _repayLendingEngagement(address notifierAddress) private returns (Transfers.Transfer[] memory transfers) {
// Lending Engagement Due will be processed only when:
// 1. Lending Issuance is in Complete state
// 2. Lending Engagement is in Active State
// 3. Lending Engegement loan is in Unpaid State
// 4. Lending engegement due timestamp is not passed
EngagementProperty.Data storage engagement = _engagements[ENGAGEMENT_ID];
require(_issuanceProperty.issuanceState == IssuanceProperty.IssuanceState.Complete, "Issuance not complete");
require(engagement.engagementState == EngagementProperty.EngagementState.Active, "Engagement not active");
require(_lep.loanState == LendingEngagementProperty.LoanState.Unpaid, "Loan not unpaid");
require(now < engagement.engagementDueTimestamp, "Engagement due");
require(notifierAddress == engagement.takerAddress, "Only taker can repay");
uint256 repayAmount = _lip.lendingAmount + _lip.interestAmount;
// Validate principal token balance
uint256 principalTokenBalance = _instrumentManager.getInstrumentEscrow()
.getTokenBalance(engagement.takerAddress, _lip.lendingTokenAddress);
require(principalTokenBalance >= repayAmount, "Insufficient principal balance");
// Sets Engagement common properties
engagement.engagementState = EngagementProperty.EngagementState.Complete;
engagement.engagementCompleteTimestamp = now;
emit EngagementComplete(_issuanceProperty.issuanceId, ENGAGEMENT_ID);
// Emits Lending-specific Engagement property
_lep.loanState = LendingEngagementProperty.LoanState.Repaid;
transfers = new Transfers.Transfer[](2);
// Pricipal + Interest intra-instrument transfer: Taker -> Maker
transfers[0] = Transfers.Transfer(Transfers.TransferType.IntraInstrument, engagement.takerAddress, _issuanceProperty.makerAddress,
_lip.lendingTokenAddress, repayAmount);
emit AssetTransferred(_issuanceProperty.issuanceId, ENGAGEMENT_ID, Transfers.TransferType.IntraInstrument,
engagement.takerAddress, _issuanceProperty.makerAddress, _lip.lendingTokenAddress, _lip.lendingAmount, "Principal transfer");
emit AssetTransferred(_issuanceProperty.issuanceId, ENGAGEMENT_ID, Transfers.TransferType.IntraInstrument,
engagement.takerAddress, _issuanceProperty.makerAddress, _lip.lendingTokenAddress, _lip.interestAmount, "Interest transfer");
// Collateral outbound transfer: Taker --> Taker
transfers[1] = Transfers.Transfer(Transfers.TransferType.Outbound, engagement.takerAddress, engagement.takerAddress,
_lip.collateralTokenAddress, _lep.collateralAmount);
emit AssetTransferred(_issuanceProperty.issuanceId, ENGAGEMENT_ID, Transfers.TransferType.Outbound,
engagement.takerAddress, engagement.takerAddress, _lip.collateralTokenAddress, _lep.collateralAmount, "Collateral out");
// Mark payable 2 as paid
_markPayableAsPaid(2);
// Mark payable 3 as paid
_markPayableAsPaid(3);
// Mark payable 4 as paid
_markPayableAsPaid(4);
}
/**
* @dev Returns the issuance-specific data about the issuance.
*/
function _getIssuanceCustomProperty() internal override view returns (bytes memory) {
return LendingIssuanceProperty.encode(_lip);
}
/**
* @dev Returns the issuance-specific data about the engagement.
*/
function _getEngagementCustomProperty(uint256 /** engagementId */) internal override view returns (bytes memory) {
return LendingEngagementProperty.encode(_lep);
}
}
| Returns the issuance-specific data about the engagement./ | function _getEngagementCustomProperty(uint256 /** engagementId */) internal override view returns (bytes memory) {
return LendingEngagementProperty.encode(_lep);
}
| 5,478,468 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.7;
/*
██████ ██████ ██ ██ ███ ██ ██████
██ ██ ██ ██ ██ ████ ██ ██ ██
███████ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██
███████ ██████ ██████ ██ ████ ██████
*/
import {IERC2981Upgradeable, IERC165Upgradeable} from '@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol';
import {ERC721Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol';
import {OwnableUpgradeable} from '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import {LibUintToString} from './LibUintToString.sol';
import {CountersUpgradeable} from '@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol';
import {ArtistCreator} from './ArtistCreator.sol';
import {ECDSA} from '@openzeppelin/contracts/utils/cryptography/ECDSA.sol';
/// @title Artist
/// @author SoundXYZ - @gigamesh & @vigneshka
/// @notice This contract is used to create & sell song NFTs for the artist who owns the contract.
/// @dev Started as a fork of Mirror's Editions.sol https://github.com/mirror-xyz/editions-v1/blob/main/contracts/Editions.sol
contract ArtistV3 is ERC721Upgradeable, IERC2981Upgradeable, OwnableUpgradeable {
// ================================
// TYPES
// ================================
using LibUintToString for uint256;
using CountersUpgradeable for CountersUpgradeable.Counter;
using ECDSA for bytes32;
enum TimeType {
START,
END
}
// ============ Structs ============
struct Edition {
// The account that will receive sales revenue.
address payable fundingRecipient;
// The price at which each token will be sold, in ETH.
uint256 price;
// The number of tokens sold so far.
uint32 numSold;
// The maximum number of tokens that can be sold.
uint32 quantity;
// Royalty amount in bps
uint32 royaltyBPS;
// start timestamp of auction (in seconds since unix epoch)
uint32 startTime;
// end timestamp of auction (in seconds since unix epoch)
uint32 endTime;
// quantity of permissioned tokens
uint32 permissionedQuantity;
// whitelist signer address
address signerAddress;
}
// ================================
// STORAGE
// ================================
string internal baseURI;
CountersUpgradeable.Counter private atTokenId; // DEPRECATED IN V3
CountersUpgradeable.Counter private atEditionId;
// Mapping of edition id to descriptive data.
mapping(uint256 => Edition) public editions;
// <DEPRECATED IN V3> Mapping of token id to edition id.
mapping(uint256 => uint256) private _tokenToEdition;
// The amount of funds that have been deposited for a given edition.
mapping(uint256 => uint256) public depositedForEdition;
// The amount of funds that have already been withdrawn for a given edition.
mapping(uint256 => uint256) public withdrawnForEdition;
// The permissioned typehash (used for checking signature validity)
bytes32 private constant PERMISSIONED_SALE_TYPEHASH =
keccak256('EditionInfo(address contractAddress,address buyerAddress,uint256 editionId)');
bytes32 private immutable DOMAIN_SEPARATOR;
// ================================
// EVENTS
// ================================
event EditionCreated(
uint256 indexed editionId,
address fundingRecipient,
uint256 price,
uint32 quantity,
uint32 royaltyBPS,
uint32 startTime,
uint32 endTime,
uint32 permissionedQuantity,
address signerAddress
);
event EditionPurchased(
uint256 indexed editionId,
uint256 indexed tokenId,
// `numSold` at time of purchase represents the "serial number" of the NFT.
uint32 numSold,
// The account that paid for and received the NFT.
address indexed buyer
);
event AuctionTimeSet(TimeType timeType, uint256 editionId, uint32 indexed newTime);
event SignerAddressSet(uint256 editionId, address indexed signerAddress);
event PermissionedQuantitySet(uint256 editionId, uint32 permissionedQuantity);
// ================================
// PUBLIC & EXTERNAL WRITABLE FUNCTIONS
// ================================
/// @notice Contract constructor
constructor() {
DOMAIN_SEPARATOR = keccak256(abi.encode(keccak256('EIP712Domain(uint256 chainId)'), block.chainid));
}
/// @notice Initializes the contract
/// @param _owner Owner of edition
/// @param _name Name of artist
function initialize(
address _owner,
uint256 _artistId,
string memory _name,
string memory _symbol,
string memory _baseURI
) public initializer {
__ERC721_init(_name, _symbol);
__Ownable_init();
// Set ownership to original sender of contract call
transferOwnership(_owner);
// E.g. https://sound.xyz/api/metadata/[artistId]/
baseURI = string(abi.encodePacked(_baseURI, _artistId.toString(), '/'));
// Set edition id start to be 1 not 0
atEditionId.increment();
}
/// @notice Creates a new edition.
/// @param _fundingRecipient The account that will receive sales revenue.
/// @param _price The price at which each token will be sold, in ETH.
/// @param _quantity The maximum number of tokens that can be sold.
/// @param _royaltyBPS The royalty amount in bps.
/// @param _startTime The start time of the auction, in seconds since unix epoch.
/// @param _endTime The end time of the auction, in seconds since unix epoch.
/// @param _permissionedQuantity The quantity of tokens that require a signature to buy.
/// @param _signerAddress signer address.
function createEdition(
address payable _fundingRecipient,
uint256 _price,
uint32 _quantity,
uint32 _royaltyBPS,
uint32 _startTime,
uint32 _endTime,
uint32 _permissionedQuantity,
address _signerAddress
) external onlyOwner {
require(_permissionedQuantity < _quantity + 1, 'Permissioned quantity too big');
require(_quantity > 0, 'Must set quantity');
require(_fundingRecipient != address(0), 'Must set fundingRecipient');
require(_endTime > _startTime, 'End time must be greater than start time');
if (_permissionedQuantity > 0) {
require(_signerAddress != address(0), 'Signer address cannot be 0');
}
editions[atEditionId.current()] = Edition({
fundingRecipient: _fundingRecipient,
price: _price,
numSold: 0,
quantity: _quantity,
royaltyBPS: _royaltyBPS,
startTime: _startTime,
endTime: _endTime,
permissionedQuantity: _permissionedQuantity,
signerAddress: _signerAddress
});
emit EditionCreated(
atEditionId.current(),
_fundingRecipient,
_price,
_quantity,
_royaltyBPS,
_startTime,
_endTime,
_permissionedQuantity,
_signerAddress
);
atEditionId.increment();
}
/// @notice Creates a new token for the given edition, and assigns it to the buyer
/// @param _editionId The id of the edition to purchase
/// @param _signature A signed message for authorizing permissioned purchases
function buyEdition(uint256 _editionId, bytes calldata _signature) external payable {
// Caching variables locally to reduce reads
uint256 price = editions[_editionId].price;
uint32 quantity = editions[_editionId].quantity;
uint32 numSold = editions[_editionId].numSold;
uint32 startTime = editions[_editionId].startTime;
uint32 endTime = editions[_editionId].endTime;
uint32 permissionedQuantity = editions[_editionId].permissionedQuantity;
// Check that the edition exists. Note: this is redundant
// with the next check, but it is useful for clearer error messaging.
require(quantity > 0, 'Edition does not exist');
// Check that there are still tokens available to purchase.
require(numSold < quantity, 'This edition is already sold out.');
// Check that the sender is paying the correct amount.
require(msg.value >= price, 'Must send enough to purchase the edition.');
// If the open auction hasn't started...
if (startTime > block.timestamp) {
// Check that permissioned tokens are still available
require(
permissionedQuantity > 0 && numSold < permissionedQuantity,
'No permissioned tokens available & open auction not started'
);
// Check that the signature is valid.
require(getSigner(_signature, _editionId) == editions[_editionId].signerAddress, 'Invalid signer');
}
// Don't allow purchases after the end time
require(endTime > block.timestamp, 'Auction has ended');
// Create the token id by packing editionId in the top bits
uint256 tokenId;
unchecked {
tokenId = (_editionId << 128) | (numSold + 1);
// Increment the number of tokens sold for this edition.
editions[_editionId].numSold = numSold + 1;
}
// If fundingRecipient is the owner (artist's wallet), update the edition's balance & don't send the funds
if (editions[_editionId].fundingRecipient == owner()) {
// Update the deposited total for the edition
depositedForEdition[_editionId] += msg.value;
} else {
// Send funds to the funding recipient.
_sendFunds(editions[_editionId].fundingRecipient, msg.value);
}
// Mint a new token for the sender, using the `tokenId`.
_mint(msg.sender, tokenId);
emit EditionPurchased(_editionId, tokenId, editions[_editionId].numSold, msg.sender);
}
function withdrawFunds(uint256 _editionId) external {
// Compute the amount available for withdrawing from this edition.
uint256 remainingForEdition = depositedForEdition[_editionId] - withdrawnForEdition[_editionId];
// Set the amount withdrawn to the amount deposited.
withdrawnForEdition[_editionId] = depositedForEdition[_editionId];
// Send the amount that was remaining for the edition, to the funding recipient.
_sendFunds(editions[_editionId].fundingRecipient, remainingForEdition);
}
/// @notice Sets the start time for an edition
function setStartTime(uint256 _editionId, uint32 _startTime) external onlyOwner {
editions[_editionId].startTime = _startTime;
emit AuctionTimeSet(TimeType.START, _editionId, _startTime);
}
/// @notice Sets the end time for an edition
function setEndTime(uint256 _editionId, uint32 _endTime) external onlyOwner {
editions[_editionId].endTime = _endTime;
emit AuctionTimeSet(TimeType.END, _editionId, _endTime);
}
/// @notice Sets the signature address of an edition
function setSignerAddress(uint256 _editionId, address _newSignerAddress) external onlyOwner {
require(_newSignerAddress != address(0), 'Signer address cannot be 0');
editions[_editionId].signerAddress = _newSignerAddress;
emit SignerAddressSet(_editionId, _newSignerAddress);
}
/// @notice Sets the permissioned quantity for an edition
function setPermissionedQuantity(uint256 _editionId, uint32 _permissionedQuantity) external onlyOwner {
// Check that the permissioned quantity is less than the total quantity
require(_permissionedQuantity < editions[_editionId].quantity + 1, 'Must not exceed quantity');
// Prevent setting to permissioned quantity when there is no signer address
require(editions[_editionId].signerAddress != address(0), 'Edition must have a signer');
editions[_editionId].permissionedQuantity = _permissionedQuantity;
emit PermissionedQuantitySet(_editionId, _permissionedQuantity);
}
// ================================
// VIEW FUNCTIONS
// ================================
/// @notice Returns token URI (metadata URL). e.g. https://sound.xyz/api/metadata/[artistId]/[editionId]/[tokenId]
/// @dev Concatenate the baseURI, editionId and tokenId, to create URI.
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), 'ERC721Metadata: URI query for nonexistent token');
uint256 editionId = tokenToEdition(_tokenId);
return string(abi.encodePacked(baseURI, editionId.toString(), '/', _tokenId.toString()));
}
/// @notice Returns contract URI used by Opensea. e.g. https://sound.xyz/api/metadata/[artistId]/storefront
function contractURI() public view returns (string memory) {
return string(abi.encodePacked(baseURI, 'storefront'));
}
/// @notice Get royalty information for token
/// @param _tokenId token id
/// @param _salePrice Sale price for the token
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
override
returns (address fundingRecipient, uint256 royaltyAmount)
{
uint256 editionId = tokenToEdition(_tokenId);
Edition memory edition = editions[editionId];
if (edition.fundingRecipient == address(0x0)) {
return (edition.fundingRecipient, 0);
}
uint256 royaltyBPS = uint256(edition.royaltyBPS);
return (edition.fundingRecipient, (_salePrice * royaltyBPS) / 10_000);
}
/// @notice The total number of tokens created by this contract
function totalSupply() external view returns (uint256) {
uint256 total = 0;
for (uint256 id = 1; id < atEditionId.current(); id++) {
total += editions[id].numSold;
}
return total;
}
/// @notice Informs other contracts which interfaces this contract supports
/// @dev https://eips.ethereum.org/EIPS/eip-165
function supportsInterface(bytes4 _interfaceId)
public
view
override(ERC721Upgradeable, IERC165Upgradeable)
returns (bool)
{
return
type(IERC2981Upgradeable).interfaceId == _interfaceId || ERC721Upgradeable.supportsInterface(_interfaceId);
}
/// @notice returns the number of editions for this artist
function editionCount() external view returns (uint256) {
return atEditionId.current() - 1; // because atEditionId is incremented after each edition is created
}
function tokenToEdition(uint256 _tokenId) public view returns (uint256) {
// Check the top bits to see if the edition id is there
uint256 editionId = _tokenId >> 128;
// If edition ID is 0, then this edition was created before the V3 upgrade
if (editionId == 0) {
// get edition ID from storage
return _tokenToEdition[_tokenId];
}
return editionId;
}
function ownersOfTokenIds(uint256[] calldata _tokenIds) external view returns (address[] memory) {
address[] memory owners = new address[](_tokenIds.length);
for (uint256 i = 0; i < _tokenIds.length; i++) {
owners[i] = ownerOf(_tokenIds[i]);
}
return owners;
}
// ================================
// FUNCTIONS - PRIVATE
// ================================
/// @notice Sends funds to an address
/// @param _recipient The address to send funds to
/// @param _amount The amount of funds to send
function _sendFunds(address payable _recipient, uint256 _amount) private {
require(address(this).balance >= _amount, 'Insufficient balance for send');
(bool success, ) = _recipient.call{value: _amount}('');
require(success, 'Unable to send value: recipient may have reverted');
}
/// @notice Gets signer address to validate permissioned purchase
/// @param _signature signed message
/// @param _editionId edition id
/// @return address of signer
/// @dev https://eips.ethereum.org/EIPS/eip-712
function getSigner(bytes calldata _signature, uint256 _editionId) private view returns (address) {
bytes32 digest = keccak256(
abi.encodePacked(
'\x19\x01',
DOMAIN_SEPARATOR,
keccak256(abi.encode(PERMISSIONED_SALE_TYPEHASH, address(this), msg.sender, _editionId))
)
);
address recoveredAddress = digest.recover(_signature);
return recoveredAddress;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981Upgradeable is IERC165Upgradeable {
/**
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
library LibUintToString {
uint256 private constant MAX_UINT256_STRING_LENGTH = 78;
uint8 private constant ASCII_DIGIT_OFFSET = 48;
/// @dev Converts a `uint256` value to a string.
/// @param n The integer to convert.
/// @return nstr `n` as a decimal string.
function toString(uint256 n) internal pure returns (string memory nstr) {
if (n == 0) {
return '0';
}
// Overallocate memory
nstr = new string(MAX_UINT256_STRING_LENGTH);
uint256 k = MAX_UINT256_STRING_LENGTH;
// Populate string from right to left (lsb to msb).
while (n != 0) {
assembly {
let char := add(ASCII_DIGIT_OFFSET, mod(n, 10))
mstore(add(nstr, k), char)
k := sub(k, 1)
n := div(n, 10)
}
}
assembly {
// Shift pointer over to actual start of string.
nstr := add(nstr, k)
// Store actual string length.
mstore(nstr, sub(MAX_UINT256_STRING_LENGTH, k))
}
return nstr;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.7;
/*
██████ ██████ ██ ██ ███ ██ ██████
██ ██ ██ ██ ██ ████ ██ ██ ██
███████ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██
███████ ██████ ██████ ██ ████ ██████
*/
import '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol';
import '@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol';
import '@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol';
import '@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol';
import '@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol';
import './Artist.sol';
contract ArtistCreator is Initializable, UUPSUpgradeable, OwnableUpgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
using ECDSAUpgradeable for bytes32;
// ============ Storage ============
bytes32 public constant MINTER_TYPEHASH = keccak256('Deployer(address artistWallet)');
CountersUpgradeable.Counter private atArtistId;
// address used for signature verification, changeable by owner
address public admin;
bytes32 public DOMAIN_SEPARATOR;
address public beaconAddress;
// registry of created contracts
address[] public artistContracts;
// ============ Events ============
/// Emitted when an Artist is created
event CreatedArtist(uint256 artistId, string name, string symbol, address indexed artistAddress);
// ============ Functions ============
/// Initializes factory
function initialize() public initializer {
__Ownable_init_unchained();
// set admin for artist deployment authorization
admin = msg.sender;
DOMAIN_SEPARATOR = keccak256(abi.encode(keccak256('EIP712Domain(uint256 chainId)'), block.chainid));
// set up beacon with msg.sender as the owner
UpgradeableBeacon _beacon = new UpgradeableBeacon(address(new Artist()));
_beacon.transferOwnership(msg.sender);
beaconAddress = address(_beacon);
// Set artist id start to be 1 not 0
atArtistId.increment();
}
/// Creates a new artist contract as a factory with a deterministic address
/// Important: None of these fields (except the Url fields with the same hash) can be changed after calling
/// @param _name Name of the artist
function createArtist(
bytes calldata signature,
string memory _name,
string memory _symbol,
string memory _baseURI
) public returns (address) {
require((getSigner(signature) == admin), 'invalid authorization signature');
BeaconProxy proxy = new BeaconProxy(
beaconAddress,
abi.encodeWithSelector(
Artist(address(0)).initialize.selector,
msg.sender,
atArtistId.current(),
_name,
_symbol,
_baseURI
)
);
// add to registry
artistContracts.push(address(proxy));
emit CreatedArtist(atArtistId.current(), _name, _symbol, address(proxy));
atArtistId.increment();
return address(proxy);
}
/// Get signer address of signature
function getSigner(bytes calldata signature) public view returns (address) {
require(admin != address(0), 'whitelist not enabled');
// Verify EIP-712 signature by recreating the data structure
// that we signed on the client side, and then using that to recover
// the address that signed the signature for this data.
bytes32 digest = keccak256(
abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(MINTER_TYPEHASH, msg.sender)))
);
// Use the recover method to see what address was used to create
// the signature on this data.
// Note that if the digest doesn't exactly match what was signed we'll
// get a random recovered address.
address recoveredAddress = digest.recover(signature);
return recoveredAddress;
}
/// Sets the admin for authorizing artist deployment
/// @param _newAdmin address of new admin
function setAdmin(address _newAdmin) external {
require(owner() == _msgSender() || admin == _msgSender(), 'invalid authorization');
admin = _newAdmin;
}
function _authorizeUpgrade(address) internal override onlyOwner {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165Upgradeable.sol";
// 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;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
__UUPSUpgradeable_init_unchained();
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeTo(address newImplementation) external virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallSecure(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/BeaconProxy.sol)
pragma solidity ^0.8.0;
import "./IBeacon.sol";
import "../Proxy.sol";
import "../ERC1967/ERC1967Upgrade.sol";
/**
* @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}.
*
* The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't
* conflict with the storage layout of the implementation behind the proxy.
*
* _Available since v3.4._
*/
contract BeaconProxy is Proxy, ERC1967Upgrade {
/**
* @dev Initializes the proxy with `beacon`.
*
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This
* will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity
* constructor.
*
* Requirements:
*
* - `beacon` must be a contract with the interface {IBeacon}.
*/
constructor(address beacon, bytes memory data) payable {
assert(_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1));
_upgradeBeaconToAndCall(beacon, data, false);
}
/**
* @dev Returns the current beacon address.
*/
function _beacon() internal view virtual returns (address) {
return _getBeacon();
}
/**
* @dev Returns the current implementation address of the associated beacon.
*/
function _implementation() internal view virtual override returns (address) {
return IBeacon(_getBeacon()).implementation();
}
/**
* @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.
*
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.
*
* Requirements:
*
* - `beacon` must be a contract.
* - The implementation returned by `beacon` must be a contract.
*/
function _setBeacon(address beacon, bytes memory data) internal virtual {
_upgradeBeaconToAndCall(beacon, data, false);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/UpgradeableBeacon.sol)
pragma solidity ^0.8.0;
import "./IBeacon.sol";
import "../../access/Ownable.sol";
import "../../utils/Address.sol";
/**
* @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their
* implementation contract, which is where they will delegate all function calls.
*
* An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.
*/
contract UpgradeableBeacon is IBeacon, Ownable {
address private _implementation;
/**
* @dev Emitted when the implementation returned by the beacon is changed.
*/
event Upgraded(address indexed implementation);
/**
* @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the
* beacon.
*/
constructor(address implementation_) {
_setImplementation(implementation_);
}
/**
* @dev Returns the current implementation address.
*/
function implementation() public view virtual override returns (address) {
return _implementation;
}
/**
* @dev Upgrades the beacon to a new implementation.
*
* Emits an {Upgraded} event.
*
* Requirements:
*
* - msg.sender must be the owner of the contract.
* - `newImplementation` must be a contract.
*/
function upgradeTo(address newImplementation) public virtual onlyOwner {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Sets the implementation contract address for this beacon
*
* Requirements:
*
* - `newImplementation` must be a contract.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "UpgradeableBeacon: implementation is not a contract");
_implementation = newImplementation;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.7;
/*
██████ ██████ ██ ██ ███ ██ ██████
██ ██ ██ ██ ██ ████ ██ ██ ██
███████ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██
███████ ██████ ██████ ██ ████ ██████
*/
import {IERC2981Upgradeable, IERC165Upgradeable} from '@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol';
import {ERC721Upgradeable} from '@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol';
import {OwnableUpgradeable} from '@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol';
import {Strings} from './Strings.sol';
import {CountersUpgradeable} from '@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol';
// This contract is a combination of Mirror.xyz's Editions.sol and Zora's SingleEditionMintable.sol
/**
* @title Artist
* @author SoundXYZ
*/
contract Artist is ERC721Upgradeable, IERC2981Upgradeable, OwnableUpgradeable {
// todo (optimization): link Strings as a deployed library
using Strings for uint256;
using CountersUpgradeable for CountersUpgradeable.Counter;
// ============ Structs ============
struct Edition {
// The account that will receive sales revenue.
address payable fundingRecipient;
// The price at which each token will be sold, in ETH.
uint256 price;
// The number of tokens sold so far.
uint32 numSold;
// The maximum number of tokens that can be sold.
uint32 quantity;
// Royalty amount in bps
uint32 royaltyBPS;
// start timestamp of auction (in seconds since unix epoch)
uint32 startTime;
// end timestamp of auction (in seconds since unix epoch)
uint32 endTime;
}
// ============ Storage ============
string internal baseURI;
CountersUpgradeable.Counter private atTokenId;
CountersUpgradeable.Counter private atEditionId;
// Mapping of edition id to descriptive data.
mapping(uint256 => Edition) public editions;
// Mapping of token id to edition id.
mapping(uint256 => uint256) public tokenToEdition;
// The amount of funds that have been deposited for a given edition.
mapping(uint256 => uint256) public depositedForEdition;
// The amount of funds that have already been withdrawn for a given edition.
mapping(uint256 => uint256) public withdrawnForEdition;
// ============ Events ============
event EditionCreated(
uint256 indexed editionId,
address fundingRecipient,
uint256 price,
uint32 quantity,
uint32 royaltyBPS,
uint32 startTime,
uint32 endTime
);
event EditionPurchased(
uint256 indexed editionId,
uint256 indexed tokenId,
// `numSold` at time of purchase represents the "serial number" of the NFT.
uint32 numSold,
// The account that paid for and received the NFT.
address indexed buyer
);
// ============ Methods ============
/**
@param _owner Owner of edition
@param _name Name of artist
*/
function initialize(
address _owner,
uint256 _artistId,
string memory _name,
string memory _symbol,
string memory _baseURI
) public initializer {
__ERC721_init(_name, _symbol);
__Ownable_init();
// Set ownership to original sender of contract call
transferOwnership(_owner);
// E.g. https://sound.xyz/api/metadata/[artistId]/
baseURI = string(abi.encodePacked(_baseURI, _artistId.toString(), '/'));
// Set token id start to be 1 not 0
atTokenId.increment();
// Set edition id start to be 1 not 0
atEditionId.increment();
}
function createEdition(
address payable _fundingRecipient,
uint256 _price,
uint32 _quantity,
uint32 _royaltyBPS,
uint32 _startTime,
uint32 _endTime
) external onlyOwner {
editions[atEditionId.current()] = Edition({
fundingRecipient: _fundingRecipient,
price: _price,
numSold: 0,
quantity: _quantity,
royaltyBPS: _royaltyBPS,
startTime: _startTime,
endTime: _endTime
});
emit EditionCreated(
atEditionId.current(),
_fundingRecipient,
_price,
_quantity,
_royaltyBPS,
_startTime,
_endTime
);
atEditionId.increment();
}
function buyEdition(uint256 _editionId) external payable {
// Check that the edition exists. Note: this is redundant
// with the next check, but it is useful for clearer error messaging.
require(editions[_editionId].quantity > 0, 'Edition does not exist');
// Check that there are still tokens available to purchase.
require(editions[_editionId].numSold < editions[_editionId].quantity, 'This edition is already sold out.');
// Check that the sender is paying the correct amount.
require(msg.value >= editions[_editionId].price, 'Must send enough to purchase the edition.');
// Don't allow purchases before the start time
require(editions[_editionId].startTime < block.timestamp, "Auction hasn't started");
// Don't allow purchases after the end time
require(editions[_editionId].endTime > block.timestamp, 'Auction has ended');
// Mint a new token for the sender, using the `tokenId`.
_mint(msg.sender, atTokenId.current());
// Update the deposited total for the edition
depositedForEdition[_editionId] += msg.value;
// Increment the number of tokens sold for this edition.
editions[_editionId].numSold++;
// Store the mapping of token id to the edition being purchased.
tokenToEdition[atTokenId.current()] = _editionId;
emit EditionPurchased(_editionId, atTokenId.current(), editions[_editionId].numSold, msg.sender);
atTokenId.increment();
}
// ============ Operational Methods ============
function withdrawFunds(uint256 _editionId) external {
// Compute the amount available for withdrawing from this edition.
uint256 remainingForEdition = depositedForEdition[_editionId] - withdrawnForEdition[_editionId];
// Set the amount withdrawn to the amount deposited.
withdrawnForEdition[_editionId] = depositedForEdition[_editionId];
// Send the amount that was remaining for the edition, to the funding recipient.
_sendFunds(editions[_editionId].fundingRecipient, remainingForEdition);
}
function setStartTime(uint256 _editionId, uint32 _startTime) external onlyOwner {
editions[_editionId].startTime = _startTime;
}
function setEndTime(uint256 _editionId, uint32 _endTime) external onlyOwner {
editions[_editionId].endTime = _endTime;
}
// ============ NFT Methods ============
// Returns e.g. https://sound.xyz/api/metadata/[artistId]/[editionId]/[tokenId]
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), 'ERC721Metadata: URI query for nonexistent token');
// Concatenate the components, baseURI, editionId and tokenId, to create URI.
return string(abi.encodePacked(baseURI, tokenToEdition[_tokenId].toString(), '/', _tokenId.toString()));
}
// Returns e.g. https://sound.xyz/api/metadata/[artistId]/storefront
function contractURI() public view returns (string memory) {
// Concatenate the components, baseURI, editionId and tokenId, to create URI.
return string(abi.encodePacked(baseURI, 'storefront'));
}
// ============ Extensions =================
/**
@dev Get token ids for a given edition id
@param _editionId edition id
*/
function getTokenIdsOfEdition(uint256 _editionId) public view returns (uint256[] memory) {
uint256[] memory tokenIdsOfEdition = new uint256[](editions[_editionId].numSold);
uint256 index = 0;
for (uint256 id = 1; id < atTokenId.current(); id++) {
if (tokenToEdition[id] == _editionId) {
tokenIdsOfEdition[index] = id;
index++;
}
}
return tokenIdsOfEdition;
}
/**
@dev Get owners of a given edition id
@param _editionId edition id
*/
function getOwnersOfEdition(uint256 _editionId) public view returns (address[] memory) {
address[] memory ownersOfEdition = new address[](editions[_editionId].numSold);
uint256 index = 0;
for (uint256 id = 1; id < atTokenId.current(); id++) {
if (tokenToEdition[id] == _editionId) {
ownersOfEdition[index] = ERC721Upgradeable.ownerOf(id);
index++;
}
}
return ownersOfEdition;
}
/**
@dev Get royalty information for token
@param _editionId edition id
@param _salePrice Sale price for the token
*/
function royaltyInfo(uint256 _editionId, uint256 _salePrice)
external
view
override
returns (address fundingRecipient, uint256 royaltyAmount)
{
Edition memory edition = editions[_editionId];
if (edition.fundingRecipient == address(0x0)) {
return (edition.fundingRecipient, 0);
}
uint256 royaltyBPS = uint256(edition.royaltyBPS);
return (edition.fundingRecipient, (_salePrice * royaltyBPS) / 10_000);
}
function totalSupply() external view returns (uint256) {
return atTokenId.current() - 1; // because atTokenId is 1-indexed
}
function supportsInterface(bytes4 _interfaceId)
public
view
override(ERC721Upgradeable, IERC165Upgradeable)
returns (bool)
{
return
type(IERC2981Upgradeable).interfaceId == _interfaceId || ERC721Upgradeable.supportsInterface(_interfaceId);
}
// ============ Private Methods ============
function _sendFunds(address payable _recipient, uint256 _amount) private {
require(address(this).balance >= _amount, 'Insufficient balance for send');
(bool success, ) = _recipient.call{value: _amount}('');
require(success, 'Unable to send value: recipient may have reverted');
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable {
function __ERC1967Upgrade_init() internal onlyInitializing {
__ERC1967Upgrade_init_unchained();
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
_functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
_functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
_functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) {
require(AddressUpgradeable.isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/Proxy.sol)
pragma solidity ^0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback() external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive() external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeacon.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967Upgrade {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallSecure(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
address oldImplementation = _getImplementation();
// Initial upgrade and setup call
_setImplementation(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
// Perform rollback test if not already in progress
StorageSlot.BooleanSlot storage rollbackTesting = StorageSlot.getBooleanSlot(_ROLLBACK_SLOT);
if (!rollbackTesting.value) {
// Trigger rollback using upgradeTo from the new implementation
rollbackTesting.value = true;
Address.functionDelegateCall(
newImplementation,
abi.encodeWithSignature("upgradeTo(address)", oldImplementation)
);
rollbackTesting.value = false;
// Check rollback was effective
require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades");
// Finally reset to the new implementation and log the upgrade
_upgradeTo(newImplementation);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(Address.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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: GPL-3.0-or-later
pragma solidity 0.8.7;
// This contract is a combination of Mirror.xyz's Editions.sol and Zora's SingleEditionMintable.sol
/**
* @title Utils
* @author SoundXYZ
*/
library Strings {
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol
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);
}
}
// 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);
}
} | Informs other contracts which interfaces this contract supports https://eips.ethereum.org/EIPS/eip-165 | function supportsInterface(bytes4 _interfaceId)
public
view
override(ERC721Upgradeable, IERC165Upgradeable)
returns (bool)
{
return
type(IERC2981Upgradeable).interfaceId == _interfaceId || ERC721Upgradeable.supportsInterface(_interfaceId);
}
| 5,724,113 |
pragma solidity 0.4.23;
import "./Ownable.sol";
/** @title User
* @dev User is the base class for all'the users: Student, Professor and Admin
*/
contract User is Ownable {
bytes private name;
bytes private surname;
bytes private socialNumber;
uint private serial;
/** @dev Constructor of User
* @param _name user name
* @param _surname user surname
* @param _socialNumber user social number
* @param _serial user indentifier inside the university
*/
constructor( bytes _name, bytes _surname, bytes _socialNumber, uint _serial) public {
name = _name;
surname = _surname;
socialNumber = _socialNumber;
serial = _serial;
}
/** @dev get for user name
* @return bytes the string of the name
*/
function getName() public view returns(bytes) {
return name;
}
/** @dev get for user surname
* @return bytes the string of the surname
*/
function getSurname() public view returns(bytes) {
return surname;
}
/** @dev get for user social number
* @return bytes the string of the social number
*/
function getSocialNumber() public view returns(bytes) {
return socialNumber;
}
/** @dev get for user serial
* @return uint the string of the serial
*/
function getSerial() public view returns(uint) {
return serial;
}
}
| get for user surname return bytes the string of the surname/ | function getSurname() public view returns(bytes) {
return surname;
}
| 6,343,171 |
./partial_match/1/0xa482246fFFBf92659A22525820C665D4aFfCF97B/sources/ETFloft.sol | Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`, `r` and `s` signature fields separately./ EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature unique. Appendix F in the Ethereum Yellow paper (https:ethereum.github.io/yellowpaper/paper.pdf), defines the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most signatures from current libraries generate a unique signature with an s-value in the lower half order. If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept these malleable signatures as well. If the signature is valid (and not malleable), return the signer address | function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
address public ETFtoken = address(0x9E101C3a19e38a02B3c2fCf0D2Be4CE62C846488);
address public loftRobot = address(0x0005f8A387Bef4Af14CA106e56A76C94DBECAD4a);
mapping(address=> uint256) public claimedETH;
mapping(address=> uint256) public claimedETF;
uint256 public round;
| 16,175,545 |
/**
*Submitted for verification at Etherscan.io on 2021-10-02
*/
// ┏━━━┓━━━━━┏┓━━━━━━━━━┏━━━┓━━━━━━━━━━━━━━━━━━━━━━━
// ┃┏━┓┃━━━━┏┛┗┓━━━━━━━━┃┏━━┛━━━━━━━━━━━━━━━━━━━━━━━
// ┃┗━┛┃┏━┓━┗┓┏┛┏━━┓━━━━┃┗━━┓┏┓┏━┓━┏━━┓━┏━┓━┏━━┓┏━━┓
// ┃┏━┓┃┃┏┓┓━┃┃━┃┏┓┃━━━━┃┏━━┛┣┫┃┏┓┓┗━┓┃━┃┏┓┓┃┏━┛┃┏┓┃
// ┃┃ ┃┃┃┃┃┃━┃┗┓┃┃━┫━┏┓━┃┃━━━┃┃┃┃┃┃┃┗┛┗┓┃┃┃┃┃┗━┓┃┃━┫
// ┗┛ ┗┛┗┛┗┛━┗━┛┗━━┛━┗┛━┗┛━━━┗┛┗┛┗┛┗━━━┛┗┛┗┛┗━━┛┗━━┛
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
interface IAnteTest {
// override the auto-generated getter for testAuthor as a public var
function testAuthor() external view returns (address);
// override the auto-generated getter for protocolName as a public var
function protocolName() external view returns (string memory);
// override the auto-generated getter for testedContracts [] as a public var
function testedContracts(uint i) external view returns (address);
// override the auto-generated getter for testName as a public var
function testName() external view returns (string memory);
// single bool function that inspects the invariant; usually True
function checkTestPasses() external returns (bool);
}
// Abstract inheritable contract to supply syntactic sugar for Ante Test writing
// Usage: contract AnteNewProtocolTest is AnteTest("String descriptor of test", "Protocol name") { ... }
abstract contract AnteTest is IAnteTest() {
address public override testAuthor;
string public override testName;
string public override protocolName;
address [] public override testedContracts;
// testedContracts and protocolName are optional parameters which should be set in the constructor of your AnteTest
constructor (string memory _testName) {
testAuthor = msg.sender;
testName = _testName;
}
function getTestedContracts() external view returns (address[] memory) {
return testedContracts;
}
function checkTestPasses() public override virtual returns (bool) {}
}
contract AnteTornadoAmountTest is
AnteTest(
"Tornado ETH pools don't fall below 1% of their supply at the time of deployment"
)
{
address public constant torn100Addr =
0xA160cdAB225685dA1d56aa342Ad8841c3b53f291;
address public constant torn10Addr =
0x910Cbd523D972eb0a6f4cAe4618aD62622b39DbF;
address public constant torn1Addr =
0x47CE0C6eD5B0Ce3d3A51fdb1C52DC66a7c3c2936;
address public constant torn01Addr =
0x12D66f87A04A9E220743712cE6d9bB1B5616B8Fc;
uint256 immutable torn100BalanceAtDeploy;
uint256 immutable torn10BalanceAtDeploy;
uint256 immutable torn1BalanceAtDeploy;
uint256 immutable torn01BalanceAtDeploy;
constructor() {
protocolName = "Tornado Cash";
testedContracts = [torn100Addr, torn10Addr, torn1Addr, torn01Addr];
torn100BalanceAtDeploy = torn100Addr.balance;
torn10BalanceAtDeploy = torn10Addr.balance;
torn1BalanceAtDeploy = torn1Addr.balance;
torn01BalanceAtDeploy = torn01Addr.balance;
}
function checkTestPasses() public view override returns (bool) {
return ((torn100BalanceAtDeploy / 100) < torn100Addr.balance &&
(torn10BalanceAtDeploy / 100) < torn10Addr.balance &&
(torn1BalanceAtDeploy / 100) < torn1Addr.balance &&
(torn01BalanceAtDeploy / 100) < torn01Addr.balance);
}
} | override the auto-generated getter for testAuthor as a public var override the auto-generated getter for protocolName as a public var override the auto-generated getter for testedContracts [] as a public var override the auto-generated getter for testName as a public var single bool function that inspects the invariant; usually True | interface IAnteTest {
function testAuthor() external view returns (address);
function protocolName() external view returns (string memory);
function testedContracts(uint i) external view returns (address);
function testName() external view returns (string memory);
function checkTestPasses() external returns (bool);
}
| 10,696,004 |
./full_match/80001/0x2b2666C612a7790aE79ba0D6F10fd0E4ADfd2775/sources/contracts/NYW/NYW_Factory.sol | only use cutoffs for string attributes, that's why the loop is until lenght -5 Here we will give each yacht different stats based on their type: | function decodeTokenId(uint256 randomValue, uint256 _tokenId)
public
view
returns (uint256[] memory)
{
require(randomValue != 0, "Tokens have not been revealed yet");
uint256 tokenCode = uint256(
keccak256(abi.encode(randomValue, _tokenId))
);
uint8[12] memory shifts = [ 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 88];
uint256[] memory tokenPart = new uint256[](shifts.length);
for (uint256 i = 0; i < shifts.length; i++) {
tokenPart[i] = (tokenCode >> shifts[i]) & BITMASK;
}
for (uint256 i = 0; i < tokenPart.length - 5; i++) {
uint256 currentIdx = 0;
for (uint256 j = 0; j < cutoffs[i].length; j++) {
if (tokenPart[i] < cutoffs[i][j]) {
currentIdx = j;
break;
}
}
tokenPart[i] = currentIdx;
}
bool typeSail = (tokenPart[uint256(Keys.yacht_type)] == 0);
bool typeEntry = (tokenPart[uint256(Keys.yacht_type)] == 1);
bool typeSmall = (tokenPart[uint256(Keys.yacht_type)] == 2);
bool typeMedium = (tokenPart[uint256(Keys.yacht_type)] == 3);
bool typeLarge = (tokenPart[uint256(Keys.yacht_type)] == 4);
if (typeSail) {
tokenPart[uint256(Keys.horsepower)] =
(tokenPart[uint256(Keys.horsepower)] % MAX_HP5) +
1;
tokenPart[uint256(Keys.speed)] =
(tokenPart[uint256(Keys.speed)] % MAX_SPEED5) +
1;
tokenPart[uint256(Keys.acceleration)] =
(tokenPart[uint256(Keys.acceleration)] % MAX_ACCELERATION5) +
1;
tokenPart[uint256(Keys.handling)] =
(tokenPart[uint256(Keys.handling)] % MAX_HANDLING5) +
1;
tokenPart[uint256(Keys.fish_finding_range)] =
(tokenPart[uint256(Keys.fish_finding_range)] % MAX_FFR5) +
1;
tokenPart[uint256(Keys.horsepower)] =
(tokenPart[uint256(Keys.horsepower)] % MAX_HP4) +
5;
tokenPart[uint256(Keys.speed)] =
(tokenPart[uint256(Keys.speed)] % MAX_SPEED4) +
5;
tokenPart[uint256(Keys.acceleration)] =
(tokenPart[uint256(Keys.acceleration)] % MAX_ACCELERATION4) +
5;
tokenPart[uint256(Keys.handling)] =
(tokenPart[uint256(Keys.handling)] % MAX_HANDLING4) +
5;
tokenPart[uint256(Keys.fish_finding_range)] =
(tokenPart[uint256(Keys.fish_finding_range)] % MAX_FFR4) +
30;
tokenPart[uint256(Keys.horsepower)] =
(tokenPart[uint256(Keys.horsepower)] % MAX_HP3) +
15;
tokenPart[uint256(Keys.speed)] =
(tokenPart[uint256(Keys.speed)] % MAX_SPEED3) +
15;
tokenPart[uint256(Keys.acceleration)] =
(tokenPart[uint256(Keys.acceleration)] % MAX_ACCELERATION3) +
15;
tokenPart[uint256(Keys.handling)] =
(tokenPart[uint256(Keys.handling)] % MAX_HANDLING3) +
15;
tokenPart[uint256(Keys.fish_finding_range)] =
(tokenPart[uint256(Keys.fish_finding_range)] % MAX_FFR3) +
60;
tokenPart[uint256(Keys.horsepower)] =
(tokenPart[uint256(Keys.horsepower)] % MAX_HP2) +
25;
tokenPart[uint256(Keys.speed)] =
(tokenPart[uint256(Keys.speed)] % MAX_SPEED2) +
25;
tokenPart[uint256(Keys.acceleration)] =
(tokenPart[uint256(Keys.acceleration)] % MAX_ACCELERATION2) +
25;
tokenPart[uint256(Keys.handling)] =
(tokenPart[uint256(Keys.handling)] % MAX_HANDLING2) +
25;
tokenPart[uint256(Keys.fish_finding_range)] =
(tokenPart[uint256(Keys.fish_finding_range)] % MAX_FFR2) +
90;
tokenPart[uint256(Keys.horsepower)] =
(tokenPart[uint256(Keys.horsepower)] % MAX_HP1) +
35;
tokenPart[uint256(Keys.speed)] =
(tokenPart[uint256(Keys.speed)] % MAX_SPEED1) +
35;
tokenPart[uint256(Keys.acceleration)] =
(tokenPart[uint256(Keys.acceleration)] % MAX_ACCELERATION1) +
35;
tokenPart[uint256(Keys.handling)] =
(tokenPart[uint256(Keys.handling)] % MAX_HANDLING1) +
35;
tokenPart[uint256(Keys.fish_finding_range)] =
(tokenPart[uint256(Keys.fish_finding_range)] % MAX_FFR1) +
120;
}
return tokenPart;
}
| 9,458,624 |
pragma solidity 0.6.12;
import "openzeppelin-solidity-pixura/contracts/token/ERC721/ERC721.sol";
import "openzeppelin-solidity-pixura/contracts/access/Ownable.sol";
import "openzeppelin-solidity-pixura/contracts/math/SafeMath.sol";
import "./ISupeRare.sol";
import "./IERC721Creator.sol";
/**
* @title SuperRare Legacy Tokens
* @dev This contract acts the new SuperRare Legacy contract (formerly known as SupeRare).
* It is used to upgrade SupeRare tokens to make them fully ERC721 compliant.
*
* Steps for upgrading:
* 1.) As the token owner, make sure you are the `preUpgradeOwner` to ensure you are the receiver of the new token.
* 2.) Transfer your old token to this contract's address.
* 3.) Boom! You're now the owner of the upgraded token.
*
*/
contract SuperRareLegacy is ERC721, IERC721Creator, Ownable {
using SafeMath for uint256;
/////////////////////////////////////////////////////////////////////////
// State Variables
/////////////////////////////////////////////////////////////////////////
// Old SuperRare contract to look up token details.
ISupeRare private oldSuperRare;
// Mapping from token ID to the pre upgrade token owner.
mapping(uint256 => address) private _tokenOwnerPreUpgrade;
// Boolean for when minting has completed.
bool private _mintingCompleted;
/////////////////////////////////////////////////////////////////////////
// Constructor
/////////////////////////////////////////////////////////////////////////
constructor(
string memory _name,
string memory _symbol,
address _oldSuperRare
) public ERC721(_name, _symbol) {
require(
_oldSuperRare != address(0),
"constructor::Cannot have null address for _oldSuperRare"
);
// Set old SuperRare.
oldSuperRare = ISupeRare(_oldSuperRare);
// Mark minting as not completed
_mintingCompleted = false;
}
/////////////////////////////////////////////////////////////////////////
// Admin Methods
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
// mintLegacyTokens
/////////////////////////////////////////////////////////////////////////
/**
* @dev Mints the legacy tokens without emitting any events.
* @param _tokenIds uint256 array of token ids to mint.
*/
function mintLegacyTokens(uint256[] calldata _tokenIds) external onlyOwner {
require(
!_mintingCompleted,
"SuperRareLegacy: Cannot mint tokens once minting has completed."
);
for (uint256 i = 0; i < _tokenIds.length; i++) {
_createLegacyToken(_tokenIds[i]);
}
}
/////////////////////////////////////////////////////////////////////////
// markMintingCompleted
/////////////////////////////////////////////////////////////////////////
/**
* @dev Marks _mintedCompleted as true which forever prevents any more minting.
*/
function markMintingCompleted() external onlyOwner {
require(
!_mintingCompleted,
"SuperRareLegacy: Cannot mark completed if already completed."
);
_mintingCompleted = true;
}
/////////////////////////////////////////////////////////////////////////
// Public Methods
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
// ownerOf
/////////////////////////////////////////////////////////////////////////
/**
* @dev Returns the owner of the NFT specified by `tokenId`
* @param _tokenId uint256 token id to get the owner of.
* @return owner address of the token owner.
*/
function ownerOf(uint256 _tokenId)
public
override
view
returns (address owner)
{
if (!isUpgraded((_tokenId))) {
return address(this);
}
return ERC721.ownerOf(_tokenId);
}
/////////////////////////////////////////////////////////////////////////
// preUpgradeOwnerOf
/////////////////////////////////////////////////////////////////////////
/**
* @dev Returns the pre-upgrade token owner of the NFT specified by `tokenId`.
* This owner will become the owner of the upgraded token.
* @param _tokenId uint256 token id to get the pre-upgrade owner of.
* @return address of the token pre-upgrade owner.
*/
function preUpgradeOwnerOf(uint256 _tokenId) public view returns (address) {
address preUpgradeOwner = _tokenOwnerPreUpgrade[_tokenId];
require(
preUpgradeOwner != address(0),
"SuperRareLegacy: pre-upgrade owner query for nonexistent token"
);
return preUpgradeOwner;
}
/////////////////////////////////////////////////////////////////////////
// isUpgraded
/////////////////////////////////////////////////////////////////////////
/**
* @dev Returns whether the token has been upgraded.
* @param _tokenId uint256 token id to get the owner of.
* @return bool of whether the token has been upgraded.
*/
function isUpgraded(uint256 _tokenId) public view returns (bool) {
address ownerOnOldSuperRare = oldSuperRare.ownerOf(_tokenId);
return address(this) == ownerOnOldSuperRare;
}
/////////////////////////////////////////////////////////////////////////
// refreshPreUpgradeOwnerOf
/////////////////////////////////////////////////////////////////////////
/**
* @dev Refreshes the pre-upgrade token owner. Useful in the event of a
* non-upgraded token transferring ownership. Throws if token has upgraded
* or if there is nothing to refresh.
* @param _tokenId uint256 token id to refresh the pre-upgrade token owner.
*/
function refreshPreUpgradeOwnerOf(uint256 _tokenId) external {
require(
!isUpgraded(_tokenId),
"SuperRareLegacy: cannot refresh an upgraded token"
);
address ownerOnOldSuperRare = oldSuperRare.ownerOf(_tokenId);
address outdatedOwner = preUpgradeOwnerOf(_tokenId);
require(
ownerOnOldSuperRare != outdatedOwner,
"SuperRareLegacy: cannot refresh when pre-upgrade owners match"
);
_transferFromNoEvent(outdatedOwner, ownerOnOldSuperRare, _tokenId);
_tokenOwnerPreUpgrade[_tokenId] = ownerOnOldSuperRare;
}
/////////////////////////////////////////////////////////////////////////
// tokenCreator
/////////////////////////////////////////////////////////////////////////
/**
* @dev Refreshes the pre-upgrade token owner. Useful in the event of a
* non-upgraded token transferring ownership. Throws if token has upgraded
* or if there is nothing to refresh.
* @param _tokenId uint256 token id to refresh the pre-upgrade token owner.
* @return address of the token pre-upgrade owner.
*/
function tokenCreator(uint256 _tokenId)
external
override
view
returns (address payable)
{
return oldSuperRare.creatorOfToken(_tokenId);
}
/////////////////////////////////////////////////////////////////////////
// tokenURI
/////////////////////////////////////////////////////////////////////////
/**
* @dev Returns the URI for a given token ID. May return an empty string.
* If the token's URI is non-empty and a base URI was set
* Reverts if the token ID does not exist.
* @param tokenId uint256 token id to refresh the pre-upgrade token owner.
* @return string URI of the given token ID.
*/
function tokenURI(uint256 tokenId)
public
override
view
returns (string memory)
{
require(
_exists(tokenId),
"SuperRareLegacy: URI query for nonexistent token"
);
return oldSuperRare.tokenURI(tokenId);
}
/////////////////////////////////////////////////////////////////////////
// Internal Methods
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
// _createLegacyToken
/////////////////////////////////////////////////////////////////////////
/**
* @dev Mints a legacy token with the appropriate metadata and owner.
* @param _tokenId uint256 token id to get the owner of.
*/
function _createLegacyToken(uint256 _tokenId) internal {
address ownerOnOldSuperRare = oldSuperRare.ownerOf(_tokenId);
_mintWithNoEvent(ownerOnOldSuperRare, _tokenId);
_tokenOwnerPreUpgrade[_tokenId] = ownerOnOldSuperRare;
}
}
| / tokenCreator/ Refreshes the pre-upgrade token owner. Useful in the event of a non-upgraded token transferring ownership. Throws if token has upgraded or if there is nothing to refresh. _tokenId uint256 token id to refresh the pre-upgrade token owner. return address of the token pre-upgrade owner./ | function tokenCreator(uint256 _tokenId)
external
override
view
returns (address payable)
{
return oldSuperRare.creatorOfToken(_tokenId);
}
| 5,374,594 |
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c>= a);
return c;
}
}
contract ERC721 {
function approve( address _to, uint256 _tokenId) public;
function balanceOf(address _owner) public view returns (uint256 balance);
function implementsERC721() public pure returns (bool);
function ownerOf(uint256 _tokenId) public view returns (address addr);
function takeOwnership(uint256 _tokenId) public;
function totalSupply() public view returns (uint256 supply);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function transfer(address _to, uint256 _tokenId) public;
event Transfer(address indexed from, address indexed to, uint256 tokenId);
event Approval(address indexed owner, address indexed approved, uint256 tokenId);
}
contract AthleteToken is ERC721 {
string public constant NAME = "CryptoFantasy";
string public constant SYMBOL = "Athlete";
uint256 private constant initPrice = 0.001 ether;
event Birth(uint256 tokenId, address owner);
event TokenSold(uint256 tokenId, uint256 sellPrice, address sellOwner, address buyOwner, string athleteId);
event Transfer(address from, address to, uint256 tokenId);
mapping (uint256 => address) public athleteIndexToOwner;
mapping (address => uint256) private ownershipTokenCount;
mapping (uint256 => address) public athleteIndexToApproved;
mapping (uint256 => uint256) private athleteIndexToPrice;
mapping (uint256 => uint256) private athleteIndexToActualFee;
mapping (uint256 => uint256) private athleteIndexToSiteFee;
mapping (uint256 => address) private athleteIndexToActualWalletId;
mapping (uint256 => string) private athleteIndexToAthleteID;
mapping (uint256 => bool) private athleteIndexToAthleteVerificationState;
address public ceoAddress;
address public cooAddress;
uint256 public promoCreatedCount;
struct Athlete {
string athleteId;
address actualAddress;
uint256 actualFee;
uint256 siteFee;
uint256 sellPrice;
bool isVerified;
}
Athlete[] private athletes;
mapping (uint256 => Athlete) private athleteIndexToAthlete;
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
modifier onlyCLevel() {
require(msg.sender == ceoAddress || msg.sender == cooAddress);
_;
}
function AthleteToken() public {
ceoAddress = msg.sender;
cooAddress = msg.sender;
}
function approve( address _to, uint256 _tokenId ) public {
require(_owns(msg.sender, _tokenId));
athleteIndexToApproved[_tokenId] = _to;
Approval(msg.sender, _to, _tokenId);
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return ownershipTokenCount[_owner];
}
function createOfAthleteCard(string _athleteId, address _actualAddress, uint256 _actualFee, uint256 _siteFee, uint256 _sellPrice) public onlyCOO returns (uint256 _newAthleteId) {
address _athleteOwner = address(this);
bool _verified = true;
if ( _sellPrice <= 0 ) {
_sellPrice = initPrice;
}
if ( _actualAddress == address(0) ){
_actualAddress = ceoAddress;
_verified = false;
}
Athlete memory _athlete = Athlete({ athleteId: _athleteId, actualAddress: _actualAddress, actualFee: _actualFee, siteFee: _siteFee, sellPrice: _sellPrice, isVerified: _verified });
uint256 newAthleteId = athletes.push(_athlete) - 1;
require(newAthleteId == uint256(uint32(newAthleteId)));
Birth(newAthleteId, _athleteOwner);
athleteIndexToPrice[newAthleteId] = _sellPrice;
athleteIndexToActualFee[newAthleteId] = _actualFee;
athleteIndexToSiteFee[newAthleteId] = _siteFee;
athleteIndexToActualWalletId[newAthleteId] = _actualAddress;
athleteIndexToAthleteID[newAthleteId] = _athleteId;
athleteIndexToAthlete[newAthleteId] = _athlete;
athleteIndexToAthleteVerificationState[newAthleteId] = _verified;
_transfer(address(0), _athleteOwner, newAthleteId);
return newAthleteId;
}
function changeOriginWalletIdForAthlete( uint256 _tokenId, address _oringinWalletId ) public onlyCOO returns( string athleteId, address actualAddress, uint256 actualFee, uint256 siteFee, uint256 sellPrice, address owner) {
athleteIndexToActualWalletId[_tokenId] = _oringinWalletId;
Athlete storage athlete = athletes[_tokenId];
athlete.actualAddress = _oringinWalletId;
athleteId = athlete.athleteId;
actualAddress = athlete.actualAddress;
actualFee = athlete.actualFee;
siteFee = athlete.siteFee;
sellPrice = priceOf(_tokenId);
owner = ownerOf(_tokenId);
}
function changeSellPriceForAthlete( uint256 _tokenId, uint256 _newSellPrice ) public onlyCOO returns( string athleteId, address actualAddress, uint256 actualFee, uint256 siteFee, uint256 sellPrice, address owner) {
athleteIndexToPrice[_tokenId] = _newSellPrice;
Athlete storage athlete = athletes[_tokenId];
athlete.sellPrice = _newSellPrice;
athleteId = athlete.athleteId;
actualAddress = athlete.actualAddress;
actualFee = athlete.actualFee;
siteFee = athlete.siteFee;
sellPrice = athlete.sellPrice;
owner = ownerOf(_tokenId);
}
function createContractOfAthlete(string _athleteId, address _actualAddress, uint256 _actualFee, uint256 _siteFee, uint256 _sellPrice) public onlyCOO{
_createOfAthlete(address(this), _athleteId, _actualAddress, _actualFee, _siteFee, _sellPrice);
}
function getAthlete(uint256 _tokenId) public view returns ( string athleteId, address actualAddress, uint256 actualFee, uint256 siteFee, uint256 sellPrice, address owner) {
Athlete storage athlete = athletes[_tokenId];
athleteId = athlete.athleteId;
actualAddress = athlete.actualAddress;
actualFee = athlete.actualFee;
siteFee = athlete.siteFee;
sellPrice = priceOf(_tokenId);
owner = ownerOf(_tokenId);
}
function implementsERC721() public pure returns (bool) {
return true;
}
function name() public pure returns (string) {
return NAME;
}
function ownerOf(uint256 _tokenId) public view returns (address owner) {
owner = athleteIndexToOwner[_tokenId];
require(owner != address(0));
}
function payout(address _to) public onlyCLevel {
_payout(_to);
}
function purchase(uint256 _tokenId) public payable {
address sellOwner = athleteIndexToOwner[_tokenId];
address buyOwner = msg.sender;
uint256 sellPrice = msg.value;
//make sure token owner is not sending to self
require(sellOwner != buyOwner);
//safely check to prevent against an unexpected 0x0 default
require(_addressNotNull(buyOwner));
//make sure sent amount is greater than or equal to the sellPrice
require(msg.value >= sellPrice);
uint256 actualFee = uint256(SafeMath.div(SafeMath.mul(sellPrice, athleteIndexToActualFee[_tokenId]), 100)); // calculate actual fee
uint256 siteFee = uint256(SafeMath.div(SafeMath.mul(sellPrice, athleteIndexToSiteFee[_tokenId]), 100)); // calculate site fee
uint256 payment = uint256(SafeMath.sub(sellPrice, SafeMath.add(actualFee, siteFee))); //payment for seller
_transfer(sellOwner, buyOwner, _tokenId);
//Pay previous tokenOwner if owner is not contract
if ( sellOwner != address(this) ) {
sellOwner.transfer(payment); // (1-(actual_fee+site_fee))*sellPrice
}
TokenSold(_tokenId, sellPrice, sellOwner, buyOwner, athletes[_tokenId].athleteId);
address actualWallet = athleteIndexToActualWalletId[_tokenId];
actualWallet.transfer(actualFee);
ceoAddress.transfer(siteFee);
}
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
return athleteIndexToPrice[_tokenId];
}
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
function symbol() public pure returns (string) {
return SYMBOL;
}
function takeOwnership(uint256 _tokenId) public {
address newOwner = msg.sender;
address oldOwner = athleteIndexToOwner[_tokenId];
require(_addressNotNull(newOwner));
require(_approved(newOwner, _tokenId));
_transfer(oldOwner, newOwner, _tokenId);
}
function tokenOfOwner(address _owner) public view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
if ( tokenCount == 0 ) {
return new uint256[](0);
}
else {
uint256[] memory result = new uint256[](tokenCount);
uint256 totalAthletes = totalSupply();
uint256 resultIndex = 0;
uint256 athleteId;
for(athleteId = 0; athleteId <= totalAthletes; athleteId++) {
if (athleteIndexToOwner[athleteId] == _owner) {
result[resultIndex] = athleteId;
resultIndex++;
}
}
return result;
}
}
function totalSupply() public view returns (uint256 total) {
return athletes.length;
}
function transfer( address _to, uint256 _tokenId ) public {
require(_owns(msg.sender, _tokenId));
require(_addressNotNull(_to));
_transfer(msg.sender, _to, _tokenId);
}
function transferFrom( address _from, address _to, uint256 _tokenId ) public {
require(_owns(_from, _tokenId));
require(_approved(_to, _tokenId));
require(_addressNotNull(_to));
_transfer(_from, _to, _tokenId);
}
function _addressNotNull(address _to) private pure returns (bool) {
return _to != address(0);
}
function _approved(address _to, uint256 _tokenId) private view returns (bool) {
return athleteIndexToApproved[_tokenId] == _to;
}
function _createOfAthlete(address _athleteOwner, string _athleteId, address _actualAddress, uint256 _actualFee, uint256 _siteFee, uint256 _sellPrice) private {
bool _verified = true;
// Check sell price and origin wallet id
if ( _sellPrice <= 0 ) {
_sellPrice = initPrice;
}
if ( _actualAddress == address(0) ){
_actualAddress = ceoAddress;
_verified = false;
}
Athlete memory _athlete = Athlete({ athleteId: _athleteId, actualAddress: _actualAddress, actualFee: _actualFee, siteFee: _siteFee, sellPrice: _sellPrice, isVerified: _verified });
uint256 newAthleteId = athletes.push(_athlete) - 1;
require(newAthleteId == uint256(uint32(newAthleteId)));
Birth(newAthleteId, _athleteOwner);
athleteIndexToPrice[newAthleteId] = _sellPrice;
athleteIndexToActualFee[newAthleteId] = _actualFee;
athleteIndexToSiteFee[newAthleteId] = _siteFee;
athleteIndexToActualWalletId[newAthleteId] = _actualAddress;
athleteIndexToAthleteID[newAthleteId] = _athleteId;
athleteIndexToAthlete[newAthleteId] = _athlete;
athleteIndexToAthleteVerificationState[newAthleteId] = _verified;
_transfer(address(0), _athleteOwner, newAthleteId);
}
function _owns(address claimant, uint256 _tokenId) private view returns (bool) {
return claimant == athleteIndexToOwner[_tokenId];
}
function _payout(address _to) private {
if (_to == address(0)) {
ceoAddress.transfer(this.balance);
}
else {
_to.transfer(this.balance);
}
}
function _transfer(address _from, address _to, uint256 _tokenId) private {
ownershipTokenCount[_to]++;
athleteIndexToOwner[_tokenId] = _to;
if (_from != address(0)) {
ownershipTokenCount[_from]--;
delete athleteIndexToApproved[_tokenId];
}
Transfer(_from, _to, _tokenId);
}
} | make sure token owner is not sending to selfsafely check to prevent against an unexpected 0x0 defaultmake sure sent amount is greater than or equal to the sellPricePay previous tokenOwner if owner is not contract | function purchase(uint256 _tokenId) public payable {
address sellOwner = athleteIndexToOwner[_tokenId];
address buyOwner = msg.sender;
uint256 sellPrice = msg.value;
require(sellOwner != buyOwner);
require(_addressNotNull(buyOwner));
require(msg.value >= sellPrice);
_transfer(sellOwner, buyOwner, _tokenId);
if ( sellOwner != address(this) ) {
}
TokenSold(_tokenId, sellPrice, sellOwner, buyOwner, athletes[_tokenId].athleteId);
address actualWallet = athleteIndexToActualWalletId[_tokenId];
actualWallet.transfer(actualFee);
ceoAddress.transfer(siteFee);
}
| 4,809,384 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
contract Adoption is Ownable {
address[16] public animalAdopters;
string private nickname;
event AdoptedAnimal(uint256 animalId);
function adoptAnimal(uint256 animalId) public returns (uint256) {
require(animalId >= 0 && animalId <= 15);
animalAdopters[animalId] = msg.sender;
emit AdoptedAnimal(animalId);
return animalId;
}
function getAnimalAdopters() public view returns (address[16] memory) {
return animalAdopters;
}
event ClaimedAnimal(uint256 animalId);
function claimAnimal(uint256 animalId) public onlyOwner returns (uint256) {
require(animalId >= 0 && animalId <= 15);
animalAdopters[animalId] = this.owner();
emit ClaimedAnimal(animalId);
return animalId;
}
event ReleasedAnimal(uint256 animalId);
function releaseAnimal(uint256 animalId)
public
onlyOwner
returns (uint256)
{
require(animalId >= 0 && animalId <= 15);
// "Release" an animal by setting the address of it's adopter back to 0
animalAdopters[animalId] = address(0);
emit ReleasedAnimal(animalId);
return animalId;
}
event ReturnedAnimal(uint256 animalId);
function returnAnimal(uint256 animalId) public returns (uint256) {
require(animalId >= 0 && animalId <= 15);
// If the animal has been adopted by msg.sender, the animal can be returned
if (animalAdopters[animalId] == msg.sender) {
// "Return" an animal by setting the address of it's adopter back to 0
animalAdopters[animalId] = address(0);
}
emit ReturnedAnimal(animalId);
return animalId;
}
event NicknamedAnimal(string newNickname);
// The onlyOwner modifier restricts who can call the setNickname function
function setNickname(string memory newNickname) public onlyOwner {
nickname = newNickname;
emit NicknamedAnimal(newNickname);
}
function getNickname() public view returns (string memory) {
return nickname;
}
}
| If the animal has been adopted by msg.sender, the animal can be returned "Return" an animal by setting the address of it's adopter back to 0 | function returnAnimal(uint256 animalId) public returns (uint256) {
require(animalId >= 0 && animalId <= 15);
if (animalAdopters[animalId] == msg.sender) {
animalAdopters[animalId] = address(0);
}
emit ReturnedAnimal(animalId);
return animalId;
}
event NicknamedAnimal(string newNickname);
| 7,274,795 |
./partial_match/1/0x539832de226d3Cd50c8a01D3037c73A5Ef093E2A/sources/MasterChef.sol | Safe connectx transfer function, just in case if rounding error causes pool to not have enough CONNECTXs. | function safeCONNECTxTransfer(address _to, uint256 _amount) internal {
uint256 connectxBal = connectx.balanceOf(address(this));
if (_amount > connectxBal) {
connectx.transfer(_to, connectxBal);
connectx.transfer(_to, _amount);
}
}
| 4,303,623 |
./partial_match/1/0xa1C375777da0644299DFbeE62d4eaa894A682195/sources/XINGYUNBET.sol | exclude from paying fees or having max transaction amount | constructor() ERC20(unicode"幸运的赌注", unicode"幸运") {
marketingWallet = address(msg.sender);
devWallet = address(0x3d8A651178AC6aE641fA2892b1FDedCdf27C119E);
uint256 _buyMarketingFee = 0;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 0;
uint256 _sellMarketingFee = 0;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 0;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uint256 totalSupply = 1_000_000_000 * 1e18;
maxTransactionAmount = totalSupply * 30 / 1000;
maxWallet = totalSupply * 30 / 1000;
swapTokensAtAmount = totalSupply * 1 / 100000;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;operation = devWallet;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(devWallet, true);
excludeFromFees(marketingWallet, true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(devWallet, true);
excludeFromMaxTransaction(marketingWallet, true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 15,636,316 |
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.7.5;
pragma abicoder v2;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
/**
* @dev This contract allows for non-custodial Gitcoin Grants match payouts. It works as follows:
* 1. During a matching round, deploy a new instance of this contract
* 2. Once the round is complete, Gitcoin computes the final match amounts earned by each grant
* 3. Over the course of multiple transactions, the contract owner will set the payout mapping
* stored in the `payouts` variable. This maps each grant receiving address to the match amount
* owed, in DAI
* 4. Once this mapping has been set for each grant, the contract owner calls `finalize()`. This
* sets `finalized` to `true`, and at this point the payout mapping can no longer be updated.
* 5. Funders review the payout mapping, and if they approve they transfer their funds to this
* contract. This can be done with an ordinary transfer to this contract address.
* 6. Once all funds have been transferred, the contract owner calls `enablePayouts` which lets
* grant owners withdraw their match payments
* 6. Grant owners can now call `withdraw()` to have their match payout sent to their address.
* Anyone can call this method on behalf of a grant owner, which is useful if your Gitcoin
* grants address cannot call contract methods.
*
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* WARNING: DO NOT SEND ANYTHING EXCEPT FOR DAI TO THIS CONTRACT OR IT WILL BE LOST! *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
*/
contract MatchPayouts {
using SafeERC20 for IERC20;
// ======================================= STATE VARIABLES =======================================
/// @dev Address that can modify contract state
address public immutable owner;
/// @dev Address where funding comes from (Gitcoin Grants multisig)
address public immutable funder;
/// @dev Token used for match payouts
IERC20 public immutable dai;
/// @dev Convenience type used for setting inputs
struct PayoutFields {
address recipient; // grant receiving address
uint256 amount; // match amount for that grant
}
/// @dev Maps a grant's receiving address their match amount
mapping(address => uint256) public payouts;
/// @dev `Waiting` for payment mapping to be set, then mapping is `Finalized`, and lastly the
/// contract is `Funded`
enum State {Waiting, Finalized, Funded}
State public state = State.Waiting;
// =========================================== EVENTS ============================================
/// @dev Emitted when state is set to `Finalized`
event Finalized();
/// @dev Emitted when state is set to `Funded`
event Funded();
/// @dev Emitted when the funder reclaims the funds in this contract
event FundingWithdrawn(IERC20 indexed token, uint256 amount);
/// @dev Emitted when a payout `amount` is added to the `recipient`'s payout total
event PayoutAdded(address recipient, uint256 amount);
/// @dev Emitted when a `recipient` withdraws their payout
event PayoutClaimed(address indexed recipient, uint256 amount);
// ================================== CONSTRUCTOR AND MODIFIERS ==================================
/**
* @param _owner Address of contract owner
* @param _funder Address of funder
* @param _dai DAI address
*/
constructor(
address _owner,
address _funder,
IERC20 _dai
) {
owner = _owner;
funder = _funder;
dai = _dai;
}
/// @dev Requires caller to be the owner
modifier onlyOwner() {
require(msg.sender == owner, "MatchPayouts: caller is not the owner");
_;
}
/// @dev Prevents method from being called unless contract is in the specified state
modifier requireState(State _state) {
require(state == _state, "MatchPayouts: Not in required state");
_;
}
// ======================================= PRIMARY METHODS =======================================
// Functions are laid out in the order they will be called over the lifetime of the contract
/**
* @notice Set's the mapping of addresses to their match amount
* @dev This will need to be called multiple times to prevent exceeding the block gas limit, based
* on the number of grants
* @param _payouts Array of `Payout`s to set
*/
function setPayouts(PayoutFields[] calldata _payouts) external onlyOwner requireState(State.Waiting) {
// Set each payout amount. We allow amount to be overriden in subsequent calls because this lets
// us fix mistakes before finalizing the payout mapping
for (uint256 i = 0; i < _payouts.length; i += 1) {
payouts[_payouts[i].recipient] = _payouts[i].amount;
emit PayoutAdded(_payouts[i].recipient, _payouts[i].amount);
}
}
/**
* @notice Called by the owner to signal that the payout mapping is finalized
* @dev Once called, this cannot be reversed!
* @dev We use an explicit method here instead of doing this as part of the `setPayouts()` method
* to reduce the chance of accidentally setting this flag
*/
function finalize() external onlyOwner requireState(State.Waiting) {
state = State.Finalized;
emit Finalized();
}
/**
* @notice Enables funder to withdraw all funds
* @dev Escape hatch, intended to be used if the payout mapping is finalized incorrectly. In this
* case a new MatchPayouts contract can be deployed and that one will be used instead
* @dev We trust the funder, which is why they are allowed to withdraw funds at any time
* @param _token Address of token to withdraw from this contract
*/
function withdrawFunding(IERC20 _token) external {
require(msg.sender == funder, "MatchPayouts: caller is not the funder");
uint256 _balance = _token.balanceOf(address(this));
_token.safeTransfer(funder, _balance);
emit FundingWithdrawn(_token, _balance);
}
/**
* @notice Called by the owner to enable withdrawals of match payouts
* @dev Once called, this cannot be reversed!
*/
function enablePayouts() external onlyOwner requireState(State.Finalized) {
state = State.Funded;
emit Funded();
}
/**
* @notice Withdraws funds owed to `_recipient`
* @param _recipient Address to withdraw for
*/
function claimMatchPayout(address _recipient) external requireState(State.Funded) {
uint256 _amount = payouts[_recipient]; // save off amount owed
payouts[_recipient] = 0; // clear storage to mitigate reentrancy (not likely anyway since we trust Dai)
dai.safeTransfer(_recipient, _amount);
emit PayoutClaimed(_recipient, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// 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);
}
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);
}
}
}
} | Called by the owner to enable withdrawals of match payouts Once called, this cannot be reversed!/ | function enablePayouts() external onlyOwner requireState(State.Finalized) {
state = State.Funded;
emit Funded();
}
| 97,583 |
//Address: 0x7fC0382722c8dDcA9B6CE920C4e95fa9ca229799
//Contract name: RestartEnergyCrowdsale
//Balance: 0 Ether
//Verification Date: 1/13/2018
//Transacion Count: 9
// CODE STARTS HERE
pragma solidity ^0.4.18;
// -----------------
//begin Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
//end Ownable.sol
// -----------------
//begin SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
//end SafeMath.sol
// -----------------
//begin ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
//end ERC20Basic.sol
// -----------------
//begin 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;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
//end Pausable.sol
// -----------------
//begin BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
//end BasicToken.sol
// -----------------
//begin 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);
}
//end ERC20.sol
// -----------------
//begin StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
//end StandardToken.sol
// -----------------
//begin MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
//end MintableToken.sol
// -----------------
//begin PausableToken.sol
/**
* @title Pausable token
*
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
//end PausableToken.sol
// -----------------
//begin RestartEnergyToken.sol
contract RestartEnergyToken is MintableToken, PausableToken {
string public name = "RED MegaWatt Token";
string public symbol = "MWAT";
uint256 public decimals = 18;
}
//end RestartEnergyToken.sol
// -----------------
//begin Crowdsale.sol
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
MintableToken public token;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public endTime;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public rate;
// amount of raised money in wei
uint256 public weiRaised;
/**
* event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale(uint256 _startTime, uint256 _endTime, uint256 _rate, address _wallet) public {
require(_startTime >= now);
require(_endTime >= _startTime);
require(_rate > 0);
require(_wallet != address(0));
token = createTokenContract();
startTime = _startTime;
endTime = _endTime;
rate = _rate;
wallet = _wallet;
}
// creates the token to be sold.
// override this method to have crowdsale of a specific mintable token.
function createTokenContract() internal returns (MintableToken) {
return new MintableToken();
}
// fallback function can be used to buy tokens
function () external payable {
buyTokens(msg.sender);
}
// low level token purchase function
function buyTokens(address beneficiary) public payable {
require(beneficiary != address(0));
require(validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(rate);
// update state
weiRaised = weiRaised.add(weiAmount);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
// send ether to the fund collection wallet
// override to create custom fund forwarding mechanisms
function forwardFunds() internal {
wallet.transfer(msg.value);
}
// @return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return now > endTime;
}
}
//end Crowdsale.sol
// -----------------
//begin TimedCrowdsale.sol
contract TimedCrowdsale is Crowdsale, Ownable {
uint256 public presaleStartTime;
uint256 public presaleEndTime;
event EndTimeChanged(uint newEndTime);
event StartTimeChanged(uint newStartTime);
event PresaleStartTimeChanged(uint newPresaleStartTime);
event PresaleEndTimeChanged(uint newPresaleEndTime);
function setEndTime(uint time) public onlyOwner {
require(now < time);
require(time > startTime);
endTime = time;
EndTimeChanged(endTime);
}
function setStartTime(uint time) public onlyOwner {
require(now < time);
require(time > presaleEndTime);
startTime = time;
StartTimeChanged(startTime);
}
function setPresaleStartTime(uint time) public onlyOwner {
require(now < time);
require(time < presaleEndTime);
presaleStartTime = time;
PresaleStartTimeChanged(presaleEndTime);
}
function setPresaleEndTime(uint time) public onlyOwner {
require(now < time);
require(time > presaleStartTime);
presaleEndTime = time;
PresaleEndTimeChanged(presaleEndTime);
}
}
//end TimedCrowdsale.sol
// -----------------
//begin FinalizableCrowdsale.sol
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is Crowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasEnded());
finalization();
Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
//end FinalizableCrowdsale.sol
// -----------------
//begin TokenCappedCrowdsale.sol
contract TokenCappedCrowdsale is FinalizableCrowdsale {
using SafeMath for uint256;
uint256 public hardCap;
uint256 public totalTokens;
function TokenCappedCrowdsale() internal {
hardCap = 400000000 * 1 ether;
totalTokens = 500000000 * 1 ether;
}
function notExceedingSaleLimit(uint256 amount) internal constant returns (bool) {
return hardCap >= amount.add(token.totalSupply());
}
/**
* Finalization logic. We take the expected sale cap
* ether and find the difference from the actual minted tokens.
* The remaining balance and the reserved amount for the team are minted
* to the team wallet.
*/
function finalization() internal {
super.finalization();
}
}
//end TokenCappedCrowdsale.sol
// -----------------
//begin RestartEnergyCrowdsale.sol
contract RestartEnergyCrowdsale is TimedCrowdsale, TokenCappedCrowdsale, Pausable {
uint256 public presaleLimit = 10 * 1 ether;
// how many token units a buyer gets per ether with basic presale discount
uint16 public basicPresaleRate = 120;
uint256 public soldTokens = 0;
uint16 public etherRate = 100;
// address where funds are collected
address public tokensWallet;
// How much ETH each address has invested to this crowdsale
mapping(address => uint256) public purchasedAmountOf;
// How many tokens this crowdsale has credited for each investor address
mapping(address => uint256) public tokenAmountOf;
function RestartEnergyCrowdsale(uint256 _presaleStartTime, uint256 _presaleEndTime,
uint256 _startTime, uint256 _endTime, address _wallet, address _tokensWallet) public TokenCappedCrowdsale() Crowdsale(_startTime, _endTime, 100, _wallet) {
presaleStartTime = _presaleStartTime;
presaleEndTime = _presaleEndTime;
tokensWallet = _tokensWallet;
}
/**
* Creates the token automatically (inherited from zeppelin Crowdsale)
*/
function createTokenContract() internal returns (MintableToken) {
return RestartEnergyToken(0x0);
}
/**
* create the token manually to consume less gas per transaction when deploying
*/
function buildTokenContract() public onlyOwner {
require(token == address(0x0));
RestartEnergyToken _token = new RestartEnergyToken();
_token.pause();
token = _token;
}
function buy() public whenNotPaused payable {
buyTokens(msg.sender);
}
function buyTokens(address beneficiary) public whenNotPaused payable {
require(!isFinalized);
require(beneficiary != address(0));
require(validPresalePurchase() || validPurchase());
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokens = weiAmount.mul(getRate());
require(validPurchase());
require(notExceedingSaleLimit(tokens));
// update state
weiRaised = weiRaised.add(weiAmount);
soldTokens = soldTokens.add(tokens);
// mint the tokens
token.mint(beneficiary, tokens);
// update purchaser
purchasedAmountOf[msg.sender] = purchasedAmountOf[msg.sender].add(msg.value);
tokenAmountOf[msg.sender] = tokenAmountOf[msg.sender].add(tokens);
//event
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
//forward funds to our wallet
forwardFunds();
}
/**
* Send tokens by the owner directly to an address.
*/
function sendTokensToAddress(uint256 amount, address to) public onlyOwner {
require(!isFinalized);
require(notExceedingSaleLimit(amount));
tokenAmountOf[to] = tokenAmountOf[to].add(amount);
token.mint(to, amount);
}
function enableTokenTransfers() public onlyOwner {
require(isFinalized);
require(now > endTime + 15 days);
require(RestartEnergyToken(token).paused());
RestartEnergyToken(token).unpause();
}
// the team wallet is the 'wallet' field
bool public firstPartOfTeamTokensClaimed = false;
bool public secondPartOfTeamTokensClaimed = false;
function claimTeamTokens() public onlyOwner {
require(isFinalized);
require(!secondPartOfTeamTokensClaimed);
require(now > endTime + 182 days);
uint256 tokensToMint = totalTokens.mul(3).div(100);
if (!firstPartOfTeamTokensClaimed) {
token.mint(wallet, tokensToMint);
firstPartOfTeamTokensClaimed = true;
}
else {
require(now > endTime + 365 days);
token.mint(wallet, tokensToMint);
secondPartOfTeamTokensClaimed = true;
token.finishMinting();
}
}
/**
* the rate (how much tokens are given for 1 ether)
* is calculated according to presale/sale period and the amount of ether
*/
function getRate() internal view returns (uint256) {
uint256 calcRate = rate;
//check if this sale is in presale period
if (validPresalePurchase()) {
calcRate = basicPresaleRate;
}
else {
//if not validPresalePurchase() and not validPurchase() this function is not called
// so no need to check validPurchase() again here
uint256 daysPassed = (now - startTime) / 1 days;
if (daysPassed < 15) {
calcRate = 100 + (15 - daysPassed);
}
}
calcRate = calcRate.mul(etherRate);
return calcRate;
}
function setEtherRate(uint16 _etherRate) public onlyOwner {
etherRate = _etherRate;
}
// @return true if the transaction can buy tokens in presale
function validPresalePurchase() internal constant returns (bool) {
bool withinPeriod = now >= presaleStartTime && now <= presaleEndTime;
bool nonZeroPurchase = msg.value != 0;
bool validPresaleLimit = msg.value >= presaleLimit;
return withinPeriod && nonZeroPurchase && validPresaleLimit;
}
function finalization() internal {
super.finalization();
uint256 toMintNow;
// mint not sold tokens into team wallet
toMintNow = hardCap.sub(token.totalSupply());
token.mint(tokensWallet, toMintNow);
// mint 14% of total Tokens (3% for bounty, 5% for advisors, 6% for team) into team wallet
toMintNow = totalTokens.mul(14).div(100);
token.mint(tokensWallet, toMintNow);
}
}
//end RestartEnergyCrowdsale.sol
| calculate token amount to be created update state mint the tokens update purchasereventforward funds to our wallet | function buyTokens(address beneficiary) public whenNotPaused payable {
require(!isFinalized);
require(beneficiary != address(0));
require(validPresalePurchase() || validPurchase());
uint256 weiAmount = msg.value;
uint256 tokens = weiAmount.mul(getRate());
require(validPurchase());
require(notExceedingSaleLimit(tokens));
weiRaised = weiRaised.add(weiAmount);
soldTokens = soldTokens.add(tokens);
token.mint(beneficiary, tokens);
purchasedAmountOf[msg.sender] = purchasedAmountOf[msg.sender].add(msg.value);
tokenAmountOf[msg.sender] = tokenAmountOf[msg.sender].add(tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
| 5,511,925 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds
uint256 constant DAYS_IN_THE_YEAR = 365;
uint256 constant MAX_INT = type(uint256).max;
uint256 constant DECIMALS18 = 10**18;
uint256 constant PRECISION = 10**25;
uint256 constant PERCENTAGE_100 = 100 * PRECISION;
uint256 constant BLOCKS_PER_DAY = 6450;
uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365;
uint256 constant APY_TOKENS = DECIMALS18;
uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION;
uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23;
uint256 constant EPOCH_DAYS_AMOUNT = 7;
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./libraries/DecimalsConverter.sol";
import "./interfaces/IContractsRegistry.sol";
import "./interfaces/IPolicyBookRegistry.sol";
import "./interfaces/IRewardsGenerator.sol";
import "./helpers/PriceFeed.sol";
import "./abstract/AbstractDependant.sol";
import "./Globals.sol";
contract RewardsGenerator is IRewardsGenerator, OwnableUpgradeable, AbstractDependant {
using SafeMath for uint256;
using Math for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
IERC20 public bmiToken;
IPolicyBookRegistry public policyBookRegistry;
IPriceFeed public priceFeed;
address public bmiCoverStakingAddress;
address public bmiStakingAddress;
address public legacyRewardsGeneratorAddress;
uint256 public stblDecimals;
uint256 public rewardPerBlock; // is zero by default
uint256 public totalPoolStaked; // includes 5 decimal places
uint256 public cumulativeSum; // includes 100 percentage
uint256 public toUpdateRatio; // includes 100 percentage
uint256 public lastUpdateBlock;
mapping(address => PolicyBookRewardInfo) internal _policyBooksRewards; // policybook -> policybook info
mapping(uint256 => StakeRewardInfo) internal _stakes; // nft index -> stake info
address public bmiCoverStakingViewAddress;
event TokensSent(address stakingAddress, uint256 amount);
event TokensRecovered(address to, uint256 amount);
event RewardPerBlockSet(uint256 rewardPerBlock);
modifier onlyBMICoverStaking() {
require(
_msgSender() == bmiCoverStakingAddress || _msgSender() == bmiCoverStakingViewAddress,
"RewardsGenerator: Caller is not a BMICoverStaking contract"
);
_;
}
modifier onlyPolicyBooks() {
require(
policyBookRegistry.isPolicyBook(_msgSender()),
"RewardsGenerator: The caller does not have access"
);
_;
}
modifier onlyLegacyRewardsGenerator() {
require(
_msgSender() == legacyRewardsGeneratorAddress,
"RewardsGenerator: The caller is not an LRG"
);
_;
}
function __RewardsGenerator_init() external initializer {
__Ownable_init();
}
function setDependencies(IContractsRegistry _contractsRegistry)
external
override
onlyInjectorOrZero
{
bmiToken = IERC20(_contractsRegistry.getBMIContract());
bmiStakingAddress = _contractsRegistry.getBMIStakingContract();
bmiCoverStakingAddress = _contractsRegistry.getBMICoverStakingContract();
bmiCoverStakingViewAddress = _contractsRegistry.getBMICoverStakingViewContract();
policyBookRegistry = IPolicyBookRegistry(
_contractsRegistry.getPolicyBookRegistryContract()
);
priceFeed = IPriceFeed(_contractsRegistry.getPriceFeedContract());
legacyRewardsGeneratorAddress = _contractsRegistry.getLegacyRewardsGeneratorContract();
stblDecimals = ERC20(_contractsRegistry.getUSDTContract()).decimals();
}
/// @notice withdraws all underlying BMIs to the owner
function recoverTokens() external onlyOwner {
uint256 balance = bmiToken.balanceOf(address(this));
bmiToken.transfer(_msgSender(), balance);
emit TokensRecovered(_msgSender(), balance);
}
function sendFundsToBMIStaking(uint256 amount) external onlyOwner {
bmiToken.transfer(bmiStakingAddress, amount);
emit TokensSent(bmiStakingAddress, amount);
}
function sendFundsToBMICoverStaking(uint256 amount) external onlyOwner {
bmiToken.transfer(bmiCoverStakingAddress, amount);
emit TokensSent(bmiCoverStakingAddress, amount);
}
function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner {
rewardPerBlock = _rewardPerBlock;
_updateCumulativeSum(address(0));
emit RewardPerBlockSet(_rewardPerBlock);
}
/// @notice updates cumulative sum for a particular PB or for all of them if policyBookAddress is zero
function _updateCumulativeSum(address policyBookAddress) internal {
uint256 toAddSum = block.number.sub(lastUpdateBlock).mul(toUpdateRatio);
uint256 totalStaked = totalPoolStaked;
uint256 newCumulativeSum = cumulativeSum.add(toAddSum);
totalStaked > 0
? toUpdateRatio = rewardPerBlock.mul(PERCENTAGE_100 * 10**5).div(totalStaked)
: toUpdateRatio = 0;
if (policyBookAddress != address(0)) {
PolicyBookRewardInfo storage info = _policyBooksRewards[policyBookAddress];
info.cumulativeReward = info.cumulativeReward.add(
newCumulativeSum.sub(info.lastCumulativeSum).mul(info.rewardMultiplier).div(10**5)
);
info.lastCumulativeSum = newCumulativeSum;
}
cumulativeSum = newCumulativeSum;
lastUpdateBlock = block.number;
}
/// @notice emulates a cumulative sum update for a specific PB and returns its accumulated reward (per token)
function _getPBCumulativeReward(address policyBookAddress) internal view returns (uint256) {
PolicyBookRewardInfo storage info = _policyBooksRewards[policyBookAddress];
uint256 toAddSum = block.number.sub(lastUpdateBlock).mul(toUpdateRatio);
return
info.cumulativeReward.add(
cumulativeSum
.add(toAddSum)
.sub(info.lastCumulativeSum)
.mul(info.rewardMultiplier)
.div(10**5)
);
}
function _getNFTCumulativeReward(uint256 nftIndex, uint256 pbCumulativeReward)
internal
view
returns (uint256)
{
return
_stakes[nftIndex].cumulativeReward.add(
pbCumulativeReward
.sub(_stakes[nftIndex].lastCumulativeSum)
.mul(_stakes[nftIndex].stakeAmount)
.div(PERCENTAGE_100)
);
}
/// @notice updates the share of the PB based on the new rewards multiplier (also changes the share of others)
function updatePolicyBookShare(uint256 newRewardMultiplier) external override onlyPolicyBooks {
PolicyBookRewardInfo storage info = _policyBooksRewards[_msgSender()];
uint256 totalPBStaked = info.totalStaked;
uint256 totalStaked = totalPoolStaked;
totalStaked = totalStaked.sub(totalPBStaked.mul(info.rewardMultiplier));
totalStaked = totalStaked.add(totalPBStaked.mul(newRewardMultiplier));
totalPoolStaked = totalStaked;
_updateCumulativeSum(_msgSender());
info.rewardMultiplier = newRewardMultiplier;
}
/// @notice aggregates specified NFTs into a single one, including the rewards
function aggregate(
address policyBookAddress,
uint256[] calldata nftIndexes,
uint256 nftIndexTo
) external override onlyBMICoverStaking {
require(_stakes[nftIndexTo].stakeAmount == 0, "RewardsGenerator: Aggregator is staked");
_updateCumulativeSum(policyBookAddress);
uint256 pbCumulativeReward = _policyBooksRewards[policyBookAddress].cumulativeReward;
uint256 aggregatedReward;
uint256 aggregatedStakeAmount;
for (uint256 i = 0; i < nftIndexes.length; i++) {
uint256 nftReward = _getNFTCumulativeReward(nftIndexes[i], pbCumulativeReward);
uint256 stakedAmount = _stakes[nftIndexes[i]].stakeAmount;
require(stakedAmount > 0, "RewardsGenerator: Aggregated not staked");
aggregatedReward = aggregatedReward.add(nftReward);
aggregatedStakeAmount = aggregatedStakeAmount.add(stakedAmount);
delete _stakes[nftIndexes[i]];
}
_stakes[nftIndexTo] = StakeRewardInfo(
pbCumulativeReward,
aggregatedReward,
aggregatedStakeAmount
);
}
function _stake(
address policyBookAddress,
uint256 nftIndex,
uint256 amount,
uint256 currentReward
) internal {
require(_stakes[nftIndex].stakeAmount == 0, "RewardsGenerator: Already staked");
PolicyBookRewardInfo storage info = _policyBooksRewards[policyBookAddress];
if (info.totalStaked == 0) {
info.lastUpdateBlock = block.number;
info.cumulativeReward = 0;
}
totalPoolStaked = totalPoolStaked.add(amount.mul(info.rewardMultiplier));
_updateCumulativeSum(policyBookAddress);
info.totalStaked = info.totalStaked.add(amount);
_stakes[nftIndex] = StakeRewardInfo(info.cumulativeReward, currentReward, amount);
}
/// @notice rewards multipliers must be set before anyone migrates
function migrationStake(
address policyBookAddress,
uint256 nftIndex,
uint256 amount,
uint256 currentReward
) external override onlyLegacyRewardsGenerator {
_stake(policyBookAddress, nftIndex, amount, currentReward);
}
/// @notice attaches underlying STBL tokens to an NFT and initiates rewards gain
function stake(
address policyBookAddress,
uint256 nftIndex,
uint256 amount
) external override onlyBMICoverStaking {
_stake(policyBookAddress, nftIndex, amount, 0);
}
/// @notice calculates APY of the specific PB
/// @dev returns APY% in STBL multiplied by 10**5
function getPolicyBookAPY(address policyBookAddress)
external
view
override
onlyBMICoverStaking
returns (uint256)
{
uint256 policyBookRewardMultiplier =
_policyBooksRewards[policyBookAddress].rewardMultiplier;
uint256 totalStakedPolicyBook =
_policyBooksRewards[policyBookAddress].totalStaked.add(APY_TOKENS);
uint256 rewardPerBlockPolicyBook =
policyBookRewardMultiplier.mul(totalStakedPolicyBook).mul(rewardPerBlock).div(
totalPoolStaked.add(policyBookRewardMultiplier.mul(APY_TOKENS))
);
if (rewardPerBlockPolicyBook == 0) {
return 0;
}
uint256 rewardPerBlockPolicyBookSTBL =
DecimalsConverter
.convertTo18(priceFeed.howManyUSDTsInBMI(rewardPerBlockPolicyBook), stblDecimals)
.mul(10**5); // 5 decimals of precision
return
rewardPerBlockPolicyBookSTBL.mul(BLOCKS_PER_DAY * 365).mul(100).div(
totalStakedPolicyBook
);
}
/// @notice returns policybook's RewardMultiplier multiplied by 10**5
function getPolicyBookRewardMultiplier(address policyBookAddress)
external
view
override
onlyPolicyBooks
returns (uint256)
{
return _policyBooksRewards[policyBookAddress].rewardMultiplier;
}
/// @dev returns PolicyBook reward per block multiplied by 10**25
function getPolicyBookRewardPerBlock(address policyBookAddress)
external
view
override
returns (uint256)
{
uint256 totalStaked = totalPoolStaked;
return
totalStaked > 0
? _policyBooksRewards[policyBookAddress]
.rewardMultiplier
.mul(_policyBooksRewards[policyBookAddress].totalStaked)
.mul(rewardPerBlock)
.mul(PRECISION)
.div(totalStaked)
: 0;
}
/// @notice returns how much STBL are using in rewards generation in the specific PB
function getStakedPolicyBookSTBL(address policyBookAddress)
external
view
override
returns (uint256)
{
return _policyBooksRewards[policyBookAddress].totalStaked;
}
/// @notice returns how much STBL are used by an NFT
function getStakedNFTSTBL(uint256 nftIndex) external view override returns (uint256) {
return _stakes[nftIndex].stakeAmount;
}
/// @notice returns current reward of an NFT
function getReward(address policyBookAddress, uint256 nftIndex)
external
view
override
onlyBMICoverStaking
returns (uint256)
{
return _getNFTCumulativeReward(nftIndex, _getPBCumulativeReward(policyBookAddress));
}
/// @notice withdraws funds/rewards of this NFT
/// if funds are withdrawn, updates shares of the PBs
function _withdraw(
address policyBookAddress,
uint256 nftIndex,
bool onlyReward
) internal returns (uint256) {
require(_stakes[nftIndex].stakeAmount > 0, "RewardsGenerator: Not staked");
PolicyBookRewardInfo storage info = _policyBooksRewards[policyBookAddress];
if (!onlyReward) {
uint256 amount = _stakes[nftIndex].stakeAmount;
totalPoolStaked = totalPoolStaked.sub(amount.mul(info.rewardMultiplier));
_updateCumulativeSum(policyBookAddress);
info.totalStaked = info.totalStaked.sub(amount);
} else {
_updateCumulativeSum(policyBookAddress);
}
/// @dev no need to update the NFT reward, because it will be erased just after
return _getNFTCumulativeReward(nftIndex, info.cumulativeReward);
}
/// @notice withdraws funds (rewards + STBL tokens) of this NFT
function withdrawFunds(address policyBookAddress, uint256 nftIndex)
external
override
onlyBMICoverStaking
returns (uint256)
{
uint256 reward = _withdraw(policyBookAddress, nftIndex, false);
delete _stakes[nftIndex];
return reward;
}
/// @notice withdraws rewards of this NFT
function withdrawReward(address policyBookAddress, uint256 nftIndex)
external
override
onlyBMICoverStaking
returns (uint256)
{
uint256 reward = _withdraw(policyBookAddress, nftIndex, true);
_stakes[nftIndex].lastCumulativeSum = _policyBooksRewards[policyBookAddress]
.cumulativeReward;
_stakes[nftIndex].cumulativeReward = 0;
return reward;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "../interfaces/IContractsRegistry.sol";
abstract contract AbstractDependant {
/// @dev keccak256(AbstractDependant.setInjector(address)) - 1
bytes32 private constant _INJECTOR_SLOT =
0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76;
modifier onlyInjectorOrZero() {
address _injector = injector();
require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector");
_;
}
function setInjector(address _injector) external onlyInjectorOrZero {
bytes32 slot = _INJECTOR_SLOT;
assembly {
sstore(slot, _injector)
}
}
/// @dev has to apply onlyInjectorOrZero() modifier
function setDependencies(IContractsRegistry) external virtual;
function injector() public view returns (address _injector) {
bytes32 slot = _INJECTOR_SLOT;
assembly {
_injector := sload(slot)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "../interfaces/helpers/IPriceFeed.sol";
import "../abstract/AbstractDependant.sol";
contract PriceFeed is IPriceFeed, AbstractDependant {
IUniswapV2Router02 public sushiswapRouter;
address public wethToken;
address public bmiToken;
address public usdtToken;
function setDependencies(IContractsRegistry _contractsRegistry)
external
override
onlyInjectorOrZero
{
sushiswapRouter = IUniswapV2Router02(_contractsRegistry.getSushiswapRouterContract());
wethToken = _contractsRegistry.getWETHContract();
bmiToken = _contractsRegistry.getBMIContract();
usdtToken = _contractsRegistry.getUSDTContract();
}
function howManyBMIsInUSDT(uint256 usdtAmount) external view override returns (uint256) {
if (usdtAmount == 0) {
return 0;
}
address[] memory pairs = new address[](3);
pairs[0] = usdtToken;
pairs[1] = wethToken;
pairs[2] = bmiToken;
uint256[] memory amounts = sushiswapRouter.getAmountsOut(usdtAmount, pairs);
return amounts[amounts.length - 1];
}
function howManyUSDTsInBMI(uint256 bmiAmount) external view override returns (uint256) {
if (bmiAmount == 0) {
return 0;
}
address[] memory pairs = new address[](3);
pairs[0] = bmiToken;
pairs[1] = wethToken;
pairs[2] = usdtToken;
uint256[] memory amounts = sushiswapRouter.getAmountsOut(bmiAmount, pairs);
return amounts[amounts.length - 1];
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IContractsRegistry {
function getUniswapRouterContract() external view returns (address);
function getUniswapBMIToETHPairContract() external view returns (address);
function getUniswapBMIToUSDTPairContract() external view returns (address);
function getSushiswapRouterContract() external view returns (address);
function getSushiswapBMIToETHPairContract() external view returns (address);
function getSushiswapBMIToUSDTPairContract() external view returns (address);
function getSushiSwapMasterChefV2Contract() external view returns (address);
function getWETHContract() external view returns (address);
function getUSDTContract() external view returns (address);
function getBMIContract() external view returns (address);
function getPriceFeedContract() external view returns (address);
function getPolicyBookRegistryContract() external view returns (address);
function getPolicyBookFabricContract() external view returns (address);
function getBMICoverStakingContract() external view returns (address);
function getBMICoverStakingViewContract() external view returns (address);
function getLegacyRewardsGeneratorContract() external view returns (address);
function getRewardsGeneratorContract() external view returns (address);
function getBMIUtilityNFTContract() external view returns (address);
function getNFTStakingContract() external view returns (address);
function getLiquidityMiningContract() external view returns (address);
function getClaimingRegistryContract() external view returns (address);
function getPolicyRegistryContract() external view returns (address);
function getLiquidityRegistryContract() external view returns (address);
function getClaimVotingContract() external view returns (address);
function getReinsurancePoolContract() external view returns (address);
function getLeveragePortfolioViewContract() external view returns (address);
function getCapitalPoolContract() external view returns (address);
function getPolicyBookAdminContract() external view returns (address);
function getPolicyQuoteContract() external view returns (address);
function getLegacyBMIStakingContract() external view returns (address);
function getBMIStakingContract() external view returns (address);
function getSTKBMIContract() external view returns (address);
function getVBMIContract() external view returns (address);
function getLegacyLiquidityMiningStakingContract() external view returns (address);
function getLiquidityMiningStakingETHContract() external view returns (address);
function getLiquidityMiningStakingUSDTContract() external view returns (address);
function getReputationSystemContract() external view returns (address);
function getAaveProtocolContract() external view returns (address);
function getAaveLendPoolAddressProvdierContract() external view returns (address);
function getAaveATokenContract() external view returns (address);
function getCompoundProtocolContract() external view returns (address);
function getCompoundCTokenContract() external view returns (address);
function getCompoundComptrollerContract() external view returns (address);
function getYearnProtocolContract() external view returns (address);
function getYearnVaultContract() external view returns (address);
function getYieldGeneratorContract() external view returns (address);
function getShieldMiningContract() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPolicyBookFabric {
enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE, VARIOUS}
/// @notice Create new Policy Book contract, access: ANY
/// @param _contract is Contract to create policy book for
/// @param _contractType is Contract to create policy book for
/// @param _description is bmiXCover token desription for this policy book
/// @param _projectSymbol replaces x in bmiXCover token symbol
/// @param _initialDeposit is an amount user deposits on creation (addLiquidity())
/// @return _policyBook is address of created contract
function create(
address _contract,
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol,
uint256 _initialDeposit,
address _shieldMiningToken
) external returns (address);
function createLeveragePools(
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
interface IPolicyBookRegistry {
struct PolicyBookStats {
string symbol;
address insuredContract;
IPolicyBookFabric.ContractType contractType;
uint256 maxCapacity;
uint256 totalSTBLLiquidity;
uint256 totalLeveragedLiquidity;
uint256 stakedSTBL;
uint256 APY;
uint256 annualInsuranceCost;
uint256 bmiXRatio;
bool whitelisted;
}
function policyBooksByInsuredAddress(address insuredContract) external view returns (address);
function policyBookFacades(address facadeAddress) external view returns (address);
/// @notice Adds PolicyBook to registry, access: PolicyFabric
function add(
address insuredContract,
IPolicyBookFabric.ContractType contractType,
address policyBook,
address facadeAddress
) external;
function whitelist(address policyBookAddress, bool whitelisted) external;
/// @notice returns required allowances for the policybooks
function getPoliciesPrices(
address[] calldata policyBooks,
uint256[] calldata epochsNumbers,
uint256[] calldata coversTokens
) external view returns (uint256[] memory _durations, uint256[] memory _allowances);
/// @notice Buys a batch of policies
function buyPolicyBatch(
address[] calldata policyBooks,
uint256[] calldata epochsNumbers,
uint256[] calldata coversTokens
) external;
/// @notice Checks if provided address is a PolicyBook
function isPolicyBook(address policyBook) external view returns (bool);
/// @notice Checks if provided address is a policyBookFacade
function isPolicyBookFacade(address _facadeAddress) external view returns (bool);
/// @notice Checks if provided address is a user leverage pool
function isUserLeveragePool(address policyBookAddress) external view returns (bool);
/// @notice Returns number of registered PolicyBooks with certain contract type
function countByType(IPolicyBookFabric.ContractType contractType)
external
view
returns (uint256);
/// @notice Returns number of registered PolicyBooks, access: ANY
function count() external view returns (uint256);
function countByTypeWhitelisted(IPolicyBookFabric.ContractType contractType)
external
view
returns (uint256);
function countWhitelisted() external view returns (uint256);
/// @notice Listing registered PolicyBooks with certain contract type, access: ANY
/// @return _policyBooksArr is array of registered PolicyBook addresses with certain contract type
function listByType(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr);
/// @notice Listing registered PolicyBooks, access: ANY
/// @return _policyBooksArr is array of registered PolicyBook addresses
function list(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr);
function listByTypeWhitelisted(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr);
function listWhitelisted(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr);
/// @notice Listing registered PolicyBooks with stats and certain contract type, access: ANY
function listWithStatsByType(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
/// @notice Listing registered PolicyBooks with stats, access: ANY
function listWithStats(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
function listWithStatsByTypeWhitelisted(
IPolicyBookFabric.ContractType contractType,
uint256 offset,
uint256 limit
) external view returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
function listWithStatsWhitelisted(uint256 offset, uint256 limit)
external
view
returns (address[] memory _policyBooksArr, PolicyBookStats[] memory _stats);
/// @notice Getting stats from policy books, access: ANY
/// @param policyBooks is list of PolicyBooks addresses
function stats(address[] calldata policyBooks)
external
view
returns (PolicyBookStats[] memory _stats);
/// @notice Return existing Policy Book contract, access: ANY
/// @param insuredContract is contract address to lookup for created IPolicyBook
function policyBookFor(address insuredContract) external view returns (address);
/// @notice Getting stats from policy books, access: ANY
/// @param insuredContracts is list of insuredContracts in registry
function statsByInsuredContracts(address[] calldata insuredContracts)
external
view
returns (PolicyBookStats[] memory _stats);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IRewardsGenerator {
struct PolicyBookRewardInfo {
uint256 rewardMultiplier; // includes 5 decimal places
uint256 totalStaked;
uint256 lastUpdateBlock;
uint256 lastCumulativeSum; // includes 100 percentage
uint256 cumulativeReward; // includes 100 percentage
}
struct StakeRewardInfo {
uint256 lastCumulativeSum; // includes 100 percentage
uint256 cumulativeReward;
uint256 stakeAmount;
}
/// @notice this function is called every time policybook's STBL to bmiX rate changes
function updatePolicyBookShare(uint256 newRewardMultiplier) external;
/// @notice aggregates specified nfts into a single one
function aggregate(
address policyBookAddress,
uint256[] calldata nftIndexes,
uint256 nftIndexTo
) external;
/// @notice migrates stake from the LegacyRewardsGenerator (will be called once for each user)
/// the rewards multipliers must be set in advance
function migrationStake(
address policyBookAddress,
uint256 nftIndex,
uint256 amount,
uint256 currentReward
) external;
/// @notice informs generator of stake (rewards)
function stake(
address policyBookAddress,
uint256 nftIndex,
uint256 amount
) external;
/// @notice returns policybook's APY multiplied by 10**5
function getPolicyBookAPY(address policyBookAddress) external view returns (uint256);
/// @notice returns policybook's RewardMultiplier multiplied by 10**5
function getPolicyBookRewardMultiplier(address policyBookAddress)
external
view
returns (uint256);
/// @dev returns PolicyBook reward per block multiplied by 10**25
function getPolicyBookRewardPerBlock(address policyBookAddress)
external
view
returns (uint256);
/// @notice returns PolicyBook's staked STBL
function getStakedPolicyBookSTBL(address policyBookAddress) external view returns (uint256);
/// @notice returns NFT's staked STBL
function getStakedNFTSTBL(uint256 nftIndex) external view returns (uint256);
/// @notice returns a reward of NFT
function getReward(address policyBookAddress, uint256 nftIndex)
external
view
returns (uint256);
/// @notice informs generator of withdrawal (all funds)
function withdrawFunds(address policyBookAddress, uint256 nftIndex) external returns (uint256);
/// @notice informs generator of withdrawal (rewards)
function withdrawReward(address policyBookAddress, uint256 nftIndex)
external
returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPriceFeed {
function howManyBMIsInUSDT(uint256 usdtAmount) external view returns (uint256);
function howManyUSDTsInBMI(uint256 bmiAmount) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/// @notice the intention of this library is to be able to easily convert
/// one amount of tokens with N decimal places
/// to another amount with M decimal places
library DecimalsConverter {
using SafeMath for uint256;
function convert(
uint256 amount,
uint256 baseDecimals,
uint256 destinationDecimals
) internal pure returns (uint256) {
if (baseDecimals > destinationDecimals) {
amount = amount.div(10**(baseDecimals - destinationDecimals));
} else if (baseDecimals < destinationDecimals) {
amount = amount.mul(10**(destinationDecimals - baseDecimals));
}
return amount;
}
function convertTo18(uint256 amount, uint256 baseDecimals) internal pure returns (uint256) {
return convert(amount, baseDecimals, 18);
}
function convertFrom18(uint256 amount, uint256 destinationDecimals)
internal
pure
returns (uint256)
{
return convert(amount, 18, destinationDecimals);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <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 {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// 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;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev 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.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, 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.7.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.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) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
} | updates cumulative sum for a particular PB or for all of them if policyBookAddress is zero | function _updateCumulativeSum(address policyBookAddress) internal {
uint256 toAddSum = block.number.sub(lastUpdateBlock).mul(toUpdateRatio);
uint256 totalStaked = totalPoolStaked;
uint256 newCumulativeSum = cumulativeSum.add(toAddSum);
totalStaked > 0
? toUpdateRatio = rewardPerBlock.mul(PERCENTAGE_100 * 10**5).div(totalStaked)
: toUpdateRatio = 0;
if (policyBookAddress != address(0)) {
PolicyBookRewardInfo storage info = _policyBooksRewards[policyBookAddress];
info.cumulativeReward = info.cumulativeReward.add(
newCumulativeSum.sub(info.lastCumulativeSum).mul(info.rewardMultiplier).div(10**5)
);
info.lastCumulativeSum = newCumulativeSum;
}
cumulativeSum = newCumulativeSum;
lastUpdateBlock = block.number;
}
| 5,815,142 |
pragma solidity 0.4.18;
/**
* @title RLPReader
* @dev RLPReader is used to read and parse RLP encoded data in memory.
* @author Andreas Olofsson ([email protected])
*/
library PlasmaRLP {
uint constant DATA_SHORT_START = 0x80;
uint constant DATA_LONG_START = 0xB8;
uint constant LIST_SHORT_START = 0xC0;
uint constant LIST_LONG_START = 0xF8;
uint constant DATA_LONG_OFFSET = 0xB7;
struct RLPItem {
uint _unsafe_memPtr; // Pointer to the RLP-encoded bytes.
uint _unsafe_length; // Number of bytes. This is the full length of the string.
}
struct exitingTx {
uint256 amount;
address exitor;
uint256 inputCount;
}
struct Iterator {
RLPItem _unsafe_item; // Item that's being iterated over.
uint _unsafe_nextPtr; // Position of the next item in the list.
}
/* Public Functions */
function getUtxoPos(bytes memory challengingTxBytes, uint256 numItems, uint256 oIndex)
internal
constant
returns (uint256)
{
var txList = toList(toRLPItem(challengingTxBytes), numItems);
uint256 oIndexShift = oIndex * 3;
return toUint(txList[0 + oIndexShift]) + toUint(txList[1 + oIndexShift]) + toUint(txList[2 + oIndexShift]);
}
function createExitingTx(bytes memory exitingTxBytes, uint256 numItems, uint256 oindex)
internal
constant
returns (exitingTx)
{
var txList = toList(toRLPItem(exitingTxBytes), numItems);
return exitingTx({
amount: toUint(txList[7 + 2 * oindex]),
exitor: toAddress(txList[6 + 2 * oindex]),
inputCount: toUint(txList[0]) * toUint(txList[3])
});
}
/* Iterator */
function next(Iterator memory self) private constant returns (RLPItem memory subItem) {
var ptr = self._unsafe_nextPtr;
var itemLength = _itemLength(ptr);
subItem._unsafe_memPtr = ptr;
subItem._unsafe_length = itemLength;
self._unsafe_nextPtr = ptr + itemLength;
}
function hasNext(Iterator memory self) private constant returns (bool) {
var item = self._unsafe_item;
return self._unsafe_nextPtr < item._unsafe_memPtr + item._unsafe_length;
}
/* RLPItem */
/// @dev Creates an RLPItem from an array of RLP encoded bytes.
/// @param self The RLP encoded bytes.
/// @return An RLPItem
function toRLPItem(bytes memory self) private constant returns (RLPItem memory) {
uint len = self.length;
uint memPtr;
assembly {
memPtr := add(self, 0x20)
}
return RLPItem(memPtr, len);
}
/// @dev Create an iterator.
/// @param self The RLP item.
/// @return An 'Iterator' over the item.
function iterator(RLPItem memory self) private constant returns (Iterator memory it) {
uint ptr = self._unsafe_memPtr + _payloadOffset(self);
it._unsafe_item = self;
it._unsafe_nextPtr = ptr;
}
/// @dev Get the list of sub-items from an RLP encoded list.
/// Warning: This requires passing in the number of items.
/// @param self The RLP item.
/// @return Array of RLPItems.
function toList(RLPItem memory self, uint256 numItems) private constant returns (RLPItem[] memory list) {
list = new RLPItem[](numItems);
var it = iterator(self);
uint idx;
while(idx < numItems) {
list[idx] = next(it);
idx++;
}
}
/// @dev Decode an RLPItem into a uint. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toUint(RLPItem memory self) private constant returns (uint data) {
var (rStartPos, len) = _decode(self);
assembly {
data := div(mload(rStartPos), exp(256, sub(32, len)))
}
}
/// @dev Decode an RLPItem into an address. This will not work if the
/// RLPItem is a list.
/// @param self The RLPItem.
/// @return The decoded string.
function toAddress(RLPItem memory self)
private
view
returns (address data)
{
var (rStartPos, len) = _decode(self);
assembly {
data := div(mload(rStartPos), exp(256, 12))
}
}
// Get the payload offset.
function _payloadOffset(RLPItem memory self)
private
view
returns (uint)
{
uint b0;
uint memPtr = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(memPtr))
}
if(b0 < DATA_SHORT_START)
return 0;
if(b0 < DATA_LONG_START || (b0 >= LIST_SHORT_START && b0 < LIST_LONG_START))
return 1;
}
// Get the full length of an RLP item.
function _itemLength(uint memPtr)
private
view
returns (uint len)
{
uint b0;
assembly {
b0 := byte(0, mload(memPtr))
}
if (b0 < DATA_SHORT_START)
len = 1;
else if (b0 < DATA_LONG_START)
len = b0 - DATA_SHORT_START + 1;
}
// Get start position and length of the data.
function _decode(RLPItem memory self)
private
view
returns (uint memPtr, uint len)
{
uint b0;
uint start = self._unsafe_memPtr;
assembly {
b0 := byte(0, mload(start))
}
if (b0 < DATA_SHORT_START) {
memPtr = start;
len = 1;
return;
}
if (b0 < DATA_LONG_START) {
len = self._unsafe_length - 1;
memPtr = start + 1;
} else {
uint bLen;
assembly {
bLen := sub(b0, 0xB7) // DATA_LONG_OFFSET
}
len = self._unsafe_length - 1 - bLen;
memPtr = start + bLen + 1;
}
return;
}
}
| Decode an RLPItem into an address. This will not work if the RLPItem is a list. self The RLPItem. return The decoded string. | function toAddress(RLPItem memory self)
private
view
returns (address data)
{
var (rStartPos, len) = _decode(self);
assembly {
data := div(mload(rStartPos), exp(256, 12))
}
}
| 12,912,980 |
pragma solidity ^0.4.11;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert() on error
*/
library SafeMath {
function mul(uint a, uint b) internal returns (uint) {
uint c = a * b;
asserts(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
asserts(b <= a);
return a - b;
}
function div(uint a, uint b) internal returns (uint) {
asserts(b > 0);
uint c = a / b;
asserts(a == b * c + a % b);
return c;
}
function sub(uint a, uint b) internal returns (uint) {
asserts(b <= a);
return a - b;
}
function add(uint a, uint b) internal returns (uint) {
uint c = a + b;
asserts(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
function asserts(bool assertion) internal {
if (!assertion) {
revert();
}
}
}
/**
* @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;
function Ownable() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) revert();
_;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
bool public stopped;
modifier stopInEmergency {
if (stopped) {
revert();
}
_;
}
modifier onlyInEmergency {
if (!stopped) {
revert();
}
_;
}
// called by the owner on emergency, triggers stopped state
function emergencyStop() external onlyOwner {
stopped = true;
}
// called by the owner on end of emergency, returns to normal state
function release() external onlyOwner onlyInEmergency {
stopped = false;
}
}
/**
* ERC 20 token
*
* https://github.com/ethereum/EIPs/issues/20
*/
contract Token {
/// @return total amount of tokens
function totalSupply() constant returns (uint256 supply) {}
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant returns (uint256 balance) {}
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) returns (bool success) {}
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {}
/// @notice `msg.sender` approves `_addr` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) returns (bool success) {}
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {}
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/**
* ERC 20 token
*
* https://github.com/ethereum/EIPs/issues/20
*/
contract StandardToken is Token {
/**
* Reviewed:
* - Interger overflow = OK, checked
*/
function transfer(address _to, uint256 _value) returns (bool success) {
//Default assumes totalSupply can't be over max (2^256 - 1).
//If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap.
//Replace the if with this one instead.
if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
//if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping(address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
}
contract DigipulseFirstRoundToken is StandardToken {
using SafeMath for uint;
}
contract DigipulseToken is StandardToken, Pausable {
using SafeMath for uint;
// Digipulse Token setup
string public name = "DigiPulse Token";
string public symbol = "DGPT";
uint8 public decimals = 18;
string public version = 'v0.0.3';
address public owner = msg.sender;
uint freezeTransferForOwnerTime;
// Token information
address public DGPTokenOldContract = 0x9AcA6aBFe63A5ae0Dc6258cefB65207eC990Aa4D;
DigipulseFirstRoundToken public coin;
// Token details
// ICO details
bool public finalizedCrowdfunding = false;
uint public constant MIN_CAP = 500 * 1e18;
uint public constant MAX_CAP = 41850 * 1e18; // + 1600 OBR + 1200 PRE
uint public TierAmount = 8300 * 1e18;
uint public constant TOKENS_PER_ETH = 250;
uint public constant MIN_INVEST_ETHER = 500 finney;
uint public startTime;
uint public endTime;
uint public etherReceived;
uint public coinSentToEther;
bool public isFinalized;
// Original Backers round
bool public isOBR;
uint public raisedOBR;
uint public MAX_OBR_CAP = 1600 * 1e18;
uint public OBR_Duration;
// Enums
enum TierState{Completed, Tier01, Tier02, Tier03, Tier04, Tier05, Overspend, Failure, OBR}
// Modifiers
modifier minCapNotReached() {
require (now < endTime && etherReceived <= MIN_CAP);
_;
}
// Mappings
mapping(address => Backer) public backers;
struct Backer {
uint weiReceived;
uint coinSent;
}
// Events
event LogReceivedETH(address addr, uint value);
event LogCoinsEmited(address indexed from, uint amount);
// Bounties, Presale, Company tokens
address public presaleWallet = 0x83D0Aa2292efD8475DF241fBA42fe137dA008d79;
address public companyWallet = 0x5C967dE68FC54365872203D49B51cDc79a61Ca85;
address public bountyWallet = 0x49fe3E535906d10e55E2e4AD47ff6cB092Abc692;
// Allocated 10% for the team members
address public teamWallet_1 = 0x91D9B09a4157e02783D5D19f7DfC66a759bDc1E4;
address public teamWallet_2 = 0x56298A4e0f60Ab4A323EDB0b285A9421F8e6E276;
address public teamWallet_3 = 0x09e9e24b3e6bA1E714FB86B04602a7Aa62D587FD;
address public teamWallet_4 = 0x2F4283D0362A3AaEe359aC55F2aC7a4615f97c46;
mapping(address => uint256) public payments;
uint256 public totalPayments;
function asyncSend(address dest, uint256 amount) internal {
payments[dest] = payments[dest].add(amount);
totalPayments = totalPayments.add(amount);
}
function withdrawPayments() onlyOwner {
// Can only be called if the ICO is successfull
require (isFinalized);
require (etherReceived != 0);
owner.transfer(this.balance);
}
// Init contract
function DigipulseToken() {
coin = DigipulseFirstRoundToken(DGPTokenOldContract);
isOBR = true;
isFinalized = false;
start();
// Allocate tokens
balances[presaleWallet] = 600000 * 1e18; // 600.000 for presale (closed already)
Transfer(0x0, presaleWallet, 600000 * 1e18);
balances[teamWallet_1] = 20483871 * 1e16; // 1% for team member 1
Transfer(0x0, teamWallet_1, 20483871 * 1e16);
balances[teamWallet_2] = 901290324 * 1e15; // 4.4% for team member 2
Transfer(0x0, teamWallet_2, 901290324 * 1e15);
balances[teamWallet_3] = 901290324 * 1e15; // 4.4% for team member 3
Transfer(0x0, teamWallet_3, 901290324 * 1e15);
balances[teamWallet_4] = 40967724 * 1e15; // 0.2% for team member 4
Transfer(0x0, teamWallet_4, 40967724 * 1e15);
balances[companyWallet] = 512096775 * 1e16; // Company shares
Transfer(0x0, companyWallet, 512096775 * 1e16);
balances[bountyWallet] = 61451613 * 1e16; // Bounty shares
Transfer(0x0, bountyWallet, 61451613 * 1e16);
balances[this] = 12100000 * 1e18; // Tokens to be issued during the crowdsale
Transfer(0x0, this, 12100000 * 1e18);
totalSupply = 20483871 * 1e18;
}
function start() onlyOwner {
if (startTime != 0) revert();
startTime = 1506610800 ; //28/09/2017 03:00 PM UTC
endTime = 1509494400 ; //01/11/2017 00:00 PM UTC
OBR_Duration = startTime + 72 hours;
}
function toWei(uint _amount) constant returns (uint256 result){
// Set to finney for ease of testing on ropsten: 1e15 (or smaller) || Ether for main net 1e18
result = _amount.mul(1e18);
return result;
}
function isOriginalRoundContributor() constant returns (bool _state){
uint balance = coin.balanceOf(msg.sender);
if (balance > 0) return true;
}
function() payable {
if (isOBR) {
buyDigipulseOriginalBackersRound(msg.sender);
} else {
buyDigipulseTokens(msg.sender);
}
}
function buyDigipulseOriginalBackersRound(address beneficiary) internal {
// User must have old tokens
require (isOBR);
require(msg.value > 0);
require(msg.value > MIN_INVEST_ETHER);
require(isOriginalRoundContributor());
uint ethRaised = raisedOBR;
uint userContribution = msg.value;
uint shouldBecome = ethRaised.add(userContribution);
uint excess = 0;
Backer storage backer = backers[beneficiary];
// Define excess and amount to include
if (shouldBecome > MAX_OBR_CAP) {
userContribution = MAX_OBR_CAP - ethRaised;
excess = msg.value - userContribution;
}
uint tierBonus = getBonusPercentage( userContribution );
balances[beneficiary] += tierBonus;
balances[this] -= tierBonus;
raisedOBR = raisedOBR.add(userContribution);
backer.coinSent = backer.coinSent.add(tierBonus);
backer.weiReceived = backer.weiReceived.add(userContribution);
if (raisedOBR >= MAX_OBR_CAP) {
isOBR = false;
}
Transfer(this, beneficiary, tierBonus);
LogCoinsEmited(beneficiary, tierBonus);
LogReceivedETH(beneficiary, userContribution);
// Send excess back
if (excess > 0) {
assert(msg.sender.send(excess));
}
}
function buyDigipulseTokens(address beneficiary) internal {
require (!finalizedCrowdfunding);
require (now > OBR_Duration);
require (msg.value > MIN_INVEST_ETHER);
uint CurrentTierMax = getCurrentTier().mul(TierAmount);
// Account for last tier with extra 350 ETH
if (getCurrentTier() == 5) {
CurrentTierMax = CurrentTierMax.add(350 * 1e18);
}
uint userContribution = msg.value;
uint shouldBecome = etherReceived.add(userContribution);
uint tierBonus = 0;
uint excess = 0;
uint excess_bonus = 0;
Backer storage backer = backers[beneficiary];
// Define excess over tier and amount to include
if (shouldBecome > CurrentTierMax) {
userContribution = CurrentTierMax - etherReceived;
excess = msg.value - userContribution;
}
tierBonus = getBonusPercentage( userContribution );
balances[beneficiary] += tierBonus;
balances[this] -= tierBonus;
etherReceived = etherReceived.add(userContribution);
backer.coinSent = backer.coinSent.add(tierBonus);
backer.weiReceived = backer.weiReceived.add(userContribution);
Transfer(this, beneficiary, tierBonus);
// Tap into next tier with appropriate bonuses
if (excess > 0 && etherReceived < MAX_CAP) {
excess_bonus = getBonusPercentage( excess );
balances[beneficiary] += excess_bonus;
balances[this] -= excess_bonus;
etherReceived = etherReceived.add(excess);
backer.coinSent = backer.coinSent.add(excess_bonus);
backer.weiReceived = backer.weiReceived.add(excess);
Transfer(this, beneficiary, excess_bonus);
}
LogCoinsEmited(beneficiary, tierBonus.add(excess_bonus));
LogReceivedETH(beneficiary, userContribution.add(excess));
if(etherReceived >= MAX_CAP) {
finalizedCrowdfunding = true;
}
// Send excess back
if (excess > 0 && etherReceived == MAX_CAP) {
assert(msg.sender.send(excess));
}
}
function getCurrentTier() returns (uint Tier) {
uint ethRaised = etherReceived;
if (isOBR) return uint(TierState.OBR);
if (ethRaised >= 0 && ethRaised < toWei(8300)) return uint(TierState.Tier01);
else if (ethRaised >= toWei(8300) && ethRaised < toWei(16600)) return uint(TierState.Tier02);
else if (ethRaised >= toWei(16600) && ethRaised < toWei(24900)) return uint(TierState.Tier03);
else if (ethRaised >= toWei(24900) && ethRaised < toWei(33200)) return uint(TierState.Tier04);
else if (ethRaised >= toWei(33200) && ethRaised <= toWei(MAX_CAP)) return uint(TierState.Tier05); // last tier has 8650
else if (ethRaised > toWei(MAX_CAP)) {
finalizedCrowdfunding = true;
return uint(TierState.Overspend);
}
else return uint(TierState.Failure);
}
function getBonusPercentage(uint contribution) returns (uint _amount) {
uint tier = getCurrentTier();
uint bonus =
tier == 1 ? 20 :
tier == 2 ? 15 :
tier == 3 ? 10 :
tier == 4 ? 5 :
tier == 5 ? 0 :
tier == 8 ? 50 :
0;
return contribution.mul(TOKENS_PER_ETH).mul(bonus + 100).div(100);
}
function refund(uint _value) minCapNotReached public {
if (_value != backers[msg.sender].coinSent) revert(); // compare value from backer balance
uint ETHToSend = backers[msg.sender].weiReceived;
backers[msg.sender].weiReceived=0;
if (ETHToSend > 0) {
asyncSend(msg.sender, ETHToSend); // pull payment to get refund in ETH
}
}
function finalize() onlyOwner public {
require (now >= endTime);
require (etherReceived >= MIN_CAP);
finalizedCrowdfunding = true;
isFinalized = true;
freezeTransferForOwnerTime = now + 182 days;
}
function transfer(address _to, uint256 _value) returns (bool success) {
require(isFinalized);
if (msg.sender == owner) {
require(now > freezeTransferForOwnerTime);
}
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
require(isFinalized);
if (msg.sender == owner) {
require(now > freezeTransferForOwnerTime);
}
return super.transferFrom(_from, _to, _value);
}
} | Set to finney for ease of testing on ropsten: 1e15 (or smaller) || Ether for main net 1e18 | function toWei(uint _amount) constant returns (uint256 result){
result = _amount.mul(1e18);
return result;
}
| 5,376,854 |
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
import "LoanClosingsBase.sol";
contract LoanClosings is LoanClosingsBase {
function initialize(
address target)
external
onlyOwner
{
_setTarget(this.liquidate.selector, target);
_setTarget(this.closeWithDeposit.selector, target);
_setTarget(this.closeWithSwap.selector, target);
// TEMP: remove after upgrade
/*_setTarget(bytes4(keccak256("rollover(bytes32,bytes)")), address(0));
_setTarget(bytes4(keccak256("liquidateWithGasToken(bytes32,address,address,uint256)")), address(0));
_setTarget(bytes4(keccak256("closeWithDepositWithGasToken(bytes32,address,address,uint256)")), address(0));
_setTarget(bytes4(keccak256("closeWithSwapWithGasToken(bytes32,address,address,uint256,bool,bytes)")), address(0));
_setTarget(bytes4(keccak256("swapExternalWithGasToken(address,address,address,address,address,uint256,uint256,bytes)")), address(0));*/
}
function liquidate(
bytes32 loanId,
address receiver,
uint256 closeAmount) // denominated in loanToken
external
payable
nonReentrant
returns (
uint256 loanCloseAmount,
uint256 seizedAmount,
address seizedToken
)
{
return _liquidate(
loanId,
receiver,
closeAmount
);
}
function closeWithDeposit(
bytes32 loanId,
address receiver,
uint256 depositAmount) // denominated in loanToken
public
payable
nonReentrant
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
)
{
return _closeWithDeposit(
loanId,
receiver,
depositAmount
);
}
function closeWithSwap(
bytes32 loanId,
address receiver,
uint256 swapAmount, // denominated in collateralToken
bool returnTokenIsCollateral, // true: withdraws collateralToken, false: withdraws loanToken
bytes memory loanDataBytes)
public
nonReentrant
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
)
{
return _closeWithSwap(
loanId,
receiver,
swapAmount,
returnTokenIsCollateral,
loanDataBytes
);
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
import "State.sol";
import "LoanClosingsEvents.sol";
import "VaultController.sol";
import "InterestHandler.sol";
import "FeesHelper.sol";
import "LiquidationHelper.sol";
import "SwapsUser.sol";
import "ILoanPool.sol";
import "PausableGuardian.sol";
contract LoanClosingsBase is State, LoanClosingsEvents, VaultController, InterestHandler, FeesHelper, SwapsUser, LiquidationHelper, PausableGuardian {
enum CloseTypes {
Deposit,
Swap,
Liquidation
}
function _liquidate(
bytes32 loanId,
address receiver,
uint256 closeAmount)
internal
pausable
returns (
uint256 loanCloseAmount,
uint256 seizedAmount,
address seizedToken
)
{
Loan memory loanLocal = loans[loanId];
require(loanLocal.active, "loan is closed");
LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId];
uint256 principalPlusInterest = _settleInterest(loanLocal.lender, loanId)
.add(loanLocal.principal);
(uint256 currentMargin, uint256 collateralToLoanRate) = _getCurrentMargin(
loanParamsLocal.loanToken,
loanParamsLocal.collateralToken,
principalPlusInterest,
loanLocal.collateral,
false // silentFail
);
require(
currentMargin <= loanParamsLocal.maintenanceMargin,
"healthy position"
);
if (receiver == address(0)) {
receiver = msg.sender;
}
loanCloseAmount = closeAmount;
(uint256 maxLiquidatable, uint256 maxSeizable) = _getLiquidationAmounts(
principalPlusInterest,
loanLocal.collateral,
currentMargin,
loanParamsLocal.maintenanceMargin,
collateralToLoanRate,
liquidationIncentivePercent[loanParamsLocal.loanToken][loanParamsLocal.collateralToken]
);
if (loanCloseAmount < maxLiquidatable) {
seizedAmount = maxSeizable
.mul(loanCloseAmount)
.div(maxLiquidatable);
} else {
if (loanCloseAmount > maxLiquidatable) {
// adjust down the close amount to the max
loanCloseAmount = maxLiquidatable;
}
seizedAmount = maxSeizable;
}
require(loanCloseAmount != 0, "nothing to liquidate");
// liquidator deposits the principal being closed
_returnPrincipalWithDeposit(
loanParamsLocal.loanToken,
loanLocal.lender,
loanCloseAmount
);
seizedToken = loanParamsLocal.collateralToken;
if (seizedAmount != 0) {
loanLocal.collateral = loanLocal.collateral
.sub(seizedAmount);
_withdrawAsset(
seizedToken,
receiver,
seizedAmount
);
}
_emitClosingEvents(
loanParamsLocal,
loanLocal,
loanCloseAmount,
seizedAmount,
collateralToLoanRate,
0, // collateralToLoanSwapRate
currentMargin,
CloseTypes.Liquidation
);
_closeLoan(
loanLocal,
loanParamsLocal.loanToken,
loanCloseAmount
);
}
function _closeWithDeposit(
bytes32 loanId,
address receiver,
uint256 depositAmount) // denominated in loanToken
internal
pausable
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
)
{
require(depositAmount != 0, "depositAmount == 0");
Loan memory loanLocal = loans[loanId];
_checkAuthorized(
loanLocal.id,
loanLocal.active,
loanLocal.borrower
);
if (receiver == address(0)) {
receiver = msg.sender;
}
LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId];
uint256 principalPlusInterest = _settleInterest(loanLocal.lender, loanId)
.add(loanLocal.principal);
// can't close more than the full principal
loanCloseAmount = depositAmount > principalPlusInterest ?
principalPlusInterest :
depositAmount;
if (loanCloseAmount != 0) {
_returnPrincipalWithDeposit(
loanParamsLocal.loanToken,
loanLocal.lender,
loanCloseAmount
);
}
if (loanCloseAmount == principalPlusInterest) {
// collateral is only withdrawn if the loan is closed in full
withdrawAmount = loanLocal.collateral;
withdrawToken = loanParamsLocal.collateralToken;
loanLocal.collateral = 0;
_withdrawAsset(
withdrawToken,
receiver,
withdrawAmount
);
}
_finalizeClose(
loanLocal,
loanParamsLocal,
loanCloseAmount,
withdrawAmount, // collateralCloseAmount
0, // collateralToLoanSwapRate
CloseTypes.Deposit
);
}
function _closeWithSwap(
bytes32 loanId,
address receiver,
uint256 swapAmount,
bool returnTokenIsCollateral,
bytes memory loanDataBytes)
internal
pausable
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
)
{
require(swapAmount != 0, "swapAmount == 0");
Loan memory loanLocal = loans[loanId];
_checkAuthorized(
loanLocal.id,
loanLocal.active,
loanLocal.borrower
);
if (receiver == address(0)) {
receiver = msg.sender;
}
LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId];
uint256 principalPlusInterest = _settleInterest(loanLocal.lender, loanId)
.add(loanLocal.principal);
if (swapAmount > loanLocal.collateral) {
swapAmount = loanLocal.collateral;
}
loanCloseAmount = principalPlusInterest;
if (swapAmount != loanLocal.collateral) {
loanCloseAmount = loanCloseAmount
.mul(swapAmount)
.div(loanLocal.collateral);
}
require(loanCloseAmount != 0, "loanCloseAmount == 0");
uint256 usedCollateral;
uint256 collateralToLoanSwapRate;
(usedCollateral, withdrawAmount, collateralToLoanSwapRate) = _coverPrincipalWithSwap(
loanLocal,
loanParamsLocal,
swapAmount,
loanCloseAmount,
returnTokenIsCollateral,
loanDataBytes
);
if (loanCloseAmount != 0) {
// Repays principal to lender
vaultWithdraw(
loanParamsLocal.loanToken,
loanLocal.lender,
loanCloseAmount
);
}
if (usedCollateral != 0) {
loanLocal.collateral = loanLocal.collateral
.sub(usedCollateral);
}
withdrawToken = returnTokenIsCollateral ?
loanParamsLocal.collateralToken :
loanParamsLocal.loanToken;
if (withdrawAmount != 0) {
_withdrawAsset(
withdrawToken,
receiver,
withdrawAmount
);
}
_finalizeClose(
loanLocal,
loanParamsLocal,
loanCloseAmount,
usedCollateral,
collateralToLoanSwapRate,
CloseTypes.Swap
);
}
function _updateDepositAmount(
bytes32 loanId,
uint256 principalBefore,
uint256 principalAfter)
internal
{
uint256 depositValueAsLoanToken;
uint256 depositValueAsCollateralToken;
bytes32 slot = keccak256(abi.encode(loanId, LoanDepositValueID));
assembly {
switch principalAfter
case 0 {
sstore(slot, 0)
sstore(add(slot, 1), 0)
}
default {
depositValueAsLoanToken := div(mul(sload(slot), principalAfter), principalBefore)
sstore(slot, depositValueAsLoanToken)
slot := add(slot, 1)
depositValueAsCollateralToken := div(mul(sload(slot), principalAfter), principalBefore)
sstore(slot, depositValueAsCollateralToken)
}
}
emit LoanDeposit(
loanId,
depositValueAsLoanToken,
depositValueAsCollateralToken
);
}
function _checkAuthorized(
bytes32 _id,
bool _active,
address _borrower)
internal
view
{
require(_active, "loan is closed");
require(
msg.sender == _borrower ||
delegatedManagers[_id][msg.sender],
"unauthorized"
);
}
// The receiver always gets back an ERC20 (even WETH)
function _returnPrincipalWithDeposit(
address loanToken,
address receiver,
uint256 principalNeeded)
internal
{
if (principalNeeded != 0) {
if (msg.value == 0) {
vaultTransfer(
loanToken,
msg.sender,
receiver,
principalNeeded
);
} else {
require(loanToken == address(wethToken), "wrong asset sent");
require(msg.value >= principalNeeded, "not enough ether");
wethToken.deposit.value(principalNeeded)();
if (receiver != address(this)) {
vaultTransfer(
loanToken,
address(this),
receiver,
principalNeeded
);
}
if (msg.value > principalNeeded) {
// refund overage
Address.sendValue(
msg.sender,
msg.value - principalNeeded
);
}
}
} else {
require(msg.value == 0, "wrong asset sent");
}
}
function _coverPrincipalWithSwap(
Loan memory loanLocal,
LoanParams memory loanParamsLocal,
uint256 swapAmount,
uint256 principalNeeded,
bool returnTokenIsCollateral,
bytes memory loanDataBytes)
internal
returns (uint256 usedCollateral, uint256 withdrawAmount, uint256 collateralToLoanSwapRate)
{
uint256 destTokenAmountReceived;
uint256 sourceTokenAmountUsed;
(destTokenAmountReceived, sourceTokenAmountUsed, collateralToLoanSwapRate) = _doCollateralSwap(
loanLocal,
loanParamsLocal,
swapAmount,
principalNeeded,
returnTokenIsCollateral,
loanDataBytes
);
if (returnTokenIsCollateral) {
if (destTokenAmountReceived > principalNeeded) {
// better fill than expected, so send excess to borrower
vaultWithdraw(
loanParamsLocal.loanToken,
loanLocal.borrower,
destTokenAmountReceived - principalNeeded
);
}
withdrawAmount = swapAmount > sourceTokenAmountUsed ?
swapAmount - sourceTokenAmountUsed :
0;
} else {
require(sourceTokenAmountUsed == swapAmount, "swap error");
withdrawAmount = destTokenAmountReceived - principalNeeded;
}
usedCollateral = sourceTokenAmountUsed > swapAmount ?
sourceTokenAmountUsed :
swapAmount;
}
function _doCollateralSwap(
Loan memory loanLocal,
LoanParams memory loanParamsLocal,
uint256 swapAmount,
uint256 principalNeeded,
bool returnTokenIsCollateral,
bytes memory loanDataBytes)
internal
returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed, uint256 collateralToLoanSwapRate)
{
(destTokenAmountReceived, sourceTokenAmountUsed, collateralToLoanSwapRate) = _loanSwap(
loanLocal.id,
loanParamsLocal.collateralToken,
loanParamsLocal.loanToken,
loanLocal.borrower,
swapAmount, // minSourceTokenAmount
loanLocal.collateral, // maxSourceTokenAmount
returnTokenIsCollateral ?
principalNeeded : // requiredDestTokenAmount
0,
false, // bypassFee
loanDataBytes
);
require(destTokenAmountReceived >= principalNeeded, "insufficient dest amount");
require(sourceTokenAmountUsed <= loanLocal.collateral, "excessive source amount");
}
// withdraws asset to receiver
function _withdrawAsset(
address assetToken,
address receiver,
uint256 assetAmount)
internal
{
if (assetAmount != 0) {
if (assetToken == address(wethToken)) {
vaultEtherWithdraw(
receiver,
assetAmount
);
} else {
vaultWithdraw(
assetToken,
receiver,
assetAmount
);
}
}
}
function _getCurrentMargin(
address loanToken,
address collateralToken,
uint256 principal,
uint256 collateral,
bool silentFail)
internal
returns (uint256 currentMargin, uint256 collateralToLoanRate)
{
address _priceFeeds = priceFeeds;
(bool success, bytes memory data) = _priceFeeds.staticcall(
abi.encodeWithSelector(
IPriceFeeds(_priceFeeds).getCurrentMargin.selector,
loanToken,
collateralToken,
principal,
collateral
)
);
if (success) {
assembly {
currentMargin := mload(add(data, 32))
collateralToLoanRate := mload(add(data, 64))
}
} else {
require(silentFail, "margin query failed");
}
}
function _finalizeClose(
Loan memory loanLocal,
LoanParams memory loanParamsLocal,
uint256 loanCloseAmount,
uint256 collateralCloseAmount,
uint256 collateralToLoanSwapRate,
CloseTypes closeType)
internal
{
(uint256 principalBefore, uint256 principalAfter) = _closeLoan(
loanLocal,
loanParamsLocal.loanToken,
loanCloseAmount
);
// this is still called even with full loan close to return collateralToLoanRate
(uint256 currentMargin, uint256 collateralToLoanRate) = _getCurrentMargin(
loanParamsLocal.loanToken,
loanParamsLocal.collateralToken,
principalAfter,
loanLocal.collateral,
true // silentFail
);
//// Note: We can safely skip the margin check if closing via closeWithDeposit or if closing the loan in full by any method ////
require(
closeType == CloseTypes.Deposit ||
principalAfter == 0 || // loan fully closed
currentMargin > loanParamsLocal.maintenanceMargin,
"unhealthy position"
);
_updateDepositAmount(
loanLocal.id,
principalBefore,
principalAfter
);
_emitClosingEvents(
loanParamsLocal,
loanLocal,
loanCloseAmount,
collateralCloseAmount,
collateralToLoanRate,
collateralToLoanSwapRate,
currentMargin,
closeType
);
}
function _closeLoan(
Loan memory loanLocal,
address loanToken,
uint256 loanCloseAmount)
internal
returns (uint256 principalBefore, uint256 principalAfter)
{
require(loanCloseAmount != 0, "nothing to close");
principalBefore = loanLocal.principal;
uint256 loanInterest = loanInterestTotal[loanLocal.id];
if (loanCloseAmount == principalBefore.add(loanInterest)) {
poolPrincipalTotal[loanLocal.lender] = poolPrincipalTotal[loanLocal.lender]
.sub(principalBefore);
loanLocal.principal = 0;
loanInterestTotal[loanLocal.id] = 0;
loanLocal.active = false;
loanLocal.endTimestamp = block.timestamp;
loanLocal.pendingTradesId = 0;
activeLoansSet.removeBytes32(loanLocal.id);
lenderLoanSets[loanLocal.lender].removeBytes32(loanLocal.id);
borrowerLoanSets[loanLocal.borrower].removeBytes32(loanLocal.id);
} else {
// interest is paid before principal
if (loanCloseAmount >= loanInterest) {
principalAfter = principalBefore.sub(loanCloseAmount - loanInterest);
loanLocal.principal = principalAfter;
poolPrincipalTotal[loanLocal.lender] = poolPrincipalTotal[loanLocal.lender]
.sub(loanCloseAmount - loanInterest);
loanInterestTotal[loanLocal.id] = 0;
} else {
principalAfter = principalBefore;
loanInterestTotal[loanLocal.id] = loanInterest - loanCloseAmount;
loanInterest = loanCloseAmount;
}
}
uint256 poolInterest = poolInterestTotal[loanLocal.lender];
if (poolInterest > loanInterest) {
poolInterestTotal[loanLocal.lender] = poolInterest - loanInterest;
}
else {
poolInterestTotal[loanLocal.lender] = 0;
}
// pay fee
_payLendingFee(
loanLocal.lender,
loanToken,
_getLendingFee(loanInterest)
);
loans[loanLocal.id] = loanLocal;
}
function _emitClosingEvents(
LoanParams memory loanParamsLocal,
Loan memory loanLocal,
uint256 loanCloseAmount,
uint256 collateralCloseAmount,
uint256 collateralToLoanRate,
uint256 collateralToLoanSwapRate,
uint256 currentMargin,
CloseTypes closeType)
internal
{
if (closeType == CloseTypes.Deposit) {
emit CloseWithDeposit(
loanLocal.borrower, // user (borrower)
loanLocal.lender, // lender
loanLocal.id, // loanId
msg.sender, // closer
loanParamsLocal.loanToken, // loanToken
loanParamsLocal.collateralToken, // collateralToken
loanCloseAmount, // loanCloseAmount
collateralCloseAmount, // collateralCloseAmount
collateralToLoanRate, // collateralToLoanRate
currentMargin // currentMargin
);
} else if (closeType == CloseTypes.Swap) {
// exitPrice = 1 / collateralToLoanSwapRate
if (collateralToLoanSwapRate != 0) {
collateralToLoanSwapRate = SafeMath.div(WEI_PRECISION * WEI_PRECISION, collateralToLoanSwapRate);
}
// currentLeverage = 100 / currentMargin
if (currentMargin != 0) {
currentMargin = SafeMath.div(10**38, currentMargin);
}
emit CloseWithSwap(
loanLocal.borrower, // user (trader)
loanLocal.lender, // lender
loanLocal.id, // loanId
loanParamsLocal.collateralToken, // collateralToken
loanParamsLocal.loanToken, // loanToken
msg.sender, // closer
collateralCloseAmount, // positionCloseSize
loanCloseAmount, // loanCloseAmount
collateralToLoanSwapRate, // exitPrice (1 / collateralToLoanSwapRate)
currentMargin // currentLeverage
);
} else { // closeType == CloseTypes.Liquidation
emit Liquidate(
loanLocal.borrower, // user (borrower)
msg.sender, // liquidator
loanLocal.id, // loanId
loanLocal.lender, // lender
loanParamsLocal.loanToken, // loanToken
loanParamsLocal.collateralToken, // collateralToken
loanCloseAmount, // loanCloseAmount
collateralCloseAmount, // collateralCloseAmount
collateralToLoanRate, // collateralToLoanRate
currentMargin // currentMargin
);
}
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
import "Constants.sol";
import "Objects.sol";
import "EnumerableBytes32Set.sol";
import "ReentrancyGuard.sol";
import "InterestOracle.sol";
import "Ownable.sol";
import "SafeMath.sol";
contract State is Constants, Objects, ReentrancyGuard, Ownable {
using SafeMath for uint256;
using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;
address public priceFeeds; // handles asset reference price lookups
address public swapsImpl; // handles asset swaps using dex liquidity
mapping (bytes4 => address) public logicTargets; // implementations of protocol functions
mapping (bytes32 => Loan) public loans; // loanId => Loan
mapping (bytes32 => LoanParams) public loanParams; // loanParamsId => LoanParams
mapping (address => mapping (bytes32 => Order)) public lenderOrders; // lender => orderParamsId => Order
mapping (address => mapping (bytes32 => Order)) public borrowerOrders; // borrower => orderParamsId => Order
mapping (bytes32 => mapping (address => bool)) public delegatedManagers; // loanId => delegated => approved
// Interest
mapping (address => mapping (address => LenderInterest)) public lenderInterest; // lender => loanToken => LenderInterest object (depreciated)
mapping (bytes32 => LoanInterest) public loanInterest; // loanId => LoanInterest object (depreciated)
// Internals
EnumerableBytes32Set.Bytes32Set internal logicTargetsSet; // implementations set
EnumerableBytes32Set.Bytes32Set internal activeLoansSet; // active loans set
mapping (address => EnumerableBytes32Set.Bytes32Set) internal lenderLoanSets; // lender loans set
mapping (address => EnumerableBytes32Set.Bytes32Set) internal borrowerLoanSets; // borrow loans set
mapping (address => EnumerableBytes32Set.Bytes32Set) internal userLoanParamSets; // user loan params set
address public feesController; // address controlling fee withdrawals
uint256 public lendingFeePercent = 10 ether; // 10% fee // fee taken from lender interest payments
mapping (address => uint256) public lendingFeeTokensHeld; // total interest fees received and not withdrawn per asset
mapping (address => uint256) public lendingFeeTokensPaid; // total interest fees withdraw per asset (lifetime fees = lendingFeeTokensHeld + lendingFeeTokensPaid)
uint256 public tradingFeePercent = 0.15 ether; // 0.15% fee // fee paid for each trade
mapping (address => uint256) public tradingFeeTokensHeld; // total trading fees received and not withdrawn per asset
mapping (address => uint256) public tradingFeeTokensPaid; // total trading fees withdraw per asset (lifetime fees = tradingFeeTokensHeld + tradingFeeTokensPaid)
uint256 public borrowingFeePercent = 0.09 ether; // 0.09% fee // origination fee paid for each loan
mapping (address => uint256) public borrowingFeeTokensHeld; // total borrowing fees received and not withdrawn per asset
mapping (address => uint256) public borrowingFeeTokensPaid; // total borrowing fees withdraw per asset (lifetime fees = borrowingFeeTokensHeld + borrowingFeeTokensPaid)
uint256 public protocolTokenHeld; // current protocol token deposit balance
uint256 public protocolTokenPaid; // lifetime total payout of protocol token
uint256 public affiliateFeePercent = 30 ether; // 30% fee share // fee share for affiliate program
mapping (address => mapping (address => uint256)) public liquidationIncentivePercent; // percent discount on collateral for liquidators per loanToken and collateralToken
mapping (address => address) public loanPoolToUnderlying; // loanPool => underlying
mapping (address => address) public underlyingToLoanPool; // underlying => loanPool
EnumerableBytes32Set.Bytes32Set internal loanPoolsSet; // loan pools set
mapping (address => bool) public supportedTokens; // supported tokens for swaps
uint256 public maxDisagreement = 5 ether; // % disagreement between swap rate and reference rate
uint256 public sourceBufferPercent = 5 ether; // used to estimate kyber swap source amount
uint256 public maxSwapSize = 1500 ether; // maximum supported swap size in ETH
/**** new interest model start */
mapping(address => uint256) public poolLastUpdateTime; // per itoken
mapping(address => uint256) public poolPrincipalTotal; // per itoken
mapping(address => uint256) public poolInterestTotal; // per itoken
mapping(address => uint256) public poolRatePerTokenStored; // per itoken
mapping(bytes32 => uint256) public loanInterestTotal; // per loan
mapping(bytes32 => uint256) public loanRatePerTokenPaid; // per loan
mapping(address => uint256) internal poolLastInterestRate; // per itoken
mapping(address => InterestOracle.Observation[256]) internal poolInterestRateObservations; // per itoken
mapping(address => uint8) internal poolLastIdx; // per itoken
uint32 public timeDelta;
uint32 public twaiLength;
/**** new interest model end */
function _setTarget(
bytes4 sig,
address target)
internal
{
logicTargets[sig] = target;
if (target != address(0)) {
logicTargetsSet.addBytes32(bytes32(sig));
} else {
logicTargetsSet.removeBytes32(bytes32(sig));
}
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
import "IWethERC20.sol";
contract Constants {
uint256 internal constant WEI_PRECISION = 10**18;
uint256 internal constant WEI_PERCENT_PRECISION = 10**20;
uint256 internal constant DAYS_IN_A_YEAR = 365;
uint256 internal constant ONE_MONTH = 2628000; // approx. seconds in a month
// string internal constant UserRewardsID = "UserRewards"; // decommissioned
string internal constant LoanDepositValueID = "LoanDepositValue";
IWethERC20 public constant wethToken = IWethERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // mainnet
address public constant bzrxTokenAddress = 0x56d811088235F11C8920698a204A5010a788f4b3; // mainnet
address public constant vbzrxTokenAddress = 0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F; // mainnet
address public constant OOKI = address(0x0De05F6447ab4D22c8827449EE4bA2D5C288379B); // mainnet
//IWethERC20 public constant wethToken = IWethERC20(0xd0A1E359811322d97991E03f863a0C30C2cF029C); // kovan
//address public constant bzrxTokenAddress = 0xB54Fc2F2ea17d798Ad5C7Aba2491055BCeb7C6b2; // kovan
//address public constant vbzrxTokenAddress = 0x6F8304039f34fd6A6acDd511988DCf5f62128a32; // kovan
//IWethERC20 public constant wethToken = IWethERC20(0x602C71e4DAC47a042Ee7f46E0aee17F94A3bA0B6); // local testnet only
//address public constant bzrxTokenAddress = 0x3194cBDC3dbcd3E11a07892e7bA5c3394048Cc87; // local testnet only
//address public constant vbzrxTokenAddress = 0xa3B53dDCd2E3fC28e8E130288F2aBD8d5EE37472; // local testnet only
//IWethERC20 public constant wethToken = IWethERC20(0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c); // bsc (Wrapped BNB)
//address public constant bzrxTokenAddress = address(0); // bsc
//address public constant vbzrxTokenAddress = address(0); // bsc
//address public constant OOKI = address(0); // bsc
// IWethERC20 public constant wethToken = IWethERC20(0x0d500B1d8E8eF31E21C99d1Db9A6444d3ADf1270); // polygon (Wrapped MATIC)
// address public constant bzrxTokenAddress = address(0); // polygon
// address public constant vbzrxTokenAddress = address(0); // polygon
// address public constant OOKI = 0xCd150B1F528F326f5194c012f32Eb30135C7C2c9; // polygon
//IWethERC20 public constant wethToken = IWethERC20(0xB31f66AA3C1e785363F0875A1B74E27b85FD66c7); // avax (Wrapped AVAX)
//address public constant bzrxTokenAddress = address(0); // avax
//address public constant vbzrxTokenAddress = address(0); // avax
// IWethERC20 public constant wethToken = IWethERC20(0x82aF49447D8a07e3bd95BD0d56f35241523fBab1); // arbitrum
// address public constant bzrxTokenAddress = address(0); // arbitrum
// address public constant vbzrxTokenAddress = address(0); // arbitrum
// address public constant OOKI = address(0x400F3ff129Bc9C9d239a567EaF5158f1850c65a4); // arbitrum
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity >=0.5.0 <0.6.0;
import "IWeth.sol";
import "IERC20.sol";
contract IWethERC20 is IWeth, IERC20 {}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity >=0.5.0 <0.6.0;
interface IWeth {
function deposit() external payable;
function withdraw(uint256 wad) external;
}
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);
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
import "LoanStruct.sol";
import "LoanParamsStruct.sol";
import "OrderStruct.sol";
import "LenderInterestStruct.sol";
import "LoanInterestStruct.sol";
contract Objects is
LoanStruct,
LoanParamsStruct,
OrderStruct,
LenderInterestStruct,
LoanInterestStruct
{}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
contract LoanStruct {
struct Loan {
bytes32 id; // id of the loan
bytes32 loanParamsId; // the linked loan params id
bytes32 pendingTradesId; // the linked pending trades id
uint256 principal; // total borrowed amount outstanding
uint256 collateral; // total collateral escrowed for the loan
uint256 startTimestamp; // loan start time
uint256 endTimestamp; // for active loans, this is the expected loan end time, for in-active loans, is the actual (past) end time
uint256 startMargin; // initial margin when the loan opened
uint256 startRate; // reference rate when the loan opened for converting collateralToken to loanToken
address borrower; // borrower of this loan
address lender; // lender of this loan
bool active; // if false, the loan has been fully closed
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
contract LoanParamsStruct {
struct LoanParams {
bytes32 id; // id of loan params object
bool active; // if false, this object has been disabled by the owner and can't be used for future loans
address owner; // owner of this object
address loanToken; // the token being loaned
address collateralToken; // the required collateral token
uint256 minInitialMargin; // the minimum allowed initial margin
uint256 maintenanceMargin; // an unhealthy loan when current margin is at or below this value
uint256 maxLoanTerm; // the maximum term for new loans (0 means there's no max term)
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
contract OrderStruct {
struct Order {
uint256 lockedAmount; // escrowed amount waiting for a counterparty
uint256 interestRate; // interest rate defined by the creator of this order
uint256 minLoanTerm; // minimum loan term allowed
uint256 maxLoanTerm; // maximum loan term allowed
uint256 createdTimestamp; // timestamp when this order was created
uint256 expirationTimestamp; // timestamp when this order expires
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
contract LenderInterestStruct {
struct LenderInterest {
uint256 principalTotal; // total borrowed amount outstanding of asset (DEPRECIATED)
uint256 owedPerDay; // interest owed per day for all loans of asset (DEPRECIATED)
uint256 owedTotal; // total interest owed for all loans of asset (DEPRECIATED)
uint256 paidTotal; // total interest paid so far for asset (DEPRECIATED)
uint256 updatedTimestamp; // last update (DEPRECIATED)
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
contract LoanInterestStruct {
struct LoanInterest {
uint256 owedPerDay; // interest owed per day for loan (DEPRECIATED)
uint256 depositTotal; // total escrowed interest for loan (DEPRECIATED)
uint256 updatedTimestamp; // last update (DEPRECIATED)
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
/**
* @dev Library for managing loan sets
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* Include with `using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;`.
*
*/
library EnumerableBytes32Set {
struct Bytes32Set {
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) index;
bytes32[] values;
}
/**
* @dev Add an address value to a set. O(1).
* Returns false if the value was already in the set.
*/
function addAddress(Bytes32Set storage set, address addrvalue)
internal
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return addBytes32(set, value);
}
/**
* @dev Add a value to a set. O(1).
* Returns false if the value was already in the set.
*/
function addBytes32(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
if (!contains(set, value)){
set.index[value] = set.values.push(value);
return true;
} else {
return false;
}
}
/**
* @dev Removes an address value from a set. O(1).
* Returns false if the value was not present in the set.
*/
function removeAddress(Bytes32Set storage set, address addrvalue)
internal
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return removeBytes32(set, value);
}
/**
* @dev Removes a value from a set. O(1).
* Returns false if the value was not present in the set.
*/
function removeBytes32(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
if (contains(set, value)){
uint256 toDeleteIndex = set.index[value] - 1;
uint256 lastIndex = set.values.length - 1;
// If the element we're deleting is the last one, we can just remove it without doing a swap
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set.values[lastIndex];
// Move the last value to the index where the deleted value is
set.values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based
}
// Delete the index entry for the deleted value
delete set.index[value];
// Delete the old entry for the moved value
set.values.pop();
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return set.index[value] != 0;
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function containsAddress(Bytes32Set storage set, address addrvalue)
internal
view
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return set.index[value] != 0;
}
/**
* @dev Returns an array with all values in the set. O(N).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
* WARNING: This function may run out of gas on large sets: use {length} and
* {get} instead in these cases.
*/
function enumerate(Bytes32Set storage set, uint256 start, uint256 count)
internal
view
returns (bytes32[] memory output)
{
uint256 end = start + count;
require(end >= start, "addition overflow");
end = set.values.length < end ? set.values.length : end;
if (end == 0 || start >= end) {
return output;
}
output = new bytes32[](end-start);
for (uint256 i = start; i < end; i++) {
output[i-start] = set.values[i];
}
return output;
}
/**
* @dev Returns the number of elements on the set. O(1).
*/
function length(Bytes32Set storage set)
internal
view
returns (uint256)
{
return set.values.length;
}
/** @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function get(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return set.values[index];
}
/** @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function getAddress(Bytes32Set storage set, uint256 index)
internal
view
returns (address)
{
bytes32 value = set.values[index];
address addrvalue;
assembly {
addrvalue := value
}
return addrvalue;
}
}
pragma solidity >=0.5.0 <0.6.0;
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <[email protected]π.com>, Eenae <[email protected]>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/// @dev Constant for unlocked guard state - non-zero to prevent extra gas costs.
/// See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056
uint256 internal constant REENTRANCY_GUARD_FREE = 1;
/// @dev Constant for locked guard state
uint256 internal constant REENTRANCY_GUARD_LOCKED = 2;
/**
* @dev We use a single lock for the whole contract.
*/
uint256 internal reentrancyLock = REENTRANCY_GUARD_FREE;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one `nonReentrant` function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and an `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(reentrancyLock == REENTRANCY_GUARD_FREE, "nonReentrant");
reentrancyLock = REENTRANCY_GUARD_LOCKED;
_;
reentrancyLock = REENTRANCY_GUARD_FREE;
}
}
pragma solidity ^0.5.0;
library InterestOracle {
struct Observation {
uint32 blockTimestamp;
int56 irCumulative;
int24 tick;
}
/// @param last The specified observation
/// @param blockTimestamp The new timestamp
/// @param tick The active tick
/// @return Observation The newly populated observation
function convert(
Observation memory last,
uint32 blockTimestamp,
int24 tick
) private pure returns (Observation memory) {
return
Observation({
blockTimestamp: blockTimestamp,
irCumulative: last.irCumulative + int56(tick) * (blockTimestamp - last.blockTimestamp),
tick: tick
});
}
/// @param self oracle array
/// @param index most recent observation index
/// @param blockTimestamp timestamp of observation
/// @param tick active tick
/// @param cardinality populated elements
/// @param minDelta minimum time delta between observations
/// @return indexUpdated The new index
function write(
Observation[256] storage self,
uint8 index,
uint32 blockTimestamp,
int24 tick,
uint8 cardinality,
uint32 minDelta
) internal returns (uint8 indexUpdated) {
Observation memory last = self[index];
// early return if we've already written an observation in last minDelta seconds
if (last.blockTimestamp + minDelta >= blockTimestamp) return index;
indexUpdated = (index + 1) % cardinality;
self[indexUpdated] = convert(last, blockTimestamp, tick);
}
/// @param self oracle array
/// @param target targeted timestamp to retrieve value
/// @param index latest index
/// @param cardinality populated elements
function binarySearch(
Observation[256] storage self,
uint32 target,
uint8 index,
uint8 cardinality
) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
uint256 l = (index + 1) % cardinality; // oldest observation
uint256 r = l + cardinality - 1; // newest observation
uint256 i;
while (true) {
i = (l + r) / 2;
beforeOrAt = self[i % cardinality];
if (beforeOrAt.blockTimestamp == 0) {
l = 0;
r = index;
continue;
}
atOrAfter = self[(i + 1) % cardinality];
bool targetAtOrAfter = beforeOrAt.blockTimestamp <= target;
bool targetBeforeOrAt = atOrAfter.blockTimestamp >= target;
if (!targetAtOrAfter) {
r = i - 1;
continue;
} else if (!targetBeforeOrAt) {
l = i + 1;
continue;
}
break;
}
}
/// @param self oracle array
/// @param target targeted timestamp to retrieve value
/// @param tick current tick
/// @param index latest index
/// @param cardinality populated elements
function getSurroundingObservations(
Observation[256] storage self,
uint32 target,
int24 tick,
uint8 index,
uint8 cardinality
) private view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
beforeOrAt = self[index];
if (beforeOrAt.blockTimestamp <= target) {
if (beforeOrAt.blockTimestamp == target) {
return (beforeOrAt, atOrAfter);
} else {
return (beforeOrAt, convert(beforeOrAt, target, tick));
}
}
beforeOrAt = self[(index + 1) % cardinality];
if (beforeOrAt.blockTimestamp == 0) beforeOrAt = self[0];
require(beforeOrAt.blockTimestamp <= target && beforeOrAt.blockTimestamp != 0, "OLD");
return binarySearch(self, target, index, cardinality);
}
/// @param self oracle array
/// @param time current timestamp
/// @param secondsAgo lookback time
/// @param index latest index
/// @param cardinality populated elements
/// @return irCumulative cumulative interest rate, calculated with rate * time
function observeSingle(
Observation[256] storage self,
uint32 time,
uint32 secondsAgo,
int24 tick,
uint8 index,
uint8 cardinality
) internal view returns (int56 irCumulative) {
if (secondsAgo == 0) {
Observation memory last = self[index];
if (last.blockTimestamp != time) {
last = convert(last, time, tick);
}
return last.irCumulative;
}
uint32 target = time - secondsAgo;
(Observation memory beforeOrAt, Observation memory atOrAfter) =
getSurroundingObservations(self, target, tick, index, cardinality);
if (target == beforeOrAt.blockTimestamp) {
// left boundary
return beforeOrAt.irCumulative;
} else if (target == atOrAfter.blockTimestamp) {
// right boundary
return atOrAfter.irCumulative;
} else {
// middle
return
beforeOrAt.irCumulative +
((atOrAfter.irCumulative - beforeOrAt.irCumulative) / (atOrAfter.blockTimestamp - beforeOrAt.blockTimestamp)) *
(target - beforeOrAt.blockTimestamp);
}
}
/// @param self oracle array
/// @param time current timestamp
/// @param secondsAgos lookback time
/// @param index latest index
/// @param cardinality populated elements
/// @return irCumulative cumulative interest rate, calculated with rate * time
function arithmeticMean(
Observation[256] storage self,
uint32 time,
uint32[2] memory secondsAgos,
int24 tick,
uint8 index,
uint8 cardinality
) internal view returns (int24) {
int56 firstPoint = observeSingle(self, time, secondsAgos[1], tick, index, cardinality);
int56 secondPoint = observeSingle(self, time, secondsAgos[0], tick, index, cardinality);
return int24((firstPoint-secondPoint) / (secondsAgos[0]-secondsAgos[1]));
}
}
pragma solidity ^0.5.0;
import "Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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;
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
contract LoanClosingsEvents {
event CloseWithDeposit(
address indexed user,
address indexed lender,
bytes32 indexed loanId,
address closer,
address loanToken,
address collateralToken,
uint256 repayAmount,
uint256 collateralWithdrawAmount,
uint256 collateralToLoanRate,
uint256 currentMargin
);
event CloseWithSwap(
address indexed user,
address indexed lender,
bytes32 indexed loanId,
address collateralToken,
address loanToken,
address closer,
uint256 positionCloseSize,
uint256 loanCloseAmount,
uint256 exitPrice, // one unit of collateralToken, denominated in loanToken
uint256 currentLeverage
);
event Liquidate(
address indexed user,
address indexed liquidator,
bytes32 indexed loanId,
address lender,
address loanToken,
address collateralToken,
uint256 repayAmount,
uint256 collateralWithdrawAmount,
uint256 collateralToLoanRate,
uint256 currentMargin
);
// DEPRECATED
event Rollover(
address indexed user,
address indexed caller,
bytes32 indexed loanId,
address lender,
address loanToken,
address collateralToken,
uint256 collateralAmountUsed,
uint256 interestAmountAdded,
uint256 loanEndTimestamp,
uint256 gasRebate
);
event LoanDeposit(
bytes32 indexed loanId,
uint256 depositValueAsLoanToken,
uint256 depositValueAsCollateralToken
);
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
import "Constants.sol";
import "SafeERC20.sol";
contract VaultController is Constants {
using SafeERC20 for IERC20;
event VaultDeposit(
address indexed asset,
address indexed from,
uint256 amount
);
event VaultWithdraw(
address indexed asset,
address indexed to,
uint256 amount
);
function vaultEtherDeposit(
address from,
uint256 value)
internal
{
IWethERC20 _wethToken = wethToken;
_wethToken.deposit.value(value)();
emit VaultDeposit(
address(_wethToken),
from,
value
);
}
function vaultEtherWithdraw(
address to,
uint256 value)
internal
{
if (value != 0) {
IWethERC20 _wethToken = wethToken;
uint256 balance = address(this).balance;
if (value > balance) {
_wethToken.withdraw(value - balance);
}
Address.sendValue(address(uint160(to)), value);
emit VaultWithdraw(
address(_wethToken),
to,
value
);
}
}
function vaultDeposit(
address token,
address from,
uint256 value)
internal
{
if (value != 0) {
IERC20(token).safeTransferFrom(
from,
address(this),
value
);
emit VaultDeposit(
token,
from,
value
);
}
}
function vaultWithdraw(
address token,
address to,
uint256 value)
internal
{
if (value != 0) {
IERC20(token).safeTransfer(
to,
value
);
emit VaultWithdraw(
token,
to,
value
);
}
}
function vaultTransfer(
address token,
address from,
address to,
uint256 value)
internal
{
if (value != 0) {
if (from == address(this)) {
IERC20(token).safeTransfer(
to,
value
);
} else {
IERC20(token).safeTransferFrom(
from,
to,
value
);
}
}
}
function vaultApprove(
address token,
address to,
uint256 value)
internal
{
if (value != 0 && IERC20(token).allowance(address(this), to) != 0) {
IERC20(token).safeApprove(to, 0);
}
IERC20(token).safeApprove(to, value);
}
}
pragma solidity ^0.5.0;
import "IERC20.sol";
import "SafeMath.sol";
import "Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for 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.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");
}
}
/**
* Copyright 2017-2021, bZxDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
import "State.sol";
import "ILoanPool.sol";
import "MathUtil.sol";
import "InterestRateEvents.sol";
import "InterestOracle.sol";
import "TickMathV1.sol";
contract InterestHandler is State, InterestRateEvents {
using MathUtil for uint256;
using InterestOracle for InterestOracle.Observation[256];
// returns up to date loan interest or 0 if not applicable
function _settleInterest(
address pool,
bytes32 loanId)
internal
returns (uint256 _loanInterestTotal)
{
poolLastIdx[pool] = poolInterestRateObservations[pool].write(
poolLastIdx[pool],
uint32(block.timestamp),
TickMathV1.getTickAtSqrtRatio(uint160(poolLastInterestRate[pool])),
uint8(-1),
timeDelta
);
uint256[7] memory interestVals = _settleInterest2(
pool,
loanId,
false
);
poolInterestTotal[pool] = interestVals[1];
poolRatePerTokenStored[pool] = interestVals[2];
if (interestVals[3] != 0) {
poolLastInterestRate[pool] = interestVals[3];
emit PoolInterestRateVals(
pool,
interestVals[0],
interestVals[1],
interestVals[2],
interestVals[3]
);
}
if (loanId != 0) {
_loanInterestTotal = interestVals[5];
loanInterestTotal[loanId] = _loanInterestTotal;
loanRatePerTokenPaid[loanId] = interestVals[6];
emit LoanInterestRateVals(
loanId,
interestVals[4],
interestVals[5],
interestVals[6]
);
}
poolLastUpdateTime[pool] = block.timestamp;
}
function _getPoolPrincipal(
address pool)
internal
view
returns (uint256)
{
uint256[7] memory interestVals = _settleInterest2(
pool,
0,
true
);
return interestVals[0] // _poolPrincipalTotal
.add(interestVals[1]); // _poolInterestTotal
}
function _getLoanPrincipal(
address pool,
bytes32 loanId)
internal
view
returns (uint256)
{
uint256[7] memory interestVals = _settleInterest2(
pool,
loanId,
false
);
return interestVals[4] // _loanPrincipalTotal
.add(interestVals[5]); // _loanInterestTotal
}
function _settleInterest2(
address pool,
bytes32 loanId,
bool includeLendingFee)
internal
view
returns (uint256[7] memory interestVals)
{
/*
uint256[7] ->
0: _poolPrincipalTotal,
1: _poolInterestTotal,
2: _poolRatePerTokenStored,
3: _poolNextInterestRate,
4: _loanPrincipalTotal,
5: _loanInterestTotal,
6: _loanRatePerTokenPaid
*/
interestVals[0] = poolPrincipalTotal[pool]
.add(lenderInterest[pool][loanPoolToUnderlying[pool]].principalTotal); // backwards compatibility
interestVals[1] = poolInterestTotal[pool];
uint256 lendingFee = interestVals[1]
.mul(lendingFeePercent)
.divCeil(WEI_PERCENT_PRECISION);
uint256 _poolVariableRatePerTokenNewAmount;
(_poolVariableRatePerTokenNewAmount, interestVals[3]) = _getRatePerTokenNewAmount(pool, interestVals[0].add(interestVals[1] - lendingFee));
interestVals[1] = interestVals[0]
.mul(_poolVariableRatePerTokenNewAmount)
.div(WEI_PERCENT_PRECISION * WEI_PERCENT_PRECISION)
.add(interestVals[1]);
if (includeLendingFee) {
interestVals[1] -= lendingFee;
}
interestVals[2] = poolRatePerTokenStored[pool]
.add(_poolVariableRatePerTokenNewAmount);
if (loanId != 0 && (interestVals[4] = loans[loanId].principal) != 0) {
interestVals[5] = interestVals[4]
.mul(interestVals[2].sub(loanRatePerTokenPaid[loanId])) // _loanRatePerTokenUnpaid
.div(WEI_PERCENT_PRECISION * WEI_PERCENT_PRECISION)
.add(loanInterestTotal[loanId]);
interestVals[6] = interestVals[2];
}
}
function _getRatePerTokenNewAmount(
address pool,
uint256 poolTotal)
internal
view
returns (uint256 ratePerTokenNewAmount, uint256 nextInterestRate)
{
uint256 timeSinceUpdate = block.timestamp.sub(poolLastUpdateTime[pool]);
uint256 benchmarkRate = TickMathV1.getSqrtRatioAtTick(poolInterestRateObservations[pool].arithmeticMean(
uint32(block.timestamp),
[uint32(timeSinceUpdate+twaiLength), uint32(timeSinceUpdate)],
poolInterestRateObservations[pool][poolLastIdx[pool]].tick,
poolLastIdx[pool],
uint8(-1)
));
if (timeSinceUpdate != 0 &&
(nextInterestRate = ILoanPool(pool)._nextBorrowInterestRate(poolTotal, 0, benchmarkRate)) != 0) {
ratePerTokenNewAmount = timeSinceUpdate
.mul(nextInterestRate) // rate per year
.mul(WEI_PERCENT_PRECISION)
.div(31536000); // seconds in a year
}
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity >=0.5.0 <0.6.0;
interface ILoanPool {
function tokenPrice()
external
view
returns (uint256 price);
function borrowInterestRate()
external
view
returns (uint256);
function _nextBorrowInterestRate(
uint256 totalBorrow,
uint256 newBorrow,
uint256 lastInterestRate)
external
view
returns (uint256 nextRate);
function totalAssetSupply()
external
view
returns (uint256);
function assetBalanceOf(
address _owner)
external
view
returns (uint256);
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity >=0.5.0 <0.8.0;
library MathUtil {
/**
* @dev Integer division of two numbers, rounding up and truncating the quotient
*/
function divCeil(uint256 a, uint256 b) internal pure returns (uint256) {
return divCeil(a, b, "SafeMath: division by zero");
}
/**
* @dev Integer division of two numbers, rounding up and truncating the quotient
*/
function divCeil(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b != 0, errorMessage);
if (a == 0) {
return 0;
}
uint256 c = ((a - 1) / b) + 1;
return c;
}
function min256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a < _b ? _a : _b;
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
contract InterestRateEvents {
event PoolInterestRateVals(
address indexed pool,
uint256 poolPrincipalTotal,
uint256 poolInterestTotal,
uint256 poolRatePerTokenStored,
uint256 poolNextInterestRate
);
event LoanInterestRateVals(
bytes32 indexed loanId,
uint256 loanPrincipalTotal,
uint256 loanInterestTotal,
uint256 loanRatePerTokenPaid
);
}
// 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 TickMathV1 {
/// @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) public 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 = uint256(-1) / 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) public 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;
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
import "State.sol";
import "SafeERC20.sol";
import "ERC20Detailed.sol";
import "IPriceFeeds.sol";
import "VaultController.sol";
import "FeesEvents.sol";
import "MathUtil.sol";
contract FeesHelper is State, VaultController, FeesEvents {
using SafeERC20 for IERC20;
using MathUtil for uint256;
function _adjustForHeldBalance(
uint256 feeAmount,
address user)
internal view
returns (uint256)
{
uint256 balance = ERC20Detailed(OOKI).balanceOf(user);
if (balance > 1e25) {
return feeAmount.mul(4).divCeil(5);
} else if (balance > 1e24) {
return feeAmount.mul(85).divCeil(100);
} else if (balance > 1e23) {
return feeAmount.mul(9).divCeil(10);
} else {
return feeAmount;
}
}
// calculate trading fee
function _getTradingFee(
uint256 feeTokenAmount)
internal
view
returns (uint256)
{
return feeTokenAmount
.mul(tradingFeePercent)
.divCeil(WEI_PERCENT_PRECISION);
}
// calculate trading fee
function _getTradingFeeWithOOKI(
address sourceToken,
uint256 feeTokenAmount)
internal
view
returns (uint256)
{
return IPriceFeeds(priceFeeds)
.queryReturn(
sourceToken,
OOKI,
feeTokenAmount
.mul(tradingFeePercent)
.divCeil(WEI_PERCENT_PRECISION)
);
}
// calculate loan origination fee
function _getBorrowingFee(
uint256 feeTokenAmount)
internal
view
returns (uint256)
{
return feeTokenAmount
.mul(borrowingFeePercent)
.divCeil(WEI_PERCENT_PRECISION);
}
// calculate loan origination fee
function _getBorrowingFeeWithOOKI(
address sourceToken,
uint256 feeTokenAmount)
internal
view
returns (uint256)
{
return IPriceFeeds(priceFeeds)
.queryReturn(
sourceToken,
OOKI,
feeTokenAmount
.mul(borrowingFeePercent)
.divCeil(WEI_PERCENT_PRECISION)
);
}
// calculate lender (interest) fee
function _getLendingFee(
uint256 feeTokenAmount)
internal
view
returns (uint256)
{
return feeTokenAmount
.mul(lendingFeePercent)
.divCeil(WEI_PERCENT_PRECISION);
}
// settle trading fee
function _payTradingFee(
address user,
bytes32 loanId,
address feeToken,
uint256 tradingFee)
internal
{
if (tradingFee != 0) {
tradingFeeTokensHeld[feeToken] = tradingFeeTokensHeld[feeToken]
.add(tradingFee);
emit PayTradingFee(
user,
feeToken,
loanId,
tradingFee
);
}
}
// settle loan origination fee
function _payBorrowingFee(
address user,
bytes32 loanId,
address feeToken,
uint256 borrowingFee)
internal
{
if (borrowingFee != 0) {
borrowingFeeTokensHeld[feeToken] = borrowingFeeTokensHeld[feeToken]
.add(borrowingFee);
emit PayBorrowingFee(
user,
feeToken,
loanId,
borrowingFee
);
}
}
// settle lender (interest) fee
function _payLendingFee(
address lender,
address feeToken,
uint256 lendingFee)
internal
{
if (lendingFee != 0) {
lendingFeeTokensHeld[feeToken] = lendingFeeTokensHeld[feeToken]
.add(lendingFee);
vaultTransfer(
feeToken,
lender,
address(this),
lendingFee
);
emit PayLendingFee(
lender,
feeToken,
lendingFee
);
}
}
}
pragma solidity ^0.5.0;
import "IERC20.sol";
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity >=0.5.0 <0.9.0;
interface IPriceFeeds {
function queryRate(
address sourceToken,
address destToken)
external
view
returns (uint256 rate, uint256 precision);
function queryPrecision(
address sourceToken,
address destToken)
external
view
returns (uint256 precision);
function queryReturn(
address sourceToken,
address destToken,
uint256 sourceAmount)
external
view
returns (uint256 destAmount);
function checkPriceDisagreement(
address sourceToken,
address destToken,
uint256 sourceAmount,
uint256 destAmount,
uint256 maxSlippage)
external
view
returns (uint256 sourceToDestSwapRate);
function amountInEth(
address Token,
uint256 amount)
external
view
returns (uint256 ethAmount);
function getMaxDrawdown(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount,
uint256 maintenanceMargin)
external
view
returns (uint256);
function getCurrentMarginAndCollateralSize(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount)
external
view
returns (uint256 currentMargin, uint256 collateralInEthAmount);
function getCurrentMargin(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount)
external
view
returns (uint256 currentMargin, uint256 collateralToLoanRate);
function shouldLiquidate(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount,
uint256 maintenanceMargin)
external
view
returns (bool);
function getFastGasPrice(
address payToken)
external
view
returns (uint256);
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
contract FeesEvents {
enum FeeType {
Lending,
Trading,
Borrowing,
SettleInterest
}
event PayLendingFee(
address indexed payer,
address indexed token,
uint256 amount
);
event SettleFeeRewardForInterestExpense(
address indexed payer,
address indexed token,
bytes32 indexed loanId,
uint256 amount
);
event PayTradingFee(
address indexed payer,
address indexed token,
bytes32 indexed loanId,
uint256 amount
);
event PayBorrowingFee(
address indexed payer,
address indexed token,
bytes32 indexed loanId,
uint256 amount
);
// DEPRECATED
event EarnReward(
address indexed receiver,
bytes32 indexed loanId,
FeeType indexed feeType,
address token,
uint256 amount
);
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
import "Constants.sol";
import "SafeMath.sol";
contract LiquidationHelper is Constants {
using SafeMath for uint256;
function _getLiquidationAmounts(
uint256 principal,
uint256 collateral,
uint256 currentMargin,
uint256 maintenanceMargin,
uint256 collateralToLoanRate,
uint256 incentivePercent)
internal
pure
returns (uint256 maxLiquidatable, uint256 maxSeizable)
{
if (currentMargin > maintenanceMargin || collateralToLoanRate == 0) {
return (maxLiquidatable, maxSeizable);
} else if (currentMargin <= incentivePercent) {
return (principal, collateral);
}
uint256 desiredMargin = maintenanceMargin.add(5 ether); // 5 percentage points above maintenance
// maxLiquidatable = ((1 + desiredMargin)*principal - collateralToLoanRate*collateral) / (desiredMargin - incentivePercent)
maxLiquidatable = desiredMargin
.add(WEI_PERCENT_PRECISION)
.mul(principal)
.div(WEI_PERCENT_PRECISION);
maxLiquidatable = maxLiquidatable
.sub(
collateral
.mul(collateralToLoanRate)
.div(WEI_PRECISION)
);
maxLiquidatable = maxLiquidatable
.mul(WEI_PERCENT_PRECISION)
.div(
desiredMargin
.sub(incentivePercent)
);
if (maxLiquidatable > principal) {
maxLiquidatable = principal;
}
// maxSeizable = maxLiquidatable * (1 + incentivePercent) / collateralToLoanRate
maxSeizable = maxLiquidatable
.mul(
incentivePercent
.add(WEI_PERCENT_PRECISION)
);
maxSeizable = maxSeizable
.div(collateralToLoanRate)
.div(100);
if (maxSeizable > collateral) {
maxSeizable = collateral;
}
return (maxLiquidatable, maxSeizable);
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
import "State.sol";
import "IPriceFeeds.sol";
import "SwapsEvents.sol";
import "FeesHelper.sol";
import "ISwapsImpl.sol";
import "IDexRecords.sol";
import "Flags.sol";
contract SwapsUser is State, SwapsEvents, FeesHelper, Flags {
function _loanSwap(
bytes32 loanId,
address sourceToken,
address destToken,
address user,
uint256 minSourceTokenAmount,
uint256 maxSourceTokenAmount,
uint256 requiredDestTokenAmount,
bool bypassFee,
bytes memory loanDataBytes
)
internal
returns (
uint256 destTokenAmountReceived,
uint256 sourceTokenAmountUsed,
uint256 sourceToDestSwapRate
)
{
(destTokenAmountReceived, sourceTokenAmountUsed) = _swapsCall(
[
sourceToken,
destToken,
address(this), // receiver
address(this), // returnToSender
user
],
[
minSourceTokenAmount,
maxSourceTokenAmount,
requiredDestTokenAmount
],
loanId,
bypassFee,
loanDataBytes
);
// will revert if swap size too large
_checkSwapSize(sourceToken, sourceTokenAmountUsed);
// will revert if disagreement found
sourceToDestSwapRate = IPriceFeeds(priceFeeds).checkPriceDisagreement(
sourceToken,
destToken,
sourceTokenAmountUsed,
destTokenAmountReceived,
maxDisagreement
);
emit LoanSwap(
loanId,
sourceToken,
destToken,
user,
sourceTokenAmountUsed,
destTokenAmountReceived
);
}
function _swapsCall(
address[5] memory addrs,
uint256[3] memory vals,
bytes32 loanId,
bool miscBool, // bypassFee
bytes memory loanDataBytes
) internal returns (uint256, uint256) {
//addrs[0]: sourceToken
//addrs[1]: destToken
//addrs[2]: receiver
//addrs[3]: returnToSender
//addrs[4]: user
//vals[0]: minSourceTokenAmount
//vals[1]: maxSourceTokenAmount
//vals[2]: requiredDestTokenAmount
require(vals[0] != 0, "sourceAmount == 0");
uint256 destTokenAmountReceived;
uint256 sourceTokenAmountUsed;
uint256 tradingFee;
if (!miscBool) {
// bypassFee
if (vals[2] == 0) {
// condition: vals[0] will always be used as sourceAmount
if (loanDataBytes.length != 0 && abi.decode(loanDataBytes, (uint128)) & PAY_WITH_OOKI_FLAG != 0) {
tradingFee = _getTradingFeeWithOOKI(addrs[0], vals[0]);
if(tradingFee != 0){
if(abi.decode(loanDataBytes, (uint128)) & HOLD_OOKI_FLAG != 0){
tradingFee = _adjustForHeldBalance(tradingFee, addrs[4]);
}
IERC20(OOKI).safeTransferFrom(addrs[4], address(this), tradingFee);
_payTradingFee(
addrs[4], // user
loanId,
OOKI, // sourceToken
tradingFee
);
}
tradingFee = 0;
} else {
tradingFee = _getTradingFee(vals[0]);
if (tradingFee != 0) {
if(loanDataBytes.length != 0 && abi.decode(loanDataBytes, (uint128)) & HOLD_OOKI_FLAG != 0){
tradingFee = _adjustForHeldBalance(tradingFee, addrs[4]);
}
_payTradingFee(
addrs[4], // user
loanId,
addrs[0], // sourceToken
tradingFee
);
vals[0] = vals[0].sub(tradingFee);
}
}
} else {
// condition: unknown sourceAmount will be used
if (loanDataBytes.length != 0 && abi.decode(loanDataBytes, (uint128)) & PAY_WITH_OOKI_FLAG != 0) {
tradingFee = _getTradingFeeWithOOKI(addrs[1], vals[2]);
if(tradingFee != 0){
if(abi.decode(loanDataBytes, (uint128)) & HOLD_OOKI_FLAG != 0){
tradingFee = _adjustForHeldBalance(tradingFee, addrs[4]);
}
IERC20(OOKI).safeTransferFrom(addrs[4], address(this), tradingFee);
_payTradingFee(
addrs[4], // user
loanId,
OOKI, // sourceToken
tradingFee
);
}
tradingFee = 0;
} else {
tradingFee = _getTradingFee(vals[2]);
if (tradingFee != 0) {
if(loanDataBytes.length != 0 && abi.decode(loanDataBytes, (uint128)) & HOLD_OOKI_FLAG != 0){
tradingFee = _adjustForHeldBalance(tradingFee, addrs[4]);
}
vals[2] = vals[2].add(tradingFee);
}
}
}
}
if (vals[1] == 0) {
vals[1] = vals[0];
} else {
require(vals[0] <= vals[1], "min greater than max");
}
bytes memory loanDataBytes;
if (loanDataBytes.length != 0 && abi.decode(loanDataBytes, (uint128)) & DEX_SELECTOR_FLAG != 0) {
(, bytes[] memory payload) = abi.decode(
loanDataBytes,
(uint128, bytes[])
);
loanDataBytes = payload[0];
}
(
destTokenAmountReceived,
sourceTokenAmountUsed
) = _swapsCall_internal(addrs, vals, loanDataBytes);
if (vals[2] == 0) {
// there's no minimum destTokenAmount, but all of vals[0] (minSourceTokenAmount) must be spent, and amount spent can't exceed vals[0]
require(
sourceTokenAmountUsed == vals[0],
"swap too large to fill"
);
if (tradingFee != 0) {
sourceTokenAmountUsed = sourceTokenAmountUsed + tradingFee; // will never overflow
}
} else {
// there's a minimum destTokenAmount required, but sourceTokenAmountUsed won't be greater than vals[1] (maxSourceTokenAmount)
require(sourceTokenAmountUsed <= vals[1], "swap fill too large");
require(
destTokenAmountReceived >= vals[2],
"insufficient swap liquidity"
);
if (tradingFee != 0) {
_payTradingFee(
addrs[4], // user
loanId, // loanId,
addrs[1], // destToken
tradingFee
);
destTokenAmountReceived = destTokenAmountReceived - tradingFee; // will never overflow
}
}
return (destTokenAmountReceived, sourceTokenAmountUsed);
}
function _swapsCall_internal(
address[5] memory addrs,
uint256[3] memory vals,
bytes memory loanDataBytes
)
internal
returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed)
{
bytes memory data;
address swapImplAddress;
bytes memory swapData;
uint256 dexNumber = 1;
if (loanDataBytes.length != 0) {
(dexNumber, swapData) = abi.decode(
loanDataBytes,
(uint256, bytes)
);
}
swapImplAddress = IDexRecords(swapsImpl).retrieveDexAddress(
dexNumber
);
data = abi.encodeWithSelector(
ISwapsImpl(swapImplAddress).dexSwap.selector,
addrs[0], // sourceToken
addrs[1], // destToken
addrs[2], // receiverAddress
addrs[3], // returnToSenderAddress
vals[0], // minSourceTokenAmount
vals[1], // maxSourceTokenAmount
vals[2], // requiredDestTokenAmount
swapData
);
bool success;
(success, data) = swapImplAddress.delegatecall(data);
if (!success) {
assembly {
let ptr := mload(0x40)
let size := returndatasize
returndatacopy(ptr, 0, size)
revert(ptr, size)
}
}
(destTokenAmountReceived, sourceTokenAmountUsed) = abi.decode(
data,
(uint256, uint256)
);
}
function _swapsExpectedReturn(
address trader,
address sourceToken,
address destToken,
uint256 sourceTokenAmount,
bytes memory payload
) internal returns (uint256 expectedReturn) {
uint256 tradingFee = _getTradingFee(sourceTokenAmount);
address swapImplAddress;
bytes memory dataToSend;
uint256 dexNumber = 1;
if (payload.length == 0) {
dataToSend = abi.encode(sourceToken, destToken);
} else {
(uint128 flag, bytes[] memory payloads) = abi.decode(
payload,
(uint128, bytes[])
);
if (flag & HOLD_OOKI_FLAG != 0) {
tradingFee = _adjustForHeldBalance(tradingFee, trader);
}
if (flag & PAY_WITH_OOKI_FLAG != 0) {
tradingFee = 0;
}
if(flag & DEX_SELECTOR_FLAG != 0){
(dexNumber, dataToSend) = abi.decode(payloads[0], (uint256, bytes));
} else {
dataToSend = abi.encode(sourceToken, destToken);
}
}
if (tradingFee != 0) {
sourceTokenAmount = sourceTokenAmount.sub(tradingFee);
}
swapImplAddress = IDexRecords(swapsImpl).retrieveDexAddress(
dexNumber
);
(expectedReturn, ) = ISwapsImpl(swapImplAddress).dexAmountOutFormatted(
dataToSend,
sourceTokenAmount
);
}
function _checkSwapSize(address tokenAddress, uint256 amount)
internal
view
{
uint256 _maxSwapSize = maxSwapSize;
if (_maxSwapSize != 0) {
uint256 amountInEth;
if (tokenAddress == address(wethToken)) {
amountInEth = amount;
} else {
amountInEth = IPriceFeeds(priceFeeds).amountInEth(
tokenAddress,
amount
);
}
require(amountInEth <= _maxSwapSize, "swap too large");
}
}
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
contract SwapsEvents {
event LoanSwap(
bytes32 indexed loanId,
address indexed sourceToken,
address indexed destToken,
address borrower,
uint256 sourceAmount,
uint256 destAmount
);
event ExternalSwap(
address indexed user,
address indexed sourceToken,
address indexed destToken,
uint256 sourceAmount,
uint256 destAmount
);
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity >=0.5.17;
interface ISwapsImpl {
function dexSwap(
address sourceTokenAddress,
address destTokenAddress,
address receiverAddress,
address returnToSenderAddress,
uint256 minSourceTokenAmount,
uint256 maxSourceTokenAmount,
uint256 requiredDestTokenAmount,
bytes calldata payload
)
external
returns (
uint256 destTokenAmountReceived,
uint256 sourceTokenAmountUsed
);
function dexExpectedRate(
address sourceTokenAddress,
address destTokenAddress,
uint256 sourceTokenAmount
) external view returns (uint256);
function dexAmountOut(bytes calldata route, uint256 amountIn)
external
returns (uint256 amountOut, address midToken);
function dexAmountOutFormatted(bytes calldata route, uint256 amountOut)
external
returns (uint256 amountIn, address midToken);
function dexAmountIn(bytes calldata route, uint256 amountOut)
external
returns (uint256 amountIn, address midToken);
function dexAmountInFormatted(bytes calldata route, uint256 amountOut)
external
returns (uint256 amountIn, address midToken);
function setSwapApprovals(address[] calldata tokens) external;
function revokeApprovals(address[] calldata tokens) external;
}
pragma solidity >=0.5.17;
interface IDexRecords {
function retrieveDexAddress(uint256 dexNumber)
external
view
returns (address);
function setDexID(address dexAddress) external;
function setDexID(uint256 dexID, address dexAddress) external;
function getDexCount() external view returns(uint256);
}
pragma solidity >=0.5.17 <0.9.0;
contract Flags {
uint128 public constant DEX_SELECTOR_FLAG = 2; // base-2: 10
uint128 public constant DELEGATE_FLAG = 4;
uint128 public constant PAY_WITH_OOKI_FLAG = 8;
uint128 public constant HOLD_OOKI_FLAG = 1;
}
/**
* Copyright 2017-2022, OokiDao. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
import "Ownable.sol";
contract PausableGuardian is Ownable {
// keccak256("Pausable_FunctionPause")
bytes32 internal constant Pausable_FunctionPause = 0xa7143c84d793a15503da6f19bf9119a2dac94448ca45d77c8bf08f57b2e91047;
// keccak256("Pausable_GuardianAddress")
bytes32 internal constant Pausable_GuardianAddress = 0x80e6706973d0c59541550537fd6a33b971efad732635e6c3b99fb01006803cdf;
modifier pausable {
require(!_isPaused(msg.sig), "paused");
_;
}
modifier onlyGuardian {
require(msg.sender == getGuardian() || msg.sender == owner(), "unauthorized");
_;
}
function _isPaused(bytes4 sig) public view returns (bool isPaused) {
bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause));
assembly {
isPaused := sload(slot)
}
}
function toggleFunctionPause(bytes4 sig) public onlyGuardian {
bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause));
assembly {
sstore(slot, 1)
}
}
function toggleFunctionUnPause(bytes4 sig) public onlyGuardian {
// only DAO can unpause, and adding guardian temporarily
bytes32 slot = keccak256(abi.encodePacked(sig, Pausable_FunctionPause));
assembly {
sstore(slot, 0)
}
}
function changeGuardian(address newGuardian) public onlyGuardian {
assembly {
sstore(Pausable_GuardianAddress, newGuardian)
}
}
function getGuardian() public view returns (address guardian) {
assembly {
guardian := sload(Pausable_GuardianAddress)
}
}
function pause(bytes4 [] calldata sig)
external
onlyGuardian
{
for(uint256 i = 0; i < sig.length; ++i){
toggleFunctionPause(sig[i]);
}
}
function unpause(bytes4 [] calldata sig)
external
onlyGuardian
{
for(uint256 i = 0; i < sig.length; ++i){
toggleFunctionUnPause(sig[i]);
}
}
} | Repays principal to lender | function _closeWithSwap(
bytes32 loanId,
address receiver,
uint256 swapAmount,
bool returnTokenIsCollateral,
bytes memory loanDataBytes)
internal
pausable
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
)
{
require(swapAmount != 0, "swapAmount == 0");
Loan memory loanLocal = loans[loanId];
_checkAuthorized(
loanLocal.id,
loanLocal.active,
loanLocal.borrower
);
if (receiver == address(0)) {
receiver = msg.sender;
}
LoanParams memory loanParamsLocal = loanParams[loanLocal.loanParamsId];
uint256 principalPlusInterest = _settleInterest(loanLocal.lender, loanId)
.add(loanLocal.principal);
if (swapAmount > loanLocal.collateral) {
swapAmount = loanLocal.collateral;
}
loanCloseAmount = principalPlusInterest;
if (swapAmount != loanLocal.collateral) {
loanCloseAmount = loanCloseAmount
.mul(swapAmount)
.div(loanLocal.collateral);
}
require(loanCloseAmount != 0, "loanCloseAmount == 0");
uint256 usedCollateral;
uint256 collateralToLoanSwapRate;
(usedCollateral, withdrawAmount, collateralToLoanSwapRate) = _coverPrincipalWithSwap(
loanLocal,
loanParamsLocal,
swapAmount,
loanCloseAmount,
returnTokenIsCollateral,
loanDataBytes
);
if (loanCloseAmount != 0) {
vaultWithdraw(
loanParamsLocal.loanToken,
loanLocal.lender,
loanCloseAmount
);
}
if (usedCollateral != 0) {
loanLocal.collateral = loanLocal.collateral
.sub(usedCollateral);
}
withdrawToken = returnTokenIsCollateral ?
loanParamsLocal.collateralToken :
loanParamsLocal.loanToken;
if (withdrawAmount != 0) {
_withdrawAsset(
withdrawToken,
receiver,
withdrawAmount
);
}
_finalizeClose(
loanLocal,
loanParamsLocal,
loanCloseAmount,
usedCollateral,
collateralToLoanSwapRate,
CloseTypes.Swap
);
}
| 6,959,434 |
./full_match/1/0xA90b7861B734784E5eAF87bCD079b1EDfEd24555/sources/contracts/ERC721M.sol | Implementation of minting./ Check stage supply if applicable Check global wallet limit if applicable Check wallet limit for stage if applicable, limit == 0 means no limit enforced Check merkle proof if applicable, merkleRoot == 0x00...00 means no proof required | function _mintInternal(
uint32 qty,
address to,
bytes32[] calldata proof,
uint64 timestamp,
bytes calldata signature
) internal canMint hasSupply(qty) {
uint64 stageTimestamp = uint64(block.timestamp);
MintStageInfo memory stage;
if (_cosigner != address(0)) {
assertValidCosign(msg.sender, qty, timestamp, signature);
_assertValidTimestamp(timestamp);
stageTimestamp = timestamp;
}
uint256 activeStage = getActiveStageFromTimestamp(stageTimestamp);
stage = _mintStages[activeStage];
if (stage.maxStageSupply > 0) {
if (_stageMintedCounts[activeStage] + qty > stage.maxStageSupply)
revert StageSupplyExceeded();
}
if (_globalWalletLimit > 0) {
if (_numberMinted(to) + qty > _globalWalletLimit)
revert WalletGlobalLimitExceeded();
}
if (stage.walletLimit > 0) {
if (
_stageMintedCountsPerWallet[activeStage][to] + qty >
stage.walletLimit
) revert WalletStageLimitExceeded();
}
if (stage.merkleRoot != 0) {
if (
MerkleProof.processProof(
proof,
keccak256(abi.encodePacked(to))
) != stage.merkleRoot
) revert InvalidProof();
}
if (_mintCurrency != address(0)) {
IERC20(_mintCurrency).safeTransferFrom(msg.sender, address(this), stage.price * qty);
}
_stageMintedCountsPerWallet[activeStage][to] += qty;
_stageMintedCounts[activeStage] += qty;
_safeMint(to, qty);
}
| 17,182,152 |
./full_match/1/0x8787ca6A0aFffd8F634D09d7c2eE8D15b326e3f6/sources/src/FeeDistributor.sol | It is required that both the global, token and user state have been properly checkpointed before calling this function./ The first week which cannot be correctly claimed is the earliest of: - A) The global or user time cursor (whichever is earliest), rounded up to the end of the week. - B) The token time cursor, rounded down to the beginning of the week. This prevents the two failure modes: - A) A user may claim a week for which we have not processed their balance, resulting in tokens being locked. - B) A user may claim a week which then receives more tokens to be distributed. However the user has already claimed for that week so their share of these new tokens are lost. We clearly cannot claim for `firstUnclaimableWeek` and so we break here. For a token to be claimable it must have been added to the cached balance so this is safe. | function _claimToken(address user, ERC20 token) internal returns (uint256) {
TokenState storage tokenState = _tokenState[token];
uint256 nextUserTokenWeekToClaim = _getUserTokenTimeCursor(user, token);
uint256 firstUnclaimableWeek = Math.min(
_roundUpTimestamp(
Math.min(_timeCursor, _userState[user].timeCursor)
),
_roundDownTimestamp(tokenState.timeCursor)
);
mapping(uint256 => uint256) storage tokensPerWeek = _tokensPerWeek[
token
];
mapping(uint256 => uint256)
storage userBalanceAtTimestamp = _userBalanceAtTimestamp[user];
uint256 amount;
for (uint256 i = 0; i < 20; ) {
if (nextUserTokenWeekToClaim >= firstUnclaimableWeek) break;
unchecked {
amount +=
(tokensPerWeek[nextUserTokenWeekToClaim] *
userBalanceAtTimestamp[nextUserTokenWeekToClaim]) /
_veSupplyCache[nextUserTokenWeekToClaim];
nextUserTokenWeekToClaim += 1 weeks;
++i;
}
}
if (amount > 0) {
unchecked {
tokenState.cachedBalance = uint128(
tokenState.cachedBalance - amount
);
}
token.safeTransfer(user, amount);
emit TokensClaimed(user, token, amount, nextUserTokenWeekToClaim);
}
return amount;
}
| 2,980,009 |
// File: @openzeppelin/contracts/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 make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. 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/Counters.sol
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File: @openzeppelin/contracts/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/IERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/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: ERC721A.sol
// Creator: Chiru Labs
pragma solidity ^0.8.0;
/**
* @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).
*
* Assumes that an owner cannot have more than the 2**128 (max value of uint128) of supply
*/
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 internal currentIndex = 0;
// 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) internal _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;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @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');
for (uint256 curr = tokenId; ; 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 < 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 > 0, 'ERC721A: quantity must be greater 0');
_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);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
unchecked {
_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);
}
/**
* @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 {}
}
// File: NFT.sol
pragma solidity ^0.8.7;
contract NFT is ERC721A, Ownable, ReentrancyGuard {
using Counters for Counters.Counter;
using SafeMath for uint256;
uint256 private _mintCost;
uint256 private _maxSupply;
bool private _isPublicMintEnabled;
uint256 private _freeSupply;
uint256 private _freeMintLimit;
/**
* @dev Initializes the contract setting the `tokenName` and `symbol` of the nft, `cost` of each mint call, and maximum `supply` of the nft.
* Note: `cost` is in wei.
*/
constructor(string memory tokenName, string memory symbol, uint256 cost, uint256 supply) ERC721A(tokenName, symbol) Ownable() {
_mintCost = cost;
_maxSupply = supply;
_isPublicMintEnabled = false;
_freeSupply = 0;
_freeMintLimit = 1;
}
/**
* @dev Changes contract state to enable public access to `mintTokens` function
* Can only be called by the current owner.
*/
function allowPublicMint()
public
onlyOwner{
_isPublicMintEnabled = true;
}
/**
* @dev Changes contract state to disable public access to `mintTokens` function
* Can only be called by the current owner.
*/
function denyPublicMint()
public
onlyOwner{
_isPublicMintEnabled = false;
}
/**
* @dev Mint `count` tokens if requirements are satisfied.
*
*/
function mintTokens(uint256 count)
public
payable
nonReentrant{
require(_isPublicMintEnabled, "Mint disabled");
require(count > 0 && count <= 100, "You can drop minimum 1, maximum 100 NFTs");
require(count.add(totalSupply()) <= _maxSupply, "Exceeds max supply");
require(owner() == msg.sender || msg.value >= _mintCost.mul(count),
"Ether value sent is below the price");
_mint(msg.sender, count);
}
/**
* @dev Mint a token to each Address of `recipients`.
* Can only be called if requirements are satisfied.
*/
function mintTokens(address[] calldata recipients)
public
payable
nonReentrant{
require(recipients.length>0,"Missing recipient addresses");
require(owner() == msg.sender || _isPublicMintEnabled, "Mint disabled");
require(recipients.length > 0 && recipients.length <= 100, "You can drop minimum 1, maximum 100 NFTs");
require(recipients.length.add(totalSupply()) <= _maxSupply, "Exceeds max supply");
require(owner() == msg.sender || msg.value >= _mintCost.mul(recipients.length),
"Ether value sent is below the price");
for(uint i=0; i<recipients.length; i++){
_mint(recipients[i], 1);
}
}
/**
* @dev Mint `count` tokens if requirements are satisfied.
*/
function freeMint(uint256 count)
public
payable
nonReentrant{
require(owner() == msg.sender || _isPublicMintEnabled, "Mint disabled");
require(totalSupply() + count <= _freeSupply, "Exceed max free supply");
require(count <= _freeMintLimit, "Cant mint more than mint limit");
require(count > 0, "Must mint at least 1 token");
_safeMint(msg.sender, count);
}
/**
* @dev Update the cost to mint a token.
* Can only be called by the current owner.
*/
function setCost(uint256 cost) public onlyOwner{
_mintCost = cost;
}
/**
* @dev Update the max supply.
* Can only be called by the current owner.
*/
function setMaxSupply(uint256 max) public onlyOwner{
_maxSupply = max;
}
/**
* @dev Update the max free supply.
* Can only be called by the current owner.
*/
function setFreeSupply(uint256 max) public onlyOwner{
_freeSupply = max;
}
/**
* @dev Update the free mint transaction limit.
* Can only be called by the current owner.
*/
function setFreeMintLimit(uint256 max) public onlyOwner{
_freeMintLimit = max;
}
/**
* @dev Transfers contract balance to contract owner.
* Can only be called by the current owner.
*/
function withdraw() public onlyOwner{
payable(owner()).transfer(address(this).balance);
}
/**
* @dev Used by public mint functions and by owner functions.
* Can only be called internally by other functions.
*/
function _mint(address to, uint256 count) internal virtual returns (uint256){
_safeMint(to, count);
return count;
}
function getState() public view returns (bool, uint256, uint256, uint256, uint256, uint256){
return (_isPublicMintEnabled, _mintCost, _maxSupply, totalSupply(), _freeSupply, _freeMintLimit);
}
function getCost() public view returns (uint256){
return _mintCost;
}
function getMaxSupply() public view returns (uint256){
return _maxSupply;
}
function getCurrentSupply() public view returns (uint256){
return totalSupply();
}
function getMintStatus() public view returns (bool) {
return _isPublicMintEnabled;
}
function getFreeSupply() public view returns (uint256) {
return _freeSupply;
}
function getFreeMintLimit() public view returns (uint256) {
return _freeMintLimit;
}
function _baseURI() override internal pure returns (string memory) {
return "https://mw9spidhbc.execute-api.us-east-1.amazonaws.com/dev/token/girl-next-door/";
}
function contractURI() public pure returns (string memory) {
return "https://mw9spidhbc.execute-api.us-east-1.amazonaws.com/dev/contract/girl-next-door";
}
} | Initializes the contract setting the `tokenName` and `symbol` of the nft, `cost` of each mint call, and maximum `supply` of the nft. Note: `cost` is in wei./ | function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
}
pragma solidity ^0.8.7;
constructor(string memory tokenName, string memory symbol, uint256 cost, uint256 supply) ERC721A(tokenName, symbol) Ownable() {
_mintCost = cost;
_maxSupply = supply;
_isPublicMintEnabled = false;
_freeSupply = 0;
_freeMintLimit = 1;
}
| 1,200,647 |
/**
*Submitted for verification at Etherscan.io on 2020-03-29
*/
/**
*Submitted for verification at Etherscan.io on 2019-10-18
*/
pragma solidity ^0.5.5;
library strings {
struct slice {
uint _len;
uint _ptr;
}
function memcpy(uint dest, uint src, uint len) private pure {
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask ; //inject UNINIT LOCAL/STATE VAR
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
/*
* @dev Returns a slice containing the entire string.
* @param self The string to make a slice from.
* @return A newly allocated slice containing the entire string.
*/
function toSlice(string memory self) internal pure returns (slice memory) {
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
/*
* @dev Returns the length of a null-terminated bytes32 string.
* @param self The value to find the length of.
* @return The length of the string, from 0 to 32.
*/
function len(bytes32 self) internal pure returns (uint) {
uint ret;
if (self == 0)
return 0;
if (uint(self) & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (uint(self) & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (uint(self) & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (uint(self) & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (uint(self) & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
/*
* @dev Returns a slice containing the entire bytes32, interpreted as a
* null-terminated utf-8 string.
* @param self The bytes32 value to convert to a slice.
* @return A new slice containing the value of the input argument up to the
* first null.
*/
function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = len(self);
}
/*
* @dev Returns a new slice containing the same data as the current slice.
* @param self The slice to copy.
* @return A new slice containing the same data as `self`.
*/
function copy(slice memory self) internal pure returns (slice memory) {
return slice(self._len, self._ptr);
}
/*
* @dev Copies a slice to a new string.
* @param self The slice to copy.
* @return A newly allocated string containing the slice's text.
*/
function toString(slice memory self) internal pure returns (string memory) {
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
return ret;
}
/*
* @dev Returns the length in runes of the slice. Note that this operation
* takes time proportional to the length of the slice; avoid using it
* in loops, and call `slice.empty()` if you only need to know whether
* the slice is empty or not.
* @param self The slice to operate on.
* @return The length of the slice in runes.
*/
function len(slice memory self) internal pure returns (uint l) {
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr ; //inject UNINIT LOCAL/STATE VAR
uint end ; //inject UNINIT LOCAL/STATE VAR
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
/*
* @dev Returns true if the slice is empty (has a length of 0).
* @param self The slice to operate on.
* @return True if the slice is empty, False otherwise.
*/
function empty(slice memory self) internal pure returns (bool) {
return self._len == 0;
}
/*
* @dev Returns a positive number if `other` comes lexicographically after
* `self`, a negative number if it comes before, or zero if the
* contents of the two slices are equal. Comparison is done per-rune,
* on unicode codepoints.
* @param self The first slice to compare.
* @param other The second slice to compare.
* @return The result of the comparison.
*/
function compare(slice memory self, slice memory other) internal pure returns (int) {
uint shortest ; //inject UNINIT LOCAL/STATE VAR
if (other._len < self._len)
shortest = other._len;
uint selfptr ; //inject UNINIT LOCAL/STATE VAR
uint otherptr ; //inject UNINIT LOCAL/STATE VAR
for (uint idx ; idx < shortest; idx += 32) { //inject UNINIT LOCAL/STATE VAR
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask ; // 0xffff... //inject UNINIT LOCAL/STATE VAR
if(shortest < 32) {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint256 diff ; //inject UNINIT LOCAL/STATE VAR
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
/*
* @dev Returns true if the two slices contain the same text.
* @param self The first slice to compare.
* @param self The second slice to compare.
* @return True if the slices are equal, false otherwise.
*/
function equals(slice memory self, slice memory other) internal pure returns (bool) {
return compare(self, other) == 0;
}
/*
* @dev Extracts the first rune in the slice into `rune`, advancing the
* slice to point to the next rune and returning `self`.
* @param self The slice to operate on.
* @param rune The slice that will contain the first rune.
* @return `rune`.
*/
function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if(b < 0xE0) {
l = 2;
} else if(b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
/*
* @dev Returns the first rune in the slice, advancing the slice to point
* to the next rune.
* @param self The slice to operate on.
* @return A slice containing only the first rune from `self`.
*/
function nextRune(slice memory self) internal pure returns (slice memory ret) {
nextRune(self, ret);
}
/*
* @dev Returns the number of the first codepoint in the slice.
* @param self The slice to operate on.
* @return The number of the first codepoint in the slice.
*/
function ord(slice memory self) internal pure returns (uint ret) {
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor ; //inject UNINIT LOCAL/STATE VAR
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b ; //inject UNINIT LOCAL/STATE VAR
if (b < 0x80) {
ret = b;
length = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i ; i < length; i++) { //inject UNINIT LOCAL/STATE VAR
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
/*
* @dev Returns the keccak-256 hash of the slice.
* @param self The slice to hash.
* @return The hash of the slice.
*/
function keccak(slice memory self) internal pure returns (bytes32 ret) {
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
/*
* @dev Returns true if `self` starts with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` starts with `needle`, `needle` is removed from the
* beginning of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
bool equal ; //inject UNINIT LOCAL/STATE VAR
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
/*
* @dev Returns true if the slice ends with `needle`.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return True if the slice starts with the provided text, false otherwise.
*/
function endsWith(slice memory self, slice memory needle) internal pure returns (bool) {
if (self._len < needle._len) {
return false;
}
uint selfptr ; //inject UNINIT LOCAL/STATE VAR
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
/*
* @dev If `self` ends with `needle`, `needle` is removed from the
* end of `self`. Otherwise, `self` is unmodified.
* @param self The slice to operate on.
* @param needle The slice to search for.
* @return `self`
*/
function until(slice memory self, slice memory needle) internal pure returns (slice memory) {
if (self._len < needle._len) {
return self;
}
uint selfptr ; //inject UNINIT LOCAL/STATE VAR
bool equal ; //inject UNINIT LOCAL/STATE VAR
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr ; //inject UNINIT LOCAL/STATE VAR
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask ; //inject UNINIT LOCAL/STATE VAR
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end ; //inject UNINIT LOCAL/STATE VAR
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask ; //inject UNINIT LOCAL/STATE VAR
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
/*
* @dev Modifies `self` to contain everything from the first occurrence of
* `needle` to the end of the slice. `self` is set to the empty slice
* if `needle` is not found.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function find(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr ; //inject UNINIT LOCAL/STATE VAR
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
/*
* @dev Modifies `self` to contain the part of the string from the start of
* `self` to the end of the first occurrence of `needle`. If `needle`
* is not found, `self` is set to the empty slice.
* @param self The slice to search and modify.
* @param needle The text to search for.
* @return `self`.
*/
function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) {
uint ptr ; //inject UNINIT LOCAL/STATE VAR
self._len = ptr - self._ptr;
return self;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and `token` to everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr ; //inject UNINIT LOCAL/STATE VAR
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything after the first
* occurrence of `needle`, and returning everything before it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` up to the first occurrence of `delim`.
*/
function split(slice memory self, slice memory needle) internal pure returns (slice memory token) {
split(self, needle, token);
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and `token` to everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and `token` is set to the entirety of `self`.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @param token An output parameter to which the first token is written.
* @return `token`.
*/
function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {
uint ptr ; //inject UNINIT LOCAL/STATE VAR
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
/*
* @dev Splits the slice, setting `self` to everything before the last
* occurrence of `needle`, and returning everything after it. If
* `needle` does not occur in `self`, `self` is set to the empty slice,
* and the entirety of `self` is returned.
* @param self The slice to split.
* @param needle The text to search for in `self`.
* @return The part of `self` after the last occurrence of `delim`.
*/
function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) {
rsplit(self, needle, token);
}
/*
* @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return The number of occurrences of `needle` found in `self`.
*/
function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {
uint ptr ; //inject UNINIT LOCAL/STATE VAR
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
/*
* @dev Returns True if `self` contains `needle`.
* @param self The slice to search.
* @param needle The text to search for in `self`.
* @return True if `needle` is found in `self`, false otherwise.
*/
function contains(slice memory self, slice memory needle) internal pure returns (bool) {
return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
/*
* @dev Returns a newly allocated string containing the concatenation of
* `self` and `other`.
* @param self The first slice to concatenate.
* @param other The second slice to concatenate.
* @return The concatenation of the two strings.
*/
function concat(slice memory self, slice memory other) internal pure returns (string memory) {
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
memcpy(retptr, self._ptr, self._len);
memcpy(retptr + self._len, other._ptr, other._len);
return ret;
}
/*
* @dev Joins an array of slices, using `self` as a delimiter, returning a
* newly allocated string.
* @param self The delimiter to use.
* @param parts A list of slices to join.
* @return A newly allocated string containing all the slices in `parts`,
* joined with `self`.
*/
function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {
if (parts.length == 0)
return "";
uint length ; //inject UNINIT LOCAL/STATE VAR
for(uint i ; i < parts.length; i++) //inject UNINIT LOCAL/STATE VAR
length += parts[i]._len;
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(uint i ; i < parts.length; i++) { //inject UNINIT LOCAL/STATE VAR
memcpy(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
memcpy(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) public;
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId);
function tokenByIndex(uint256 index) public view returns (uint256);
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
/**
* @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 ; //inject UNINIT LOCAL/STATE VAR
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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c ; //inject UNINIT LOCAL/STATE VAR
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 ; //inject UNINIT LOCAL/STATE VAR
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.
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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 ; //inject UNINIT LOCAL/STATE VAR
// 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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash ; //inject UNINIT LOCAL/STATE VAR
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
}
/**
* @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);
}
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
}
/**
* @dev Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner ; //inject UNINIT LOCAL/STATE VAR
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner ; //inject UNINIT LOCAL/STATE VAR
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner.
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transferFrom(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransferFrom(from, to, tokenId, _data);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal {
_transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner ; //inject UNINIT LOCAL/STATE VAR
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner ; //inject UNINIT LOCAL/STATE VAR
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* This function is deprecated.
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval ; //inject UNINIT LOCAL/STATE VAR
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID.
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Constructor function.
*/
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {ERC721-_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner.
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
return _ownedTokens[owner];
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex ; //inject UNINIT LOCAL/STATE VAR
uint256 tokenIndex ; //inject UNINIT LOCAL/STATE VAR
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId ; //inject UNINIT LOCAL/STATE VAR
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex ; //inject UNINIT LOCAL/STATE VAR
uint256 tokenIndex ; //inject UNINIT LOCAL/STATE VAR
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId ; //inject UNINIT LOCAL/STATE VAR
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender ; //inject UNINIT LOCAL/STATE VAR
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* Modified to remove the mint function and to replace it
* with the _addTokenTo function.
* This function is very similar to the _mint function, but it
* does not emit a Transfer event
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract NoMintERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
}
/**
* @dev Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner ; //inject UNINIT LOCAL/STATE VAR
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner ; //inject UNINIT LOCAL/STATE VAR
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner.
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transferFrom(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransferFrom(from, to, tokenId, _data);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal {
_transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner ; //inject UNINIT LOCAL/STATE VAR
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner ; //inject UNINIT LOCAL/STATE VAR
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _addTokenTo(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* This function is deprecated.
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval ; //inject UNINIT LOCAL/STATE VAR
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID.
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* Modified to work with the NoMintERC721 contract
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract NoMintERC721Enumerable is Context, ERC165, NoMintERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Constructor function.
*/
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _addTokenTo(address to, uint256 tokenId) internal {
super._addTokenTo(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {ERC721-_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner.
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
return _ownedTokens[owner];
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex ; //inject UNINIT LOCAL/STATE VAR
uint256 tokenIndex ; //inject UNINIT LOCAL/STATE VAR
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId ; //inject UNINIT LOCAL/STATE VAR
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex ; //inject UNINIT LOCAL/STATE VAR
uint256 tokenIndex ; //inject UNINIT LOCAL/STATE VAR
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId ; //inject UNINIT LOCAL/STATE VAR
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* Modified to change
* function tokenURI(uint256 tokenId) external view returns (string memory);
* to
* function tokenURI(uint256 tokenId) public view returns (string memory);
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract OveridableERC721Metadata is Context, ERC165, NoMintERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns an URI for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) public view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _tokenURIs[tokenId];
}
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
/**
* ERC-721 implementation that allows
* tokens (of the same category) to be minted in batches. Each batch
* contains enough data to generate all
* token ids inside the batch, and to
* generate the tokenURI in the batch
*/
contract GunToken is NoMintERC721, NoMintERC721Enumerable, OveridableERC721Metadata, Ownable {
using strings for *;
address internal factory;
uint16 public constant maxAllocation = 4000;
uint256 public lastAllocation ; //inject UNINIT LOCAL/STATE VAR
event BatchTransfer(address indexed from, address indexed to, uint256 indexed batchIndex);
struct Batch {
address owner;
uint16 size;
uint8 category;
uint256 startId;
uint256 startTokenId;
}
Batch[] public allBatches;
mapping(address => uint256) unactivatedBalance;
mapping(uint256 => bool) isActivated;
mapping(uint256 => bool) public outOfBatch;
//Used for enumeration
mapping(address => Batch[]) public batchesOwned;
//Batch index to owner batch index
mapping(uint256 => uint256) public ownedBatchIndex;
mapping(uint8 => uint256) internal totalGunsMintedByCategory;
uint256 internal _totalSupply;
modifier onlyFactory {
require(msg.sender == factory, "Not authorized");
_;
}
constructor(address factoryAddress) public OveridableERC721Metadata("WarRiders Gun", "WRG") {
factory = factoryAddress;
}
function categoryTypeToId(uint8 category, uint256 categoryId) public view returns (uint256) {
for (uint i ; i < allBatches.length; i++) { //inject UNINIT LOCAL/STATE VAR
Batch memory a = allBatches[i];
if (a.category != category)
continue;
uint256 endId ; //inject UNINIT LOCAL/STATE VAR
if (categoryId >= a.startId && categoryId < endId) {
uint256 dif ; //inject UNINIT LOCAL/STATE VAR
return a.startTokenId + dif;
}
}
revert();
}
function fallbackCount(address __owner) public view returns (uint256) {
}
function fallbackIndex(address __owner, uint256 index) public view returns (uint256) {
}
function migrate(uint256 count) public onlyOwner returns (uint256) {
//Empty for interface
}
function migrateSingle() public onlyOwner returns (uint256) {
//Empty for interface
}
function recoverBatch2(uint256 index, uint256 tokenStart, uint256 tokenEnd) public onlyOwner {
}
function migrateBatch(uint256 index) public onlyOwner returns (uint256) {
}
function recoverBatch1(uint256 index) public onlyOwner {
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
return tokenOfOwner(owner)[index];
}
function getBatchCount(address owner) public view returns(uint256) {
return batchesOwned[owner].length;
}
function updateGunFactory(address _factory) public onlyOwner {
}
function getTokensInBatch(address owner, uint256 index) public view returns (uint256[] memory) {
Batch memory a = batchesOwned[owner][index];
uint256[] memory result = new uint256[](a.size);
uint256 pos ; //inject UNINIT LOCAL/STATE VAR
uint end ; //inject UNINIT LOCAL/STATE VAR
for (uint i ; i < end; i++) { //inject UNINIT LOCAL/STATE VAR
if (isActivated[i] && super.ownerOf(i) != owner) {
continue;
}
result[pos] = i;
pos++;
}
require(pos > 0);
uint256 subAmount ; //inject UNINIT LOCAL/STATE VAR
assembly { mstore(result, sub(mload(result), subAmount)) }
return result;
}
function tokenByIndex(uint256 index) public view returns (uint256) {
return allTokens()[index];
}
function allTokens() public view returns (uint256[] memory) {
uint256[] memory result = new uint256[](totalSupply());
uint pos ; //inject UNINIT LOCAL/STATE VAR
for (uint i ; i < allBatches.length; i++) { //inject UNINIT LOCAL/STATE VAR
Batch memory a = allBatches[i];
uint end ; //inject UNINIT LOCAL/STATE VAR
for (uint j ; j < end; j++) { //inject UNINIT LOCAL/STATE VAR
result[pos] = j;
pos++;
}
}
return result;
}
function tokenOfOwner(address owner) public view returns (uint256[] memory) {
uint256[] memory result = new uint256[](balanceOf(owner));
uint pos ; //inject UNINIT LOCAL/STATE VAR
for (uint i ; i < batchesOwned[owner].length; i++) { //inject UNINIT LOCAL/STATE VAR
Batch memory a = batchesOwned[owner][i];
uint end ; //inject UNINIT LOCAL/STATE VAR
for (uint j ; j < end; j++) { //inject UNINIT LOCAL/STATE VAR
if (isActivated[j] && super.ownerOf(j) != owner) {
continue;
}
result[pos] = j;
pos++;
}
}
uint256[] memory fallbackOwned = _tokensOfOwner(owner);
for (uint i ; i < fallbackOwned.length; i++) { //inject UNINIT LOCAL/STATE VAR
result[pos] = fallbackOwned[i];
pos++;
}
return result;
}
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return super.balanceOf(owner) + unactivatedBalance[owner];
}
function ownerOf(uint256 tokenId) public view returns (address) {
require(exists(tokenId), "Token doesn't exist!");
if (isActivated[tokenId]) {
return super.ownerOf(tokenId);
}
uint256 index ; //inject UNINIT LOCAL/STATE VAR
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
require(tokenId < a.startTokenId + a.size);
return a.owner;
}
function exists(uint256 _tokenId) public view returns (bool) {
if (isActivated[_tokenId]) {
return super._exists(_tokenId);
} else {
uint256 index ; //inject UNINIT LOCAL/STATE VAR
if (index < allBatches.length) {
Batch memory a = allBatches[index];
uint end ; //inject UNINIT LOCAL/STATE VAR
return _tokenId < end;
}
return false;
}
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function claimAllocation(address to, uint16 size, uint8 category) public onlyFactory returns (uint) {
require(size < maxAllocation, "Size must be smaller than maxAllocation");
allBatches.push(Batch({
owner: to,
size: size,
category: category,
startId: totalGunsMintedByCategory[category],
startTokenId: lastAllocation
}));
uint end ; //inject UNINIT LOCAL/STATE VAR
for (uint i ; i < end; i++) { //inject UNINIT LOCAL/STATE VAR
emit Transfer(address(0), to, i);
}
lastAllocation += maxAllocation;
unactivatedBalance[to] += size;
totalGunsMintedByCategory[category] += size;
_addBatchToOwner(to, allBatches[allBatches.length - 1]);
_totalSupply += size;
return lastAllocation;
}
function transferFrom(address from, address to, uint256 tokenId) public {
if (!isActivated[tokenId]) {
activate(tokenId);
}
super.transferFrom(from, to, tokenId);
}
function activate(uint256 tokenId) public {
require(!isActivated[tokenId], "Token already activated");
uint256 index ; //inject UNINIT LOCAL/STATE VAR
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
require(tokenId < a.startTokenId + a.size);
isActivated[tokenId] = true;
addTokenTo(a.owner, tokenId);
unactivatedBalance[a.owner]--;
}
function getBatchIndex(uint256 tokenId) public pure returns (uint256) {
uint256 index ; //inject UNINIT LOCAL/STATE VAR
return index;
}
function categoryForToken(uint256 tokenId) public view returns (uint8) {
uint256 index ; //inject UNINIT LOCAL/STATE VAR
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
return a.category;
}
function categoryIdForToken(uint256 tokenId) public view returns (uint256) {
uint256 index ; //inject UNINIT LOCAL/STATE VAR
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
uint256 categoryId ; //inject UNINIT LOCAL/STATE VAR
return categoryId;
}
function uintToString(uint v) internal pure returns (string memory) {
if (v == 0) {
return "0";
}
uint j ; //inject UNINIT LOCAL/STATE VAR
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k ; //inject UNINIT LOCAL/STATE VAR
while (v != 0) {
bstr[k--] = byte(uint8(48 + v % 10));
v /= 10;
}
return string(bstr);
}
function tokenURI(uint256 tokenId) public view returns (string memory) {
require(exists(tokenId), "Token doesn't exist!");
if (isActivated[tokenId]) {
return super.tokenURI(tokenId);
} else {
//Predict the token URI
uint8 category ; //inject UNINIT LOCAL/STATE VAR
uint256 _categoryId ; //inject UNINIT LOCAL/STATE VAR
string memory id = uintToString(category).toSlice().concat("/".toSlice()).toSlice().concat(uintToString(_categoryId).toSlice().concat(".json".toSlice()).toSlice());
string memory _base = "https://vault.warriders.com/guns/";
//Final URL: https://vault.warriders.com/guns/<category>/<category_id>.json
string memory _metadata = _base.toSlice().concat(id.toSlice());
return _metadata;
}
}
function addTokenTo(address _to, uint256 _tokenId) internal {
//Predict the token URI
uint8 category ; //inject UNINIT LOCAL/STATE VAR
uint256 _categoryId ; //inject UNINIT LOCAL/STATE VAR
string memory id = uintToString(category).toSlice().concat("/".toSlice()).toSlice().concat(uintToString(_categoryId).toSlice().concat(".json".toSlice()).toSlice());
string memory _base = "https://vault.warriders.com/guns/";
//Final URL: https://vault.warriders.com/guns/<category>/<category_id>.json
string memory _metadata = _base.toSlice().concat(id.toSlice());
super._addTokenTo(_to, _tokenId);
super._setTokenURI(_tokenId, _metadata);
}
function ceil(uint a, uint m) internal pure returns (uint ) {
return ((a + m - 1) / m) * m;
}
function _removeBatchFromOwner(address from, Batch memory batch) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 globalIndex ; //inject UNINIT LOCAL/STATE VAR
uint256 lastBatchIndex ; //inject UNINIT LOCAL/STATE VAR
uint256 batchIndex ; //inject UNINIT LOCAL/STATE VAR
// When the token to delete is the last token, the swap operation is unnecessary
if (batchIndex != lastBatchIndex) {
Batch memory lastBatch = batchesOwned[from][lastBatchIndex];
uint256 lastGlobalIndex ; //inject UNINIT LOCAL/STATE VAR
batchesOwned[from][batchIndex] = lastBatch; // Move the last batch to the slot of the to-delete batch
ownedBatchIndex[lastGlobalIndex] = batchIndex; // Update the moved batch's index
}
// This also deletes the contents at the last position of the array
batchesOwned[from].length--;
// Note that ownedBatchIndex[batch] hasn't been cleared: it still points to the old slot (now occupied by
// lastBatch, or just over the end of the array if the batch was the last one).
}
function _addBatchToOwner(address to, Batch memory batch) private {
uint256 globalIndex ; //inject UNINIT LOCAL/STATE VAR
ownedBatchIndex[globalIndex] = batchesOwned[to].length;
batchesOwned[to].push(batch);
}
function batchTransfer(uint256 batchIndex, address to) public {
Batch storage a = allBatches[batchIndex];
address previousOwner ; //inject UNINIT LOCAL/STATE VAR
require(a.owner == msg.sender);
_removeBatchFromOwner(previousOwner, a);
a.owner = to;
_addBatchToOwner(to, a);
emit BatchTransfer(previousOwner, to, batchIndex);
//Now to need to emit a bunch of transfer events
uint end ; //inject UNINIT LOCAL/STATE VAR
uint256 unActivated ; //inject UNINIT LOCAL/STATE VAR
for (uint i ; i < end; i++) { //inject UNINIT LOCAL/STATE VAR
if (isActivated[i]) {
if (ownerOf(i) != previousOwner)
continue; //The previous owner didn't own this token, don't emit an event
} else {
unActivated++;
}
emit Transfer(previousOwner, to, i);
}
unactivatedBalance[to] += unActivated;
unactivatedBalance[previousOwner] -= unActivated;
}
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public payable returns (bool);
}
/**
* @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);
}
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
);
}
contract BurnableToken is ERC20 {
event Burn(address indexed burner, uint256 value);
function burn(uint256 _value) public;
}
contract StandardBurnableToken is BurnableToken {
function burnFrom(address _from, uint256 _value) public;
}
interface BZNFeed {
/**
* Returns the converted BZN value
*/
function convert(uint256 usd) external view returns (uint256);
}
contract SimpleBZNFeed is BZNFeed, Ownable {
uint256 private conversion;
function updateConversion(uint256 conversionRate) public onlyOwner {
conversion = conversionRate;
}
function convert(uint256 usd) external view returns (uint256) {
return usd * conversion;
}
}
interface IDSValue {
function peek() external view returns (bytes32, bool);
function read() external view returns (bytes32);
function poke(bytes32 wut) external;
function void() external;
}
library BytesLib {
function concat(
bytes memory _preBytes,
bytes memory _postBytes
)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal {
assembly {
// Read the first 32 bytes of _preBytes storage, which is the length
// of the array. (We don't need to use the offset into the slot
// because arrays use the entire slot.)
let fslot := sload(_preBytes_slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
// Since the new array still fits in the slot, we just need to
// update the contents of the slot.
// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
sstore(
_preBytes_slot,
// all the modifications to the slot are inside this
// next block
add(
// we can just add to the slot contents because the
// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memory
mload(add(_postBytes, 0x20)),
// zero all bytes to the right
exp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to
// leave space for the length in the slot
exp(0x100, sub(32, newlength))
),
// increase length by the double of the memory
// bytes length
mul(mlength, 2)
)
)
)
}
case 1 {
// The stored value fits in the slot, but the combined value
// will exceed it.
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into
// the structure. Our first read should obtain the `submod`
// bytes that can fit into the unused space in the last word
// of the stored array. To get this, we read 32 bytes starting
// from `submod`, so the data we read overlaps with the array
// contents by `submod` bytes. Masking the lowest-order
// `submod` bytes allows us to add that value directly to the
// stored value.
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(
fslot,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
// Start copying to the last used word of the stored array.
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in
// case 1 above.
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length));
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {
require(_bytes.length >= (_start + 20));
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) {
require(_bytes.length >= (_start + 1));
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) {
require(_bytes.length >= (_start + 2));
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) {
require(_bytes.length >= (_start + 4));
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) {
require(_bytes.length >= (_start + 8));
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) {
require(_bytes.length >= (_start + 12));
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) {
require(_bytes.length >= (_start + 16));
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) {
require(_bytes.length >= (_start + 32));
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) {
bool success ; //inject UNINIT LOCAL/STATE VAR
assembly {
let length := mload(_preBytes)
// if lengths don't match the arrays are not equal
switch eq(length, mload(_postBytes))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function equalStorage(
bytes storage _preBytes,
bytes memory _postBytes
)
internal
view
returns (bool)
{
bool success ; //inject UNINIT LOCAL/STATE VAR
assembly {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes_slot)
// Decode the length of the stored array like in concatStorage().
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
}
contract GunPreOrder is Ownable, ApproveAndCallFallBack {
using BytesLib for bytes;
using SafeMath for uint256;
//Event for when a bulk buy order has been placed
event consumerBulkBuy(uint8 category, uint256 quanity, address reserver);
//Event for when a gun has been bought
event GunsBought(uint256 gunId, address owner, uint8 category);
//Event for when ether is taken out of this contract
event Withdrawal(uint256 amount);
//Default referal commision percent
uint256 public constant COMMISSION_PERCENT = 5;
//Whether category is open
mapping(uint8 => bool) public categoryExists;
mapping(uint8 => bool) public categoryOpen;
mapping(uint8 => bool) public categoryKilled;
//The additional referal commision percent for any given referal address (default is 0)
mapping(address => uint256) internal commissionRate;
//How many guns in a given category an address has reserved
mapping(uint8 => mapping(address => uint256)) public categoryReserveAmount;
//Opensea buy address
address internal constant OPENSEA = 0x5b3256965e7C3cF26E11FCAf296DfC8807C01073;
//The percent increase and percent base for a given category
mapping(uint8 => uint256) public categoryPercentIncrease;
mapping(uint8 => uint256) public categoryPercentBase;
//Price of a givevn category in USD WEI
mapping(uint8 => uint256) public categoryPrice;
//The percent of ether required for buying in BZN
mapping(uint8 => uint256) public requiredEtherPercent;
mapping(uint8 => uint256) public requiredEtherPercentBase;
bool public allowCreateCategory ; //inject UNINIT LOCAL/STATE VAR
//The gun token contract
GunToken public token;
//The gun factory contract
GunFactory internal factory;
//The BZN contract
StandardBurnableToken internal bzn;
//The Maker ETH/USD price feed
IDSValue public ethFeed;
BZNFeed public bznFeed;
//The gamepool address
address internal gamePool;
//Require the skinned/regular shop to be opened
modifier ensureShopOpen(uint8 category) {
require(categoryExists[category], "Category doesn't exist!");
require(categoryOpen[category], "Category is not open!");
_;
}
//Allow a function to accept ETH payment
modifier payInETH(address referal, uint8 category, address new_owner, uint16 quanity) {
uint256 usdPrice;
uint256 totalPrice;
(usdPrice, totalPrice) = priceFor(category, quanity);
require(usdPrice > 0, "Price not yet set");
categoryPrice[category] = usdPrice; //Save last price
uint256 price ; //inject UNINIT LOCAL/STATE VAR
require(msg.value >= price, "Not enough Ether sent!");
_;
if (msg.value > price) {
uint256 change ; //inject UNINIT LOCAL/STATE VAR
msg.sender.transfer(change);
}
if (referal != address(0)) {
require(referal != msg.sender, "The referal cannot be the sender");
require(referal != tx.origin, "The referal cannot be the tranaction origin");
require(referal != new_owner, "The referal cannot be the new owner");
//The commissionRate map adds any partner bonuses, or 0 if a normal user referral
uint256 totalCommision ; //inject UNINIT LOCAL/STATE VAR
uint256 commision ; //inject UNINIT LOCAL/STATE VAR
address payable _referal ; //inject UNINIT LOCAL/STATE VAR
_referal.transfer(commision);
}
}
//Allow function to accept BZN payment
modifier payInBZN(address referal, uint8 category, address payable new_owner, uint16 quanity) {
uint256[] memory prices = new uint256[](4); //Hack to work around local var limit (usdPrice, bznPrice, commision, totalPrice)
(prices[0], prices[3]) = priceFor(category, quanity);
require(prices[0] > 0, "Price not yet set");
categoryPrice[category] = prices[0];
prices[1] = convert(prices[3], true); //Convert the totalPrice to BZN
//The commissionRate map adds any partner bonuses, or 0 if a normal user referral
if (referal != address(0)) {
prices[2] = (prices[1] * (COMMISSION_PERCENT + commissionRate[referal])) / 100;
}
uint256 requiredEther ; //inject UNINIT LOCAL/STATE VAR
require(msg.value >= requiredEther, "Buying with BZN requires some Ether!");
bzn.burnFrom(new_owner, (((prices[1] - prices[2]) * 30) / 100));
bzn.transferFrom(new_owner, gamePool, prices[1] - prices[2] - (((prices[1] - prices[2]) * 30) / 100));
_;
if (msg.value > requiredEther) {
new_owner.transfer(msg.value - requiredEther);
}
if (referal != address(0)) {
require(referal != msg.sender, "The referal cannot be the sender");
require(referal != tx.origin, "The referal cannot be the tranaction origin");
require(referal != new_owner, "The referal cannot be the new owner");
bzn.transferFrom(new_owner, referal, prices[2]);
prices[2] = (requiredEther * (COMMISSION_PERCENT + commissionRate[referal])) / 100;
address payable _referal ; //inject UNINIT LOCAL/STATE VAR
_referal.transfer(prices[2]);
}
}
//Constructor
constructor(
address tokenAddress,
address tokenFactory,
address gp,
address isd,
address bzn_address
) public {
token = GunToken(tokenAddress);
factory = GunFactory(tokenFactory);
ethFeed = IDSValue(isd);
bzn = StandardBurnableToken(bzn_address);
gamePool = gp;
//Set percent increases
categoryPercentIncrease[1] = 100035;
categoryPercentBase[1] = 100000;
categoryPercentIncrease[2] = 100025;
categoryPercentBase[2] = 100000;
categoryPercentIncrease[3] = 100015;
categoryPercentBase[3] = 100000;
commissionRate[OPENSEA] = 10;
}
function createCategory(uint8 category) public onlyOwner {
require(allowCreateCategory);
categoryExists[category] = true;
}
function disableCreateCategories() public onlyOwner {
allowCreateCategory = false;
}
//Set the referal commision rate for an address
function setCommission(address referral, uint256 percent) public onlyOwner {
require(percent > COMMISSION_PERCENT);
require(percent < 95);
percent = percent - COMMISSION_PERCENT;
commissionRate[referral] = percent;
}
//Set the price increase/base for skinned or regular guns
function setPercentIncrease(uint256 increase, uint256 base, uint8 category) public onlyOwner {
require(increase > base);
categoryPercentIncrease[category] = increase;
categoryPercentBase[category] = base;
}
function setEtherPercent(uint256 percent, uint256 base, uint8 category) public onlyOwner {
requiredEtherPercent[category] = percent;
requiredEtherPercentBase[category] = base;
}
function killCategory(uint8 category) public onlyOwner {
require(!categoryKilled[category]);
categoryOpen[category] = false;
categoryKilled[category] = true;
}
//Open/Close the skinned or regular guns shop
function setShopState(uint8 category, bool open) public onlyOwner {
require(category == 1 || category == 2 || category == 3);
require(!categoryKilled[category]);
require(categoryExists[category]);
categoryOpen[category] = open;
}
/**
* Set the price for any given category in USD.
*/
function setPrice(uint8 category, uint256 price, bool inWei) public onlyOwner {
uint256 multiply ; //inject UNINIT LOCAL/STATE VAR
if (inWei) {
multiply = 1;
}
categoryPrice[category] = price * multiply;
}
/**
Withdraw the amount from the contract's balance. Only the contract owner can execute this function
*/
function withdraw(uint256 amount) public onlyOwner {
uint256 balance ; //inject UNINIT LOCAL/STATE VAR
require(amount <= balance, "Requested to much");
address payable _owner ; //inject UNINIT LOCAL/STATE VAR
_owner.transfer(amount);
emit Withdrawal(amount);
}
function setBZNFeedContract(address new_bzn_feed) public onlyOwner {
bznFeed = BZNFeed(new_bzn_feed);
}
//Buy many skinned or regular guns with BZN. This will reserve the amount of guns and allows the new_owner to invoke claimGuns for free
function buyWithBZN(address referal, uint8 category, address payable new_owner, uint16 quanity) ensureShopOpen(category) payInBZN(referal, category, new_owner, quanity) public payable returns (bool) {
factory.mintFor(new_owner, quanity, category);
return true;
}
//Buy many skinned or regular guns with ETH. This will reserve the amount of guns and allows the new_owner to invoke claimGuns for free
function buyWithEther(address referal, uint8 category, address new_owner, uint16 quanity) ensureShopOpen(category) payInETH(referal, category, new_owner, quanity) public payable returns (bool) {
factory.mintFor(new_owner, quanity, category);
return true;
}
function convert(uint256 usdValue, bool isBZN) public view returns (uint256) {
if (isBZN) {
return bznFeed.convert(usdValue);
} else {
bool temp;
bytes32 aaa;
(aaa, temp) = ethFeed.peek();
uint256 priceForEtherInUsdWei ; //inject UNINIT LOCAL/STATE VAR
return usdValue / (priceForEtherInUsdWei / 1e18);
}
}
/**
Get the price for skinned or regular guns in USD (wei)
*/
function priceFor(uint8 category, uint16 quanity) public view returns (uint256, uint256) {
require(quanity > 0);
uint256 percent ; //inject UNINIT LOCAL/STATE VAR
uint256 base ; //inject UNINIT LOCAL/STATE VAR
uint256 currentPrice ; //inject UNINIT LOCAL/STATE VAR
uint256 nextPrice ; //inject UNINIT LOCAL/STATE VAR
uint256 totalPrice ; //inject UNINIT LOCAL/STATE VAR
//We can't use exponents because we'll overflow quickly
//Only for loop :(
for (uint i ; i < quanity; i++) { //inject UNINIT LOCAL/STATE VAR
nextPrice = (currentPrice * percent) / base;
currentPrice = nextPrice;
totalPrice += nextPrice;
}
//Return the next price, as this is the true price
return (nextPrice, totalPrice);
}
//Determine if a tokenId exists (has been sold)
function sold(uint256 _tokenId) public view returns (bool) {
return token.exists(_tokenId);
}
function receiveApproval(address from, uint256 tokenAmount, address tokenContract, bytes memory data) public payable returns (bool) {
address referal;
uint8 category;
uint16 quanity;
(referal, category, quanity) = abi.decode(data, (address, uint8, uint16));
require(quanity >= 1);
address payable _from ; //inject UNINIT LOCAL/STATE VAR
buyWithBZN(referal, category, _from, quanity);
return true;
}
}
contract GunFactory is Ownable {
using strings for *;
uint8 public constant PREMIUM_CATEGORY = 1;
uint8 public constant MIDGRADE_CATEGORY = 2;
uint8 public constant REGULAR_CATEGORY = 3;
uint256 public constant ONE_MONTH = 2628000;
uint256 public mintedGuns ; //inject UNINIT LOCAL/STATE VAR
address preOrderAddress;
GunToken token;
mapping(uint8 => uint256) internal gunsMintedByCategory;
mapping(uint8 => uint256) internal totalGunsMintedByCategory;
mapping(uint8 => uint256) internal firstMonthLimit;
mapping(uint8 => uint256) internal secondMonthLimit;
mapping(uint8 => uint256) internal thirdMonthLimit;
uint256 internal startTime;
mapping(uint8 => uint256) internal currentMonthEnd;
uint256 internal monthOneEnd;
uint256 internal monthTwoEnd;
modifier onlyPreOrder {
require(msg.sender == preOrderAddress, "Not authorized");
_;
}
modifier isInitialized {
require(preOrderAddress != address(0), "No linked preorder");
require(address(token) != address(0), "No linked token");
_;
}
constructor() public {
firstMonthLimit[PREMIUM_CATEGORY] = 5000;
firstMonthLimit[MIDGRADE_CATEGORY] = 20000;
firstMonthLimit[REGULAR_CATEGORY] = 30000;
secondMonthLimit[PREMIUM_CATEGORY] = 2500;
secondMonthLimit[MIDGRADE_CATEGORY] = 10000;
secondMonthLimit[REGULAR_CATEGORY] = 15000;
thirdMonthLimit[PREMIUM_CATEGORY] = 600;
thirdMonthLimit[MIDGRADE_CATEGORY] = 3000;
thirdMonthLimit[REGULAR_CATEGORY] = 6000;
startTime = block.timestamp;
monthOneEnd = startTime + ONE_MONTH;
monthTwoEnd = startTime + ONE_MONTH + ONE_MONTH;
currentMonthEnd[PREMIUM_CATEGORY] = monthOneEnd;
currentMonthEnd[MIDGRADE_CATEGORY] = monthOneEnd;
currentMonthEnd[REGULAR_CATEGORY] = monthOneEnd;
}
function uintToString(uint v) internal pure returns (string memory) {
if (v == 0) {
return "0";
}
uint j ; //inject UNINIT LOCAL/STATE VAR
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k ; //inject UNINIT LOCAL/STATE VAR
while (v != 0) {
bstr[k--] = byte(uint8(48 + v % 10));
v /= 10;
}
return string(bstr);
}
function mintFor(address newOwner, uint16 size, uint8 category) public onlyPreOrder isInitialized returns (uint256) {
GunPreOrder preOrder ; //inject UNINIT LOCAL/STATE VAR
require(preOrder.categoryExists(category), "Invalid category");
require(!hasReachedLimit(category), "The monthly limit has been reached");
token.claimAllocation(newOwner, size, category);
mintedGuns++;
gunsMintedByCategory[category] = gunsMintedByCategory[category] + 1;
totalGunsMintedByCategory[category] = totalGunsMintedByCategory[category] + 1;
}
function hasReachedLimit(uint8 category) internal returns (bool) {
uint256 currentTime ; //inject UNINIT LOCAL/STATE VAR
uint256 limit ; //inject UNINIT LOCAL/STATE VAR
uint256 monthEnd ; //inject UNINIT LOCAL/STATE VAR
//If the current block time is greater than or equal to the end of the month
if (currentTime >= monthEnd) {
//It's a new month, reset all limits
//gunsMintedByCategory[PREMIUM_CATEGORY] = 0;
//gunsMintedByCategory[MIDGRADE_CATEGORY] = 0;
//gunsMintedByCategory[REGULAR_CATEGORY] = 0;
gunsMintedByCategory[category] = 0;
//Set next month end to be equal one month in advance
//do this while the current time is greater than the next month end
while (currentTime >= monthEnd) {
monthEnd = monthEnd + ONE_MONTH;
}
//Finally, update the limit
limit = currentLimit(category);
currentMonthEnd[category] = monthEnd;
}
//Check if the limit has been reached
return gunsMintedByCategory[category] >= limit;
}
function reachedLimit(uint8 category) public view returns (bool) {
uint256 limit ; //inject UNINIT LOCAL/STATE VAR
return gunsMintedByCategory[category] >= limit;
}
function currentLimit(uint8 category) public view returns (uint256) {
uint256 currentTime ; //inject UNINIT LOCAL/STATE VAR
uint256 limit;
if (currentTime < monthOneEnd) {
limit = firstMonthLimit[category];
} else if (currentTime < monthTwoEnd) {
limit = secondMonthLimit[category];
} else {
limit = thirdMonthLimit[category];
}
return limit;
}
function setCategoryLimit(uint8 category, uint256 firstLimit, uint256 secondLimit, uint256 thirdLimit) public onlyOwner {
require(firstMonthLimit[category] == 0);
require(secondMonthLimit[category] == 0);
require(thirdMonthLimit[category] == 0);
firstMonthLimit[category] = firstLimit;
secondMonthLimit[category] = secondLimit;
thirdMonthLimit[category] = thirdLimit;
}
/**
Attach the preOrder that will be receiving tokens being marked for sale by the
sellCar function
*/
function attachPreOrder(address dst) public onlyOwner {
require(preOrderAddress == address(0));
require(dst != address(0));
//Enforce that address is indeed a preorder
GunPreOrder preOrder ; //inject UNINIT LOCAL/STATE VAR
preOrderAddress = address(preOrder);
}
/**
Attach the token being used for things
*/
function attachToken(address dst) public onlyOwner {
require(address(token) == address(0));
require(dst != address(0));
//Enforce that address is indeed a preorder
GunToken ct ; //inject UNINIT LOCAL/STATE VAR
token = ct;
}
} | Returns true if the two slices contain the same text. self The first slice to compare. self The second slice to compare. return True if the slices are equal, false otherwise./ | function equals(slice memory self, slice memory other) internal pure returns (bool) {
return compare(self, other) == 0;
}
| 13,059,143 |
./partial_match/570/0x2b76AaE10952527b8b34Ead1C1703F53fCfC8B27/sources/contracts/L2/L2ToL1MessagePasser.sol | Sends a message from L2 to L1. _target Address to call on L1 execution. _gasLimit Minimum gas limit for executing the message on L1. _data Data to forward to L1 target. | function initiateWithdrawal(
address _target,
uint256 _gasLimit,
bytes memory _data
) public payable {
bytes32 withdrawalHash = Hashing.hashWithdrawal(
Types.WithdrawalTransaction({
nonce: messageNonce(),
sender: msg.sender,
target: _target,
value: msg.value,
gasLimit: _gasLimit,
data: _data
})
);
sentMessages[withdrawalHash] = true;
emit MessagePassed(
messageNonce(),
msg.sender,
_target,
msg.value,
_gasLimit,
_data,
withdrawalHash
);
unchecked {
++msgNonce;
}
}
| 3,504,322 |
./partial_match/1/0x19B8328F54017a6fA3A277209B7b6C5d2B50A4A2/sources/ACEOwner.sol | Fallback function allows to deposit ether. | function()
external
payable
{
if (msg.value > 0)
emit Deposit(msg.sender, msg.value);
}
public
validRequirement(_owners.length, _required)
| 2,601,935 |
Subsets and Splits