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: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./IBondingCurve.sol";
import "../refs/OracleRef.sol";
import "../pcv/PCVSplitter.sol";
import "../utils/Timed.sol";
/// @title an abstract bonding curve for purchasing RUSD
/// @author Ring Protocol
abstract contract BondingCurve is IBondingCurve, OracleRef, PCVSplitter, Timed {
using Decimal for Decimal.D256;
using SafeMathCopy for uint256;
/// @notice the total amount of RUSD purchased on bonding curve. RUSD_b from the whitepaper
uint256 public override totalPurchased; // RUSD_b for this curve
/// @notice the buffer applied on top of the peg purchase price
uint256 public override buffer = 50;
uint256 public constant BUFFER_GRANULARITY = 10_000;
/// @notice amount of RUSD paid for allocation when incentivized
uint256 public override incentiveAmount;
/// @notice constructor
/// @param _core Ring Core to reference
/// @param _pcvDeposits the PCV Deposits for the PCVSplitter
/// @param _ratios the ratios for the PCVSplitter
/// @param _oracle the UniswapOracle to reference
/// @param _duration the duration between incentivizing allocations
/// @param _incentive the amount rewarded to the caller of an allocation
constructor(
address _core,
address[] memory _pcvDeposits,
uint256[] memory _ratios,
address _oracle,
uint256 _duration,
uint256 _incentive
)
OracleRef(_core, _oracle)
PCVSplitter(_pcvDeposits, _ratios)
Timed(_duration)
{
incentiveAmount = _incentive;
_initTimed();
}
/// @notice sets the bonding curve price buffer
function setBuffer(uint256 _buffer) external override onlyGovernor {
require(
_buffer < BUFFER_GRANULARITY,
"BondingCurve: Buffer exceeds or matches granularity"
);
buffer = _buffer;
emit BufferUpdate(_buffer);
}
/// @notice sets the allocate incentive amount
function setIncentiveAmount(uint256 _incentiveAmount) external override onlyGovernor {
incentiveAmount = _incentiveAmount;
emit IncentiveAmountUpdate(_incentiveAmount);
}
/// @notice sets the allocate incentive frequency
function setIncentiveFrequency(uint256 _frequency) external override onlyGovernor {
_setDuration(_frequency);
}
/// @notice sets the allocation of incoming PCV
function setAllocation(
address[] calldata allocations,
uint256[] calldata ratios
) external override onlyGovernor {
_setAllocation(allocations, ratios);
}
/// @notice batch allocate held PCV
function allocate() external override whenNotPaused {
require((!Address.isContract(msg.sender)), "BondingCurve: Caller is a contract");
uint256 amount = getTotalPCVHeld();
require(amount != 0, "BondingCurve: No PCV held");
_allocate(amount);
_incentivize();
emit Allocate(msg.sender, amount);
}
/// @notice return current instantaneous bonding curve price
/// @return price reported as RUSD per X with X being the underlying asset
function getCurrentPrice()
external
view
override
returns (Decimal.D256 memory)
{
return peg().mul(_getBufferMultiplier());
}
/// @notice return amount of RUSD received after a bonding curve purchase
/// @param amountIn the amount of underlying used to purchase
/// @return amountOut the amount of RUSD received
function getAmountOut(uint256 amountIn)
public
view
override
returns (uint256 amountOut)
{
uint256 adjustedAmount = _getAdjustedAmount(amountIn);
amountOut = _getBufferAdjustedAmount(adjustedAmount);
return amountOut;
}
/// @notice return the average price of a transaction along bonding curve
/// @param amountIn the amount of underlying used to purchase
/// @return price reported as USD per RUSD
function getAverageUSDPrice(uint256 amountIn)
external
view
override
returns (Decimal.D256 memory)
{
uint256 adjustedAmount = _getAdjustedAmount(amountIn);
uint256 amountOut = getAmountOut(amountIn);
return Decimal.ratio(adjustedAmount, amountOut);
}
/// @notice the amount of PCV held in contract and ready to be allocated
function getTotalPCVHeld() public view virtual override returns (uint256);
/// @notice multiplies amount in by the peg to convert to RUSD
function _getAdjustedAmount(uint256 amountIn)
internal
view
returns (uint256)
{
return peg().mul(amountIn).asUint256();
}
/// @notice mint RUSD and send to buyer destination
function _purchase(uint256 amountIn, address to)
internal
returns (uint256 amountOut)
{
amountOut = getAmountOut(amountIn);
_incrementTotalPurchased(amountOut);
rusd().mint(to, amountOut);
emit Purchase(to, amountIn, amountOut);
return amountOut;
}
function _incrementTotalPurchased(uint256 amount) internal {
totalPurchased = totalPurchased.add(amount);
}
/// @notice if window has passed, reward caller and reset window
function _incentivize() internal virtual {
if (isTimeEnded()) {
_initTimed(); // reset window
rusd().mint(msg.sender, incentiveAmount);
}
}
/// @notice returns the buffer on the bonding curve price
function _getBufferMultiplier() internal view returns (Decimal.D256 memory) {
uint256 granularity = BUFFER_GRANULARITY;
// uses granularity - buffer (i.e. 1-b) instead of 1+b because the peg is inverted
return Decimal.ratio(granularity - buffer, granularity);
}
function _getBufferAdjustedAmount(uint256 amountIn)
internal
view
returns (uint256)
{
return _getBufferMultiplier().mul(amountIn).asUint256();
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./BondingCurve.sol";
import "../pcv/IPCVDeposit.sol";
import "@uniswap/lib/contracts/libraries/TransferHelper.sol";
/// @title a square root growth bonding curve for purchasing RUSD with ETH
/// @author Ring Protocol
contract ERC20BondingCurve is BondingCurve {
address public immutable tokenAddress;
constructor(
address core,
address[] memory pcvDeposits,
uint256[] memory ratios,
address oracle,
uint256 duration,
uint256 incentive,
address _tokenAddress
)
BondingCurve(
core,
pcvDeposits,
ratios,
oracle,
duration,
incentive
)
{
tokenAddress = _tokenAddress;
}
/// @notice purchase RUSD for underlying tokens
/// @param to address to receive RUSD
/// @param amountIn amount of underlying tokens input
/// @return amountOut amount of RUSD received
function purchase(address to, uint256 amountIn)
external
payable
virtual
override
whenNotPaused
returns (uint256 amountOut)
{
// safeTransferFrom(address token, address from, address to, uint value)
TransferHelper.safeTransferFrom(tokenAddress, msg.sender, address(this), amountIn);
return _purchase(amountIn, to);
}
function getTotalPCVHeld() public view virtual override returns (uint256) {
return IERC20(tokenAddress).balanceOf(address(this));
}
function _allocateSingle(uint256 amount, address pcvDeposit)
internal
virtual
override
{
// safeTransfer(address token, address to, uint value)
TransferHelper.safeTransfer(tokenAddress, pcvDeposit, amount);
IPCVDeposit(pcvDeposit).deposit();
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../external/Decimal.sol";
interface IBondingCurve {
// ----------- Events -----------
event BufferUpdate(uint256 _buffer);
event IncentiveAmountUpdate(uint256 _incentiveAmount);
event Purchase(address indexed _to, uint256 _amountIn, uint256 _amountOut);
event Allocate(address indexed _caller, uint256 _amount);
// ----------- State changing Api -----------
function purchase(address to, uint256 amountIn)
external
payable
returns (uint256 amountOut);
function allocate() external;
// ----------- Governor only state changing api -----------
function setBuffer(uint256 _buffer) external;
function setAllocation(
address[] calldata pcvDeposits,
uint256[] calldata ratios
) external;
function setIncentiveAmount(uint256 _incentiveAmount) external;
function setIncentiveFrequency(uint256 _frequency) external;
// ----------- Getters -----------
function getCurrentPrice() external view returns (Decimal.D256 memory);
function getAverageUSDPrice(uint256 amountIn)
external
view
returns (Decimal.D256 memory);
function getAmountOut(uint256 amountIn)
external
view
returns (uint256 amountOut);
function buffer() external view returns (uint256);
function totalPurchased() external view returns (uint256);
function getTotalPCVHeld() external view returns (uint256);
function incentiveAmount() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "./IPermissions.sol";
import "../token/IRusd.sol";
/// @title Core Interface
/// @author Ring Protocol
interface ICore is IPermissions {
// ----------- Events -----------
event RusdUpdate(address indexed _rusd);
event RingUpdate(address indexed _ring);
event GenesisGroupUpdate(address indexed _genesisGroup);
event RingAllocation(address indexed _to, uint256 _amount);
event GenesisPeriodComplete(uint256 _timestamp);
// ----------- Governor only state changing api -----------
function init() external;
// ----------- Governor only state changing api -----------
function setRusd(address token) external;
function setRing(address token) external;
function setGenesisGroup(address _genesisGroup) external;
function allocateRing(address to, uint256 amount) external;
// ----------- Genesis Group only state changing api -----------
function completeGenesisGroup() external;
// ----------- Getters -----------
function rusd() external view returns (IRusd);
function ring() external view returns (IERC20);
function genesisGroup() external view returns (address);
function hasGenesisGroupCompleted() external view returns (bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
/// @title Permissions interface
/// @author Ring Protocol
interface IPermissions {
// ----------- Governor only state changing api -----------
function createRole(bytes32 role, bytes32 adminRole) external;
function grantMinter(address minter) external;
function grantBurner(address burner) external;
function grantPCVController(address pcvController) external;
function grantGovernor(address governor) external;
function grantGuardian(address guardian) external;
function revokeMinter(address minter) external;
function revokeBurner(address burner) external;
function revokePCVController(address pcvController) external;
function revokeGovernor(address governor) external;
function revokeGuardian(address guardian) external;
// ----------- Revoker only state changing api -----------
function revokeOverride(bytes32 role, address account) external;
// ----------- Getters -----------
function isBurner(address _address) external view returns (bool);
function isMinter(address _address) external view returns (bool);
function isGovernor(address _address) external view returns (bool);
function isGuardian(address _address) external view returns (bool);
function isPCVController(address _address) external view returns (bool);
}
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020 Empty Set Squad <[email protected]>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./SafeMathCopy.sol";
/**
* @title Decimal
* @author dYdX
*
* Library that defines a fixed-point number with 18 decimal places.
*/
library Decimal {
using SafeMathCopy for uint256;
// ============ Constants ============
uint256 private constant BASE = 10**18;
// ============ Structs ============
struct D256 {
uint256 value;
}
// ============ Static Functions ============
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ Core Methods ============
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
/**
* @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 SafeMathCopy { // To avoid namespace collision between openzeppelin safemath and uniswap 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: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../external/Decimal.sol";
/// @title generic oracle interface for Ring Protocol
/// @author Ring Protocol
interface IOracle {
// ----------- Getters -----------
function read() external view returns (Decimal.D256 memory, bool);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title a PCV Deposit interface
/// @author Ring Protocol
interface IPCVDeposit {
// ----------- Events -----------
event Deposit(address indexed _from, uint256 _amount);
event Collect(address indexed _from, uint256 _amount0, uint256 _amount1);
event Withdrawal(
address indexed _caller,
address indexed _to,
uint256 _amount
);
// ----------- State changing api -----------
function deposit() external payable;
function collect() external returns (uint256 amount0, uint256 amount1);
// ----------- PCV Controller only state changing api -----------
function withdraw(address to, uint256 amount) external;
function burnAndReset(uint24 _fee, int24 _tickLower, int24 _tickUpper) external;
// ----------- Getters -----------
function fee() external view returns (uint24);
function tickLower() external view returns (int24);
function tickUpper() external view returns (int24);
function totalLiquidity() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "../external/SafeMathCopy.sol";
/// @title abstract contract for splitting PCV into different deposits
/// @author Ring Protocol
abstract contract PCVSplitter {
using SafeMathCopy for uint256;
/// @notice total allocation allowed representing 100%
uint256 public constant ALLOCATION_GRANULARITY = 10_000;
uint256[] private ratios;
address[] private pcvDeposits;
event AllocationUpdate(address[] _pcvDeposits, uint256[] _ratios);
/// @notice PCVSplitter constructor
/// @param _pcvDeposits list of PCV Deposits to split to
/// @param _ratios ratios for splitting PCV Deposit allocations
constructor(address[] memory _pcvDeposits, uint256[] memory _ratios) {
_setAllocation(_pcvDeposits, _ratios);
}
/// @notice make sure an allocation has matching lengths and totals the ALLOCATION_GRANULARITY
/// @param _pcvDeposits new list of pcv deposits to send to
/// @param _ratios new ratios corresponding to the PCV deposits
/// @return true if it is a valid allocation
function checkAllocation(
address[] memory _pcvDeposits,
uint256[] memory _ratios
) public pure returns (bool) {
require(
_pcvDeposits.length == _ratios.length,
"PCVSplitter: PCV Deposits and ratios are different lengths"
);
uint256 total;
for (uint256 i; i < _ratios.length; i++) {
total = total.add(_ratios[i]);
}
require(
total == ALLOCATION_GRANULARITY,
"PCVSplitter: ratios do not total 100%"
);
return true;
}
/// @notice gets the pcvDeposits and ratios of the splitter
function getAllocation()
public
view
returns (address[] memory, uint256[] memory)
{
return (pcvDeposits, ratios);
}
/// @notice distribute funds to single PCV deposit
/// @param amount amount of funds to send
/// @param pcvDeposit the pcv deposit to send funds
function _allocateSingle(uint256 amount, address pcvDeposit)
internal
virtual;
/// @notice sets a new allocation for the splitter
/// @param _pcvDeposits new list of pcv deposits to send to
/// @param _ratios new ratios corresponding to the PCV deposits. Must total ALLOCATION_GRANULARITY
function _setAllocation(
address[] memory _pcvDeposits,
uint256[] memory _ratios
) internal {
checkAllocation(_pcvDeposits, _ratios);
pcvDeposits = _pcvDeposits;
ratios = _ratios;
emit AllocationUpdate(_pcvDeposits, _ratios);
}
/// @notice distribute funds to all pcv deposits at specified allocation ratios
/// @param total amount of funds to send
function _allocate(uint256 total) internal {
uint256 granularity = ALLOCATION_GRANULARITY;
for (uint256 i; i < ratios.length; i++) {
uint256 amount = total.mul(ratios[i]) / granularity;
_allocateSingle(amount, pcvDeposits[i]);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./ICoreRef.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
/// @title A Reference to Core
/// @author Ring Protocol
/// @notice defines some modifiers and utilities around interacting with Core
abstract contract CoreRef is ICoreRef, Pausable {
ICore private _core;
/// @notice CoreRef constructor
/// @param newCore Ring Core to reference
constructor(address newCore) {
_core = ICore(newCore);
}
modifier ifMinterSelf() {
if (_core.isMinter(address(this))) {
_;
}
}
modifier ifBurnerSelf() {
if (_core.isBurner(address(this))) {
_;
}
}
modifier onlyMinter() {
require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter");
_;
}
modifier onlyBurner() {
require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner");
_;
}
modifier onlyPCVController() {
require(
_core.isPCVController(msg.sender),
"CoreRef: Caller is not a PCV controller"
);
_;
}
modifier onlyGovernor() {
require(
_core.isGovernor(msg.sender),
"CoreRef: Caller is not a governor"
);
_;
}
modifier onlyGuardianOrGovernor() {
require(
_core.isGovernor(msg.sender) ||
_core.isGuardian(msg.sender),
"CoreRef: Caller is not a guardian or governor"
);
_;
}
modifier onlyRusd() {
require(msg.sender == address(rusd()), "CoreRef: Caller is not RUSD");
_;
}
modifier onlyGenesisGroup() {
require(
msg.sender == _core.genesisGroup(),
"CoreRef: Caller is not GenesisGroup"
);
_;
}
modifier nonContract() {
require(!Address.isContract(msg.sender), "CoreRef: Caller is a contract");
_;
}
/// @notice set new Core reference address
/// @param _newCore the new core address
function setCore(address _newCore) external override onlyGovernor {
_core = ICore(_newCore);
emit CoreUpdate(_newCore);
}
/// @notice set pausable methods to paused
function pause() public override onlyGuardianOrGovernor {
_pause();
}
/// @notice set pausable methods to unpaused
function unpause() public override onlyGuardianOrGovernor {
_unpause();
}
/// @notice address of the Core contract referenced
/// @return ICore implementation address
function core() public view override returns (ICore) {
return _core;
}
/// @notice address of the Rusd contract referenced by Core
/// @return IRusd implementation address
function rusd() public view override returns (IRusd) {
return _core.rusd();
}
/// @notice address of the Ring contract referenced by Core
/// @return IERC20 implementation address
function ring() public view override returns (IERC20) {
return _core.ring();
}
/// @notice rusd balance of contract
/// @return rusd amount held
function rusdBalance() public view override returns (uint256) {
return rusd().balanceOf(address(this));
}
/// @notice ring balance of contract
/// @return ring amount held
function ringBalance() public view override returns (uint256) {
return ring().balanceOf(address(this));
}
function _burnRusdHeld() internal {
rusd().burn(rusdBalance());
}
function _mintRusd(uint256 amount) internal {
rusd().mint(address(this), amount);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../core/ICore.sol";
/// @title CoreRef interface
/// @author Ring Protocol
interface ICoreRef {
// ----------- Events -----------
event CoreUpdate(address indexed _core);
// ----------- Governor only state changing api -----------
function setCore(address _newCore) external;
function pause() external;
function unpause() external;
// ----------- Getters -----------
function core() external view returns (ICore);
function rusd() external view returns (IRusd);
function ring() external view returns (IERC20);
function rusdBalance() external view returns (uint256);
function ringBalance() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
pragma experimental ABIEncoderV2;
import "../oracle/IOracle.sol";
/// @title OracleRef interface
/// @author Ring Protocol
interface IOracleRef {
// ----------- Events -----------
event OracleUpdate(address indexed _oracle);
// ----------- Governor only state changing API -----------
function setOracle(address _oracle) external;
// ----------- Getters -----------
function oracle() external view returns (IOracle);
function peg() external view returns (Decimal.D256 memory);
function invert(Decimal.D256 calldata price)
external
pure
returns (Decimal.D256 memory);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
import "./IOracleRef.sol";
import "./CoreRef.sol";
/// @title Reference to an Oracle
/// @author Ring Protocol
/// @notice defines some utilities around interacting with the referenced oracle
abstract contract OracleRef is IOracleRef, CoreRef {
using Decimal for Decimal.D256;
/// @notice the oracle reference by the contract
IOracle public override oracle;
/// @notice OracleRef constructor
/// @param _core Ring Core to reference
/// @param _oracle oracle to reference
constructor(address _core, address _oracle) CoreRef(_core) {
_setOracle(_oracle);
}
/// @notice sets the referenced oracle
/// @param _oracle the new oracle to reference
function setOracle(address _oracle) external override onlyGovernor {
_setOracle(_oracle);
}
/// @notice invert a peg price
/// @param price the peg price to invert
/// @return the inverted peg as a Decimal
/// @dev the inverted peg would be X per RUSD
function invert(Decimal.D256 memory price)
public
pure
override
returns (Decimal.D256 memory)
{
return Decimal.one().div(price);
}
/// @notice the peg price of the referenced oracle
/// @return the peg as a Decimal
/// @dev the peg is defined as RUSD per X with X being ETH, dollars, etc
function peg() public view override returns (Decimal.D256 memory) {
(Decimal.D256 memory _peg, bool valid) = oracle.read();
require(valid, "OracleRef: oracle invalid");
return _peg;
}
function _setOracle(address _oracle) internal {
oracle = IOracle(_oracle);
emit OracleUpdate(_oracle);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title RUSD stablecoin interface
/// @author Ring Protocol
interface IRusd is IERC20 {
// ----------- Events -----------
event Minting(
address indexed _to,
address indexed _minter,
uint256 _amount
);
event Burning(
address indexed _to,
address indexed _burner,
uint256 _amount
);
event IncentiveContractUpdate(
address indexed _incentiveContract
);
// ----------- State changing api -----------
function burn(uint256 amount) external;
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
// ----------- Burner only state changing api -----------
function burnFrom(address account, uint256 amount) external;
// ----------- Minter only state changing api -----------
function mint(address account, uint256 amount) external;
// ----------- Governor only state changing api -----------
function setIncentiveContract(address incentive) external;
// ----------- Getters -----------
function incentiveContract() external view returns (address);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
/// @title an abstract contract for timed events
/// @author Ring Protocol
abstract contract Timed {
/// @notice the start timestamp of the timed period
uint256 public startTime;
/// @notice the duration of the timed period
uint256 public duration;
event DurationUpdate(uint256 _duration);
event TimerReset(uint256 _startTime);
constructor(uint256 _duration) {
_setDuration(_duration);
}
modifier duringTime() {
require(isTimeStarted(), "Timed: time not started");
require(!isTimeEnded(), "Timed: time ended");
_;
}
modifier afterTime() {
require(isTimeEnded(), "Timed: time not ended");
_;
}
/// @notice return true if time period has ended
function isTimeEnded() public view returns (bool) {
return remainingTime() == 0;
}
/// @notice number of seconds remaining until time is up
/// @return remaining
function remainingTime() public view returns (uint256) {
return duration - timeSinceStart(); // duration always >= timeSinceStart which is on [0,d]
}
/// @notice number of seconds since contract was initialized
/// @return timestamp
/// @dev will be less than or equal to duration
function timeSinceStart() public view returns (uint256) {
if (!isTimeStarted()) {
return 0; // uninitialized
}
uint256 _duration = duration;
// solhint-disable-next-line not-rely-on-time
uint256 timePassed = block.timestamp - startTime; // block timestamp always >= startTime
return timePassed > _duration ? _duration : timePassed;
}
function isTimeStarted() public view returns (bool) {
return startTime != 0;
}
function _initTimed() internal {
// solhint-disable-next-line not-rely-on-time
startTime = block.timestamp;
// solhint-disable-next-line not-rely-on-time
emit TimerReset(block.timestamp);
}
function _setDuration(uint _duration) internal {
duration = _duration;
emit DurationUpdate(_duration);
}
}
// 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.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.6.0;
// 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');
}
}
| distribute funds to all pcv deposits at specified allocation ratios total amount of funds to send | function _allocate(uint256 total) internal {
uint256 granularity = ALLOCATION_GRANULARITY;
for (uint256 i; i < ratios.length; i++) {
uint256 amount = total.mul(ratios[i]) / granularity;
_allocateSingle(amount, pcvDeposits[i]);
}
}
| 1,154,635 |
./full_match/4/0x9CEfeD345D147C2dCbdff3b91a318b1aFC9E5202/sources/KeNFT/KennelFighter.sol | console.log(_tokenURI); | function _createToken(string memory _tokenURI, address _reciever, uint256 _tokenId) private {
_safeMint(_reciever, _tokenId);
_setTokenURI(_tokenId, _tokenURI);
emit NewFighter(fighters[_tokenId]);
}
| 12,473,659 |
// SPDX-License-Identifier: MIT
// File: openzeppelin-solidity/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the 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-solidity/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-solidity/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-solidity/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-solidity/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: openzeppelin-solidity/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-solidity/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-solidity/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-solidity/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-solidity/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (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);
/**
* @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-solidity/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: contracts/ERC721A.sol
// Creator: Chiru Labs
pragma solidity ^0.8.4;
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintedQueryForZeroAddress();
error BurnedQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerIndexOutOfBounds();
error OwnerQueryForNonexistentToken();
error TokenIndexOutOfBounds();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @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..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128).
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
}
// Compiler will pack the following
// _currentIndex and _burnCounter into a single 256bit word.
// The tokenId of the next token to be minted.
uint128 internal _currentIndex;
// The number of tokens burned.
uint128 internal _burnCounter;
// 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) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex times
unchecked {
return _currentIndex - _burnCounter;
}
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
* 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 tokenByIndex(uint256 index) public view override returns (uint256) {
uint256 numMintedSoFar = _currentIndex;
uint256 tokenIdsIdx;
// Counter overflow is impossible as the loop breaks when
// uint256 i is equal to another uint256 numMintedSoFar.
unchecked {
for (uint256 i; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (!ownership.burned) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
}
revert TokenIndexOutOfBounds();
}
/**
* @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) {
if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds();
uint256 numMintedSoFar = _currentIndex;
uint256 tokenIdsIdx;
address currOwnershipAddr;
// Counter overflow is impossible as the loop breaks when
// uint256 i is equal to another uint256 numMintedSoFar.
unchecked {
for (uint256 i; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
}
// Execution should never reach this point.
revert();
}
/**
* @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) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
if (owner == address(0)) revert MintedQueryForZeroAddress();
return uint256(_addressData[owner].numberMinted);
}
function _numberBurned(address owner) internal view returns (uint256) {
if (owner == address(0)) revert BurnedQueryForZeroAddress();
return uint256(_addressData[owner].numberBurned);
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
uint256 curr = tokenId;
unchecked {
if (curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @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) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
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);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
if (operator == _msgSender()) revert ApproveToCaller();
_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 {
_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 {
_transfer(from, to, tokenId);
if (!_checkOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @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 && !_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1
// updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
updatedIndex++;
}
_currentIndex = uint128(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 ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_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.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**128.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = 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)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @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 {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), 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.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**128.
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn 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)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @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 TransferToNonERC721ReceiverImplementer();
} 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.
* And also called before burning one token.
*
* 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`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
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.
* And also called after one token has been burned.
*
* 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` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// File: contracts/SpaceBlazers.sol
pragma solidity ^0.8.4;
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
contract SpaceBlazers is ERC721A, Ownable {
using SafeMath for uint256;
using Strings for uint256;
uint256 public constant MAXASSETS = 3333;
uint256 public constant freeMints = 1700;
uint256 public constant maxFreeMintsPerWallet = 40;
uint256 public reservedAssets = 0;
uint256 public maxPurchase = 20;
uint256 public _price = 0.01 ether;
string public _baseTokenURI;
string public _uriSuffix = ".json";
bool public isSaleActive;
address proxyRegistryAddress;
mapping (uint256 => string) private _tokenURIs;
mapping (address => uint256) private freeMintsWallet;
constructor(string memory baseURI, address _proxyRegistryAddress) ERC721A("Space Blazers", "SBLZR") {
setBaseURI(baseURI);
isSaleActive = false;
proxyRegistryAddress = _proxyRegistryAddress;
}
function mintNFT(uint256 numAssets) external payable {
require(isSaleActive, "Sale is not active!");
require(numAssets >= 0 && numAssets <= maxPurchase,
"You can only mint 20 assets at a time!");
require(totalSupply().add(numAssets) <= MAXASSETS - reservedAssets,
"Not enough assets available...");
if(totalSupply().add(numAssets) > freeMints){
require(msg.value >= _price.mul(numAssets),
"Not enough ETH for this purchase!");
}else{
require(totalSupply().add(numAssets) <= freeMints,
"You would exceed the number of free mints");
require(freeMintsWallet[msg.sender].add(numAssets) <= maxFreeMintsPerWallet,
"You can only mint 40 assets for free!");
freeMintsWallet[msg.sender] += numAssets;
}
_safeMint(msg.sender, numAssets);
}
function assetOfOwner(address _owner) external view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
return new uint256[](0);
} else {
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i = 0; i < tokenCount; i++){
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
}
function setPrice(uint256 newPrice) public onlyOwner {
_price = newPrice;
}
function flipSaleState() public onlyOwner {
isSaleActive = !isSaleActive;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
function setUriSuffix(string memory uriSuffix) public onlyOwner {
_uriSuffix = uriSuffix;
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), _uriSuffix)) : "";
}
function mintNFTS(address _to, uint256 _amount) external onlyOwner() {
require(totalSupply().add(_amount) <= MAXASSETS - reservedAssets,
"Hold up! You would buy more assets than available...");
_safeMint(_to, _amount);
}
function withdrawAll() public onlyOwner {
uint256 balance = address(this).balance;
require(payable(msg.sender).send(balance),
"Withdraw did not work...");
}
function isApprovedForAll(address owner, address operator) override public view returns(bool){
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
function setProxyRegistryAddress(address proxyAddress) external onlyOwner {
proxyRegistryAddress = proxyAddress;
}
} | Whitelist OpenSea proxy contract for easy trading. | function isApprovedForAll(address owner, address operator) override public view returns(bool){
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
| 480,523 |
/**
*Submitted for verification at Etherscan.io on 2021-01-21
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/cryptography/MerkleProof.sol
pragma solidity ^0.6.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// File: contracts/interfaces/IMerkleBox.sol
pragma solidity 0.6.12;
interface IMerkleBox {
event NewMerkle(
address indexed sender,
address indexed erc20,
uint256 amount,
bytes32 indexed merkleRoot,
uint256 claimGroupId,
uint256 withdrawUnlockTime
);
event MerkleClaim(address indexed account, address indexed erc20, uint256 amount);
event MerkleFundUpdate(address indexed funder, bytes32 indexed merkleRoot, uint256 claimGroupId, uint256 amount, bool withdraw);
function addFunds(uint256 claimGroupId, uint256 amount) external;
function addFundsWithPermit(uint256 claimGroupId, address funder, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
function withdrawFunds(uint256 claimGroupId, uint256 amount) external;
function newClaimsGroup(
address erc20,
uint256 amount,
bytes32 merkleRoot,
uint256 withdrawUnlockTime
) external returns (uint256);
function isClaimable(
uint256 claimGroupId,
address account,
uint256 amount,
bytes32[] memory proof
) external view returns (bool);
function claim(
uint256 claimGroupId,
address account,
uint256 amount,
bytes32[] memory proof
) external;
}
// File: contracts/interfaces/IERC20WithPermit.sol
pragma solidity 0.6.12;
interface IERC20WithPermit is IERC20 {
function permit(
address,
address,
uint256,
uint256,
uint8,
bytes32,
bytes32
) external;
}
// File: contracts/MerkleBox.sol
pragma solidity 0.6.12;
contract MerkleBox is IMerkleBox {
using MerkleProof for MerkleProof;
using SafeERC20 for IERC20;
using SafeERC20 for IERC20WithPermit;
using SafeMath for uint256;
struct Holding {
address owner; // account that contributed funds
address erc20; // claim-able ERC20 asset
uint256 balance; // amount of token held currently
bytes32 merkleRoot; // root of claims merkle tree
uint256 withdrawUnlockTime; // withdraw forbidden before this time
}
mapping(uint256 => Holding) public holdings;
mapping(address => uint256[]) public claimGroupIds;
mapping(uint256 => mapping(bytes32 => bool)) public leafClaimed;
uint256 public constant LOCKING_PERIOD = 30 days;
uint256 public claimGroupCount;
function addFunds(uint256 claimGroupId, uint256 amount) external override {
// prelim. parameter checks
require(amount != 0, "Invalid amount");
// reference our struct storage
Holding storage holding = holdings[claimGroupId];
require(holding.owner != address(0), "Holding does not exist");
// calculate amount to deposit. handle deposit-all.
IERC20 token = IERC20(holding.erc20);
uint256 balance = token.balanceOf(msg.sender);
if (amount == uint256(-1)) {
amount = balance;
}
require(amount <= balance, "Insufficient balance");
require(amount != 0, "Amount cannot be zero");
// transfer token to this contract
token.safeTransferFrom(msg.sender, address(this), amount);
// update holdings record
holding.balance = holding.balance.add(amount);
emit MerkleFundUpdate(msg.sender, holding.merkleRoot, claimGroupId, amount, false);
}
function addFundsWithPermit(
uint256 claimGroupId,
address funder,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
// prelim. parameter checks
require(amount != 0, "Invalid amount");
// reference our struct storage
Holding storage holding = holdings[claimGroupId];
require(holding.owner != address(0), "Holding does not exist");
// calculate amount to deposit. handle deposit-all.
IERC20WithPermit token = IERC20WithPermit(holding.erc20);
uint256 balance = token.balanceOf(funder);
if (amount == uint256(-1)) {
amount = balance;
}
require(amount <= balance, "Insufficient balance");
require(amount != 0, "Amount cannot be zero");
// transfer token to this contract
token.permit(funder, address(this), amount, deadline, v, r, s);
token.safeTransferFrom(funder, address(this), amount);
// update holdings record
holding.balance = holding.balance.add(amount);
emit MerkleFundUpdate(funder, holding.merkleRoot, claimGroupId, amount, false);
}
function withdrawFunds(uint256 claimGroupId, uint256 amount) external override {
// reference our struct storage
Holding storage holding = holdings[claimGroupId];
require(holding.owner != address(0), "Holding does not exist");
require(block.timestamp >= holding.withdrawUnlockTime, "Holdings may not be withdrawn");
require(holding.owner == msg.sender, "Only owner may withdraw");
// calculate amount to withdraw. handle withdraw-all.
IERC20 token = IERC20(holding.erc20);
if (amount == uint256(-1)) {
amount = holding.balance;
}
require(amount <= holding.balance, "Insufficient balance");
// update holdings record
holding.balance = holding.balance.sub(amount);
// transfer token to this contract
token.safeTransfer(msg.sender, amount);
emit MerkleFundUpdate(msg.sender, holding.merkleRoot, claimGroupId, amount, true);
}
function newClaimsGroup(
address erc20,
uint256 amount,
bytes32 merkleRoot,
uint256 withdrawUnlockTime
) external override returns (uint256) {
// prelim. parameter checks
require(erc20 != address(0), "Invalid ERC20 address");
require(merkleRoot != 0, "Merkle cannot be zero");
require(withdrawUnlockTime >= block.timestamp + LOCKING_PERIOD, "Holing lock must exceed minimum lock period");
claimGroupCount++;
// reference our struct storage
Holding storage holding = holdings[claimGroupCount];
// calculate amount to deposit. handle deposit-all.
IERC20 token = IERC20(erc20);
uint256 balance = token.balanceOf(msg.sender);
if (amount == uint256(-1)) {
amount = balance;
}
require(amount <= balance, "Insufficient balance");
require(amount != 0, "Amount cannot be zero");
// transfer token to this contract
token.safeTransferFrom(msg.sender, address(this), amount);
// record holding in stable storage
holding.owner = msg.sender;
holding.erc20 = erc20;
holding.balance = amount;
holding.merkleRoot = merkleRoot;
holding.withdrawUnlockTime = withdrawUnlockTime;
claimGroupIds[msg.sender].push(claimGroupCount);
emit NewMerkle(msg.sender, erc20, amount, merkleRoot, claimGroupCount, withdrawUnlockTime);
return claimGroupCount;
}
function isClaimable(
uint256 claimGroupId,
address account,
uint256 amount,
bytes32[] memory proof
) external view override returns (bool) {
// holding exists?
Holding memory holding = holdings[claimGroupId];
if (holding.owner == address(0)) {
return false;
}
// holding owner?
if (holding.owner == account) {
return false;
}
// sufficient balance exists? (funder may have under-funded)
if (holding.balance < amount) {
return false;
}
bytes32 leaf = _leafHash(account, amount);
// already claimed?
if (leafClaimed[claimGroupId][leaf]) {
return false;
}
// merkle proof is invalid or claim not found
if (!MerkleProof.verify(proof, holding.merkleRoot, leaf)) {
return false;
}
return true;
}
function claim(
uint256 claimGroupId,
address account,
uint256 amount,
bytes32[] memory proof
) external override {
// holding exists?
Holding storage holding = holdings[claimGroupId];
require(holding.owner != address(0), "Holding not found");
// holding owner?
require(holding.owner != account, "Holding owner cannot claim");
// sufficient balance exists? (funder may have under-funded)
require(holding.balance >= amount, "Claim under-funded by funder.");
bytes32 leaf = _leafHash(account, amount);
// already spent?
require(leafClaimed[claimGroupId][leaf] == false, "Already claimed");
// merkle proof valid?
require(MerkleProof.verify(proof, holding.merkleRoot, leaf) == true, "Claim not found");
// update state
leafClaimed[claimGroupId][leaf] = true;
holding.balance = holding.balance.sub(amount);
IERC20(holding.erc20).safeTransfer(account, amount);
emit MerkleClaim(account, holding.erc20, amount);
}
function getClaimGroupIds(address owner) public view returns (uint256[] memory ids) {
ids = claimGroupIds[owner];
}
//////////////////////////////////////////////////////////
// generate hash of (claim holder, amount)
// claim holder must be the caller
function _leafHash(address account, uint256 amount) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(account, amount));
}
} | prelim. parameter checks reference our struct storage calculate amount to deposit. handle deposit-all. | function newClaimsGroup(
address erc20,
uint256 amount,
bytes32 merkleRoot,
uint256 withdrawUnlockTime
) external override returns (uint256) {
require(erc20 != address(0), "Invalid ERC20 address");
require(merkleRoot != 0, "Merkle cannot be zero");
require(withdrawUnlockTime >= block.timestamp + LOCKING_PERIOD, "Holing lock must exceed minimum lock period");
claimGroupCount++;
Holding storage holding = holdings[claimGroupCount];
IERC20 token = IERC20(erc20);
uint256 balance = token.balanceOf(msg.sender);
if (amount == uint256(-1)) {
amount = balance;
}
require(amount <= balance, "Insufficient balance");
require(amount != 0, "Amount cannot be zero");
holding.erc20 = erc20;
holding.balance = amount;
holding.merkleRoot = merkleRoot;
holding.withdrawUnlockTime = withdrawUnlockTime;
claimGroupIds[msg.sender].push(claimGroupCount);
emit NewMerkle(msg.sender, erc20, amount, merkleRoot, claimGroupCount, withdrawUnlockTime);
return claimGroupCount;
}
| 10,787,671 |
pragma solidity ^0.5.3;
// import "zos-lib/contracts/Initializable.sol";
import "./lib/MerkleProof.sol";
import "./Identity.sol";
contract AnchorRepository {
event AnchorCommitted(
address indexed from,
uint256 indexed anchorId,
bytes32 documentRoot,
uint32 blockHeight
);
event AnchorPreCommitted(
address indexed from,
uint256 indexed anchorId,
uint32 blockHeight
);
struct PreAnchor {
bytes32 signingRoot;
address identity;
uint32 expirationBlock;
}
struct Anchor {
bytes32 docRoot;
uint32 anchoredBlock;
}
// store precommits
mapping(uint256 => PreAnchor) internal _preCommits;
// store _commits
mapping(uint256 => Anchor) internal _commits;
// The number of blocks for which a precommit is valid
uint256 constant internal EXPIRATION_LENGTH = 480;
/**
* @param anchorId Id for an Anchor.
* @param signingRoot merkle tree for a document that does not contain the signatures
*/
function preCommit(
uint256 anchorId,
bytes32 signingRoot
)
external
{
// do not allow 0x0 signingRoots
require(
signingRoot != 0x0,
"Signing Root can not be 0x0"
);
// not allowing to pre-commit for an existing anchor
require(_commits[anchorId].docRoot == 0x0,"Commit exists for the given anchor");
// do not allow a precommit if there is already a valid one in place
require(hasValidPreCommit(anchorId) == false,"Precommit exists for the given anchor");
_preCommits[anchorId] = PreAnchor(
signingRoot,
msg.sender,
uint32(block.number + EXPIRATION_LENGTH)
);
emit AnchorPreCommitted(
msg.sender,
anchorId,
uint32(block.number)
);
}
/**
* @param anchorIdPreImage pre-image for an AnchorID.
* @param documentRoot merkle tree for a document that will be anchored/commited. It also contains the signatures
* @param proof bytes32 proof for the document's signatures.
* The documentRoot must be a merkle tree constructed from the signingRoot plus all signatures
*/
function commit(
uint256 anchorIdPreImage,
bytes32 documentRoot,
bytes32 proof
)
external
{
// do not allow 0x0 documentRoots
require(
documentRoot != 0x0,
"Document Root can not be 0x0"
);
uint256 anchorId = uint256(sha256(abi.encodePacked(anchorIdPreImage)));
//not allowing to write to an existing anchor
require(_commits[anchorId].docRoot == 0x0);
// Check if there is a precommit and enforce it
if (hasValidPreCommit(anchorId)) {
// check that the precommit has the same _identity
require(_preCommits[anchorId].identity == msg.sender,"Precommit owned by someone else");
require(
MerkleProof.verifySha256(
proof,
documentRoot,
_preCommits[anchorId].signingRoot
),
"Signing root validation failed"
);
}
_commits[anchorId] = Anchor(
documentRoot,
uint32(block.number)
);
emit AnchorCommitted(
msg.sender,
anchorId,
documentRoot,
uint32(block.number)
);
}
/**
* @param id Id for an Anchor.
* @return Struct with anchorId, documentRoot, anchoredBlock
*/
function getAnchorById(uint256 id)
external
view
returns (
uint256 anchorId,
bytes32 documentRoot,
uint32 blockNumber
)
{
return (
id,
_commits[id].docRoot,
_commits[id].anchoredBlock
);
}
/**
* @dev Check if there is a valid precommit for an anchorID
* @param anchorId Id for an Anchor.
* @return true if there is a valid precommit for the provided anchorId
*/
function hasValidPreCommit(uint256 anchorId)
public
view
returns (bool valid)
{
return (
_preCommits[anchorId].expirationBlock > block.number
);
}
}
| anchorIdPreImage pre-image for an AnchorID. documentRoot merkle tree for a document that will be anchored/commited. It also contains the signatures proof bytes32 proof for the document's signatures. The documentRoot must be a merkle tree constructed from the signingRoot plus all signatures/ do not allow 0x0 documentRootsnot allowing to write to an existing anchor Check if there is a precommit and enforce it check that the precommit has the same _identity | function commit(
uint256 anchorIdPreImage,
bytes32 documentRoot,
bytes32 proof
)
external
{
require(
documentRoot != 0x0,
"Document Root can not be 0x0"
);
uint256 anchorId = uint256(sha256(abi.encodePacked(anchorIdPreImage)));
require(_commits[anchorId].docRoot == 0x0);
if (hasValidPreCommit(anchorId)) {
require(_preCommits[anchorId].identity == msg.sender,"Precommit owned by someone else");
require(
MerkleProof.verifySha256(
proof,
documentRoot,
_preCommits[anchorId].signingRoot
),
"Signing root validation failed"
);
}
_commits[anchorId] = Anchor(
documentRoot,
uint32(block.number)
);
emit AnchorCommitted(
msg.sender,
anchorId,
documentRoot,
uint32(block.number)
);
}
| 12,802,730 |
./full_match/43113/0x99fCa0B1D9b982B1cbE001e6F059413Be5920D59/sources/Happy/Happy.sol | mint tokens for nonce, sender, interval and block-hash / do not accept contract addresses to prevent FREN sharing check block-hash to be correct get current interval (in days) get number of FREN owned to use as minting multiplier get FREN total supply calculate nonce-hash of nonce for sender, interval & block-hash calculate amount of tokens for nonce-hash ensure unique nonce-hash (to be used once) mint tokens for minter (i.e. nonce provider) | function mint(uint256 _nonce, bytes32 _blockHash, address _minter) public {
require(!_isContract(_minter));
require(_blockHash == blockHash, "invalid block-hash");
uint256 _interval = interval();
uint256 frensOwned = CryptoFrens.balanceOf(_minter);
uint256 frenSupply = CryptoFrens.totalSupply();
bytes32 nonceHash = _hash(_nonce, _minter, _interval, blockHash);
require(!_hashes.contains(uint256(nonceHash)), "duplicate nonce-hash");
uint256 amount = (16**_zeros(nonceHash) - 1)*frensOwned*10000/frenSupply;
require(amount > 0, "empty nonce-hash or has no frens");
_hashes.add(uint256(nonceHash));
_mint(_minter, amount);
}
| 13,177,022 |
./full_match/80001/0x20747FA1E7758a9F8D1E36Cf91A6bf2fc05aBf5e/sources/lib/hyperlane-monorepo/solidity/contracts/libs/Message.sol | Returns the message nonce. _message ABI encoded Hyperlane message. return Nonce of `_message`/ | function nonce(bytes calldata _message) internal pure returns (uint32) {
return uint32(bytes4(_message[NONCE_OFFSET:ORIGIN_OFFSET]));
}
| 845,417 |
./partial_match/1/0x4F9343fA110e8c5C1276B810fBbBB70A19678015/sources/contracts/LowGasVRF1/Lean/NFTSingleNoGatingSevPrices.sol | _raffleId Id of the raffle The operator can cancel the raffle. The NFT is sent back to the seller The raised funds are send to the destination wallet. The buyers will be refunded offchain in the metawin wallet Dont cancel twice, or cancel an already ended raffle only if the raffle is in accepted status the NFT is staked and could have entries sold | ) external nonReentrant onlyRole(OPERATOR_ROLE) {
RaffleStruct storage raffle = raffles[_raffleId];
EntryInfoStruct storage entryInfo = rafflesEntryInfo[_raffleId];
require(
entryInfo.status != STATUS.ENDED &&
entryInfo.status != STATUS.CANCELLED &&
entryInfo.status != STATUS.EARLY_CASHOUT &&
entryInfo.status != STATUS.CLOSING_REQUESTED &&
entryInfo.status != STATUS.CANCEL_REQUESTED,
"Wrong status"
);
function transferNFTAndFunds(
uint256 _raffleId,
uint256 _normalizedRandomNumber
}
function setCashOutActions(
uint256 _raffleId
}
}
function setWinnerActions(
uint256 _raffleId
}
function setWinner(
uint256 _raffleId
}
function setDestinationAddress(
address payable _newAddress
}
function cancelRaffle(
uint256 _raffleId
if (entryInfo.status == STATUS.ACCEPTED) {
IERC721 _asset = IERC721(raffle.collateralAddress);
_asset.transferFrom(
address(this),
raffle.seller,
raffle.collateralId
);
}
entryInfo.status = STATUS.CANCEL_REQUESTED;
raffle.cancellingDate = uint48(block.timestamp);
emit RaffleCancelled(_raffleId, entryInfo.amountRaised);
}
| 4,147,268 |
./full_match/1/0x94b34CcD6b6E39cF589d5be20B417e991FA86d1D/sources/contracts/CYAN.sol | Probably the most complicated function in the CYAN contractUpdates the unclaimed balance of a given address/userInitialize some loop variablesSet time of last burn change to now if it is not already setUse minimum interest if equation interest is less. | function updateUnclaimedBalance(address account) internal {
if (_timeOfLastBurnChange[account] == 0) {
_timeOfLastBurnChange[account] = block.timestamp / (INTEREST_INTERVAL);
}
if (intervalsTotalSupply[i] > 0) {
if (thisIntervalDenominator < 1) {
amountToAddToBalance += lastAmount;
}
amountToAddToBalance += lastAmount;
continue;
}
else {
lastAmount = _burntBalances[account] / MINIMUM_INTEREST_DENOMINATOR;
amountToAddToBalance += lastAmount;
continue;
}
}
| 8,339,699 |
pragma solidity ^0.4.23;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract EmploySale is Ownable {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Amount of wei raised
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
);
/**
* @param _token Address of the token being sold
*/
constructor(ERC20 _token) public {
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary, uint256 _rate, address _wallet) public payable {
require(_wallet != address(0));
require(_rate != 0);
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount, _rate);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_forwardFunds(_wallet);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @param _rate It is number of tokens transfered per ETH investment
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount, uint256 _rate)
internal pure returns (uint256)
{
return _weiAmount.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds(address _wallet) internal {
_wallet.transfer(msg.value);
}
function withdrawToken() onlyOwner external returns(bool) {
require(token.transfer(owner, token.balanceOf(address(this))));
return true;
}
} | Override to extend the way in which ether is converted to tokens. _weiAmount Value in wei to be converted into tokens _rate It is number of tokens transfered per ETH investment return Number of tokens that can be purchased with the specified _weiAmount/ | function _getTokenAmount(uint256 _weiAmount, uint256 _rate)
internal pure returns (uint256)
{
return _weiAmount.mul(_rate);
}
| 1,809,533 |
./full_match/1/0x2D1b8C783646e146312D317E550EF80EC1Cb08C3/sources/browser/daiStrategy.sol | maxDeleverage is how much we want to reduce by | function _normalDeleverage(
uint256 maxDeleverage,
uint256 lent,
uint256 borrowed,
uint256 collatRatio
) internal returns (uint256 deleveragedAmount) {
uint256 theoreticalLent = borrowed.mul(1e18).div(collatRatio);
deleveragedAmount = lent.sub(theoreticalLent);
if (deleveragedAmount >= borrowed) {
deleveragedAmount = borrowed;
}
if (deleveragedAmount >= maxDeleverage) {
deleveragedAmount = maxDeleverage;
}
cToken.redeemUnderlying(deleveragedAmount);
}
| 9,787,421 |
/* We use a fixed version of Solidity */
pragma solidity 0.4.24;
/**
* @title Useful functions for Uint arrays
* @author clemlak https://github.com/clemlak
* @dev Be careful Work In Progress :)
*/
library UintArrayUtils {
/**
* @dev Returns the highest value in an array
* @param a The array to inspect
* @return The highest value
*/
function getMax(uint[] a) internal pure returns (uint) {
uint max = a[0];
for (uint i = 0; i < a.length; i += 1) {
if (a[i] > max) {
max = a[i];
}
}
return max;
}
/**
* @dev Returns the lowest value in an array
* @param a The array to inspect
* @return The lowest value
*/
function getMin(uint[] a) internal pure returns (uint) {
uint min = a[0];
for (uint i = 0; i < a.length; i += 1) {
if (a[i] < min) {
min = a[i];
}
}
return min;
}
/**
* @dev Returns the sum of all the values in an array
* @param a The array to inspect
* @return The sum of all the values in the array
*/
function sum(uint[] a) internal pure returns (uint) {
uint s = 0;
for (uint i = 0; i < a.length; i += 1) {
s += a[i];
}
return s;
}
/**
* @dev Checks duplicate values in an array
* @param a The array to inspect
* @return True if the array contains duplicate values
*/
function checkDuplicates(uint[] a) internal pure returns (bool) {
bool duplicates = false;
for (uint i = 0; i < a.length; i += 1) {
uint k = 0;
for (uint j = 0; j < a.length; j += 1) {
if (a[i] == a[j]) {
k += 1;
}
if (k > 1) {
duplicates = true;
}
}
}
return duplicates;
}
/**
* @dev Checks matching values between 2 arrays
* Caution: Arrays must have the same length
* @param a The first array to inspect
* @param b The second array to inspect
* @return The amount of matching values
*/
function checkMatchingValues(uint[] a, uint[] b) internal pure returns (uint) {
uint k = 0;
for (uint i = 0; i < a.length; i += 1) {
for (uint j = 0; j < b.length; j += 1) {
if (a[i] == b[j]) {
k += 1;
}
}
}
return k;
}
/**
* @dev Concatenates 2 arrays
* @param a The first array to merge
* @param b The second array to merge
* @return A new array (merging of a and b)
*/
function concat(uint[] a, uint[] b) internal pure returns (uint[]) {
uint[] memory c = new uint[](a.length + b.length);
for (uint i = 0; i < a.length; i += 1) {
c[i] = a[i];
}
for (i = 0; i < b.length; i += 1) {
c[i+a.length] = b[i];
}
return c;
}
}
| Checks matching values between 2 arrays Caution: Arrays must have the same length a The first array to inspect b The second array to inspect return The amount of matching values/ | function checkMatchingValues(uint[] a, uint[] b) internal pure returns (uint) {
uint k = 0;
for (uint i = 0; i < a.length; i += 1) {
for (uint j = 0; j < b.length; j += 1) {
if (a[i] == b[j]) {
k += 1;
}
}
}
return k;
}
| 13,097,744 |
pragma solidity 0.5.9;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
contract ETORoles {
using Roles for Roles.Role;
constructor() internal {
_addAuditWriter(msg.sender);
_addAssetSeizer(msg.sender);
_addKycProvider(msg.sender);
_addUserManager(msg.sender);
_addOwner(msg.sender);
}
/*
* Audit Writer functions
*/
event AuditWriterAdded(address indexed account);
event AuditWriterRemoved(address indexed account);
Roles.Role private _auditWriters;
modifier onlyAuditWriter() {
require(isAuditWriter(msg.sender), "Sender is not auditWriter");
_;
}
function isAuditWriter(address account) public view returns (bool) {
return _auditWriters.has(account);
}
function addAuditWriter(address account) public onlyUserManager {
_addAuditWriter(account);
}
function renounceAuditWriter() public {
_removeAuditWriter(msg.sender);
}
function _addAuditWriter(address account) internal {
_auditWriters.add(account);
emit AuditWriterAdded(account);
}
function _removeAuditWriter(address account) internal {
_auditWriters.remove(account);
emit AuditWriterRemoved(account);
}
/*
* KYC Provider functions
*/
event KycProviderAdded(address indexed account);
event KycProviderRemoved(address indexed account);
Roles.Role private _kycProviders;
modifier onlyKycProvider() {
require(isKycProvider(msg.sender), "Sender is not kycProvider");
_;
}
function isKycProvider(address account) public view returns (bool) {
return _kycProviders.has(account);
}
function addKycProvider(address account) public onlyUserManager {
_addKycProvider(account);
}
function renounceKycProvider() public {
_removeKycProvider(msg.sender);
}
function _addKycProvider(address account) internal {
_kycProviders.add(account);
emit KycProviderAdded(account);
}
function _removeKycProvider(address account) internal {
_kycProviders.remove(account);
emit KycProviderRemoved(account);
}
/*
* Asset Seizer functions
*/
event AssetSeizerAdded(address indexed account);
event AssetSeizerRemoved(address indexed account);
Roles.Role private _assetSeizers;
modifier onlyAssetSeizer() {
require(isAssetSeizer(msg.sender), "Sender is not assetSeizer");
_;
}
function isAssetSeizer(address account) public view returns (bool) {
return _assetSeizers.has(account);
}
function addAssetSeizer(address account) public onlyUserManager {
_addAssetSeizer(account);
}
function renounceAssetSeizer() public {
_removeAssetSeizer(msg.sender);
}
function _addAssetSeizer(address account) internal {
_assetSeizers.add(account);
emit AssetSeizerAdded(account);
}
function _removeAssetSeizer(address account) internal {
_assetSeizers.remove(account);
emit AssetSeizerRemoved(account);
}
/*
* User Manager functions
*/
event UserManagerAdded(address indexed account);
event UserManagerRemoved(address indexed account);
Roles.Role private _userManagers;
modifier onlyUserManager() {
require(isUserManager(msg.sender), "Sender is not UserManager");
_;
}
function isUserManager(address account) public view returns (bool) {
return _userManagers.has(account);
}
function addUserManager(address account) public onlyUserManager {
_addUserManager(account);
}
function renounceUserManager() public {
_removeUserManager(msg.sender);
}
function _addUserManager(address account) internal {
_userManagers.add(account);
emit UserManagerAdded(account);
}
function _removeUserManager(address account) internal {
_userManagers.remove(account);
emit UserManagerRemoved(account);
}
/*
* Owner functions
*/
event OwnerAdded(address indexed account);
event OwnerRemoved(address indexed account);
Roles.Role private _owners;
modifier onlyOwner() {
require(isOwner(msg.sender), "Sender is not owner");
_;
}
function isOwner(address account) public view returns (bool) {
return _owners.has(account);
}
function addOwner(address account) public onlyUserManager {
_addOwner(account);
}
function renounceOwner() public {
_removeOwner(msg.sender);
}
function _addOwner(address account) internal {
_owners.add(account);
emit OwnerAdded(account);
}
function _removeOwner(address account) internal {
_owners.remove(account);
emit OwnerRemoved(account);
}
}
/**
* @title ERC20 interface
* @dev see https://eips.ethereum.org/EIPS/eip-20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
uint256 private _totalSupply;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return A uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowed[owner][spender];
}
/**
* @dev Transfer token to a specified address
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transfer(address to, uint256 value) public returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* Note that while this function emits an Approval event, this is not required as per the specification,
* and other compliant implementations may not emit the event.
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool) {
_transfer(from, to, value);
_approve(from, msg.sender, _allowed[from][msg.sender].sub(value));
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when _allowed[msg.sender][spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _mint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
_balances[account] = _balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Approve an address to spend another addresses' tokens.
* @param owner The address that owns the tokens.
* @param spender The address that will spend the tokens.
* @param value The number of tokens that can be spent.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(spender != address(0));
require(owner != address(0));
_allowed[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* Emits an Approval event (reflecting the reduced allowance).
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
_burn(account, value);
_approve(account, msg.sender, _allowed[account][msg.sender].sub(value));
}
}
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
/**
* @title ERC20Mintable
* @dev ERC20 minting logic
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev Function to mint tokens
* @param to The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address to, uint256 value) public onlyMinter returns (bool) {
_mint(to, value);
return true;
}
}
contract ETOToken is ERC20Mintable, ETORoles {
/* ETO investors */
mapping(address => bool) public investorWhitelist;
address[] public investorWhitelistLUT;
/* ETO contract parameters */
string public constant name = "Blockstate STO Token";
string public constant symbol = "BKN";
uint8 public constant decimals = 0;
/* Listing parameters */
string public ITIN;
/* Audit logging */
mapping(uint256 => uint256) public auditHashes;
/* Document hashes */
mapping(uint256 => uint256) public documentHashes;
/* Events in the ETO contract */
// Transaction related events
event AssetsSeized(address indexed seizee, uint256 indexed amount);
event AssetsUnseized(address indexed seizee, uint256 indexed amount);
event InvestorWhitelisted(address indexed investor);
event InvestorBlacklisted(address indexed investor);
event DividendPayout(address indexed receiver, uint256 indexed amount);
event TokensGenerated(uint256 indexed amount);
event OwnershipUpdated(address indexed newOwner);
/**
* @dev Constructor that defines contract parameters
*/
constructor() public {
ITIN = "CCF5-T3UQ-2";
}
/* Variable update events */
event ITINUpdated(string newValue);
/* Variable Update Functions */
function setITIN(string memory newValue) public onlyOwner {
ITIN = newValue;
emit ITINUpdated(newValue);
}
/* Function to set the required allowance before seizing assets */
function approveFor(address seizee, uint256 seizableAmount) public onlyAssetSeizer {
_approve(seizee, msg.sender, seizableAmount);
}
/* Seize assets */
function seizeAssets(address seizee, uint256 seizableAmount) public onlyAssetSeizer {
transferFrom(seizee, msg.sender, seizableAmount);
emit AssetsSeized(seizee, seizableAmount);
}
function releaseAssets(address seizee, uint256 seizedAmount) public onlyAssetSeizer {
require(balanceOf(msg.sender) >= seizedAmount, "AssetSeizer has insufficient funds");
transfer(seizee, seizedAmount);
emit AssetsUnseized(seizee, seizedAmount);
}
/* Add investor to the whitelist */
function whitelistInvestor(address investor) public onlyKycProvider {
require(investorWhitelist[investor] == false, "Investor already whitelisted");
investorWhitelist[investor] = true;
investorWhitelistLUT.push(investor);
emit InvestorWhitelisted(investor);
}
/* Remove investor from the whitelist */
function blacklistInvestor(address investor) public onlyKycProvider {
require(investorWhitelist[investor] == true, "Investor not on whitelist");
investorWhitelist[investor] = false;
uint256 arrayLen = investorWhitelistLUT.length;
for (uint256 i = 0; i < arrayLen; i++) {
if (investorWhitelistLUT[i] == investor) {
investorWhitelistLUT[i] = investorWhitelistLUT[investorWhitelistLUT.length - 1];
delete investorWhitelistLUT[investorWhitelistLUT.length - 1];
break;
}
}
emit InvestorBlacklisted(investor);
}
/* Overwrite transfer() to respect the whitelist, tag- and drag along rules */
function transfer(address to, uint256 value) public returns (bool) {
require(investorWhitelist[to] == true, "Investor not whitelisted");
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public returns (bool) {
require(investorWhitelist[to] == true, "Investor not whitelisted");
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public returns (bool) {
require(investorWhitelist[spender] == true, "Investor not whitelisted");
return super.approve(spender, value);
}
/* Generate tokens */
function generateTokens(uint256 amount, address assetReceiver) public onlyMinter {
_mint(assetReceiver, amount);
}
function initiateDividendPayments(uint amount) onlyOwner public returns (bool) {
uint dividendPerToken = amount / totalSupply();
uint256 arrayLen = investorWhitelistLUT.length;
for (uint256 i = 0; i < arrayLen; i++) {
address currentInvestor = investorWhitelistLUT[i];
uint256 currentInvestorShares = balanceOf(currentInvestor);
uint256 currentInvestorPayout = dividendPerToken * currentInvestorShares;
emit DividendPayout(currentInvestor, currentInvestorPayout);
}
return true;
}
function addAuditHash(uint256 hash) public onlyAuditWriter {
auditHashes[now] = hash;
}
function getAuditHash(uint256 timestamp) public view returns (uint256) {
return auditHashes[timestamp];
}
function addDocumentHash(uint256 hash) public onlyOwner {
documentHashes[now] = hash;
}
function getDocumentHash(uint256 timestamp) public view returns (uint256) {
return documentHashes[timestamp];
}
}
contract ETOVotes is ETOToken {
event VoteOpen(uint256 _id, uint _deadline);
event VoteFinished(uint256 _id, bool _result);
// How many blocks should we wait before the vote can be closed
mapping (uint256 => Vote) private votes;
struct Voter {
address id;
bool vote;
}
struct Vote {
uint256 deadline;
Voter[] voters;
mapping(address => uint) votersIndex;
uint256 documentHash;
}
constructor() public {}
function vote(uint256 _id, bool _vote) public {
// Allow changing opinion until vote deadline
require (votes[_id].deadline > 0, "Vote not available");
require(now <= votes[_id].deadline, "Vote deadline exceeded");
if (didCastVote(_id)) {
uint256 currentIndex = votes[_id].votersIndex[msg.sender];
Voter memory newVoter = Voter(msg.sender, _vote);
votes[_id].voters[currentIndex - 1] = newVoter;
} else {
votes[_id].voters.push(Voter(msg.sender, _vote));
votes[_id].votersIndex[msg.sender] = votes[_id].voters.length;
}
}
function getVoteDocumentHash(uint256 _id) public view returns (uint256) {
return votes[_id].documentHash;
}
function openVote(uint256 _id, uint256 documentHash, uint256 voteDuration) onlyOwner external {
require(votes[_id].deadline == 0, "Vote already ongoing");
votes[_id].deadline = now + (voteDuration * 1 seconds);
votes[_id].documentHash = documentHash;
emit VoteOpen(_id, votes[_id].deadline);
}
/**
* @dev Once the deadline is reached this function should be called to get decision.
* @param _id data source id.
*/
function triggerDecision(uint256 _id) external {
require(votes[_id].deadline > 0, "Vote not available");
require(now > votes[_id].deadline, "Vote deadline not reached");
// prevent method to be called again before its done
votes[_id].deadline = 0;
bool result = (getCurrentPositives(_id) > getCurrentNegatives(_id));
emit VoteFinished(_id, result);
}
/**
* @dev get vote status.
* @param _id data source id.
*/
function isVoteOpen(uint256 _id) external view returns (bool) {
return (votes[_id].deadline > 0) && (now <= votes[_id].deadline);
}
/**
* @dev check if address voted already.
* @param _id data source identifier.
*/
function didCastVote(uint256 _id) public view returns (bool) {
return (votes[_id].votersIndex[msg.sender] > 0);
}
function getOwnVote(uint256 _id) public view returns (bool) {
uint voterId = votes[_id].votersIndex[msg.sender];
return votes[_id].voters[voterId-1].vote;
}
function getCurrentPositives(uint256 _id) public view returns (uint256) {
uint adder = 0;
uint256 arrayLen = votes[_id].voters.length;
for (uint256 i = 0; i < arrayLen; i++) {
if (votes[_id].voters[i].vote == true) {
adder += balanceOf(votes[_id].voters[i].id);
}
}
return adder;
}
function getCurrentNegatives(uint256 _id) public view returns (uint256) {
uint adder = 0;
uint256 arrayLen = votes[_id].voters.length;
for (uint256 i = 0; i < arrayLen; i++) {
if (votes[_id].voters[i].vote == false) {
adder += balanceOf(votes[_id].voters[i].id);
}
}
return adder;
}
} | remove an account's access to this role/ | function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
| 1,035,652 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
// File: zeppelin-solidity/contracts/ownership/rbac/Roles.sol
/**
* @title Roles
* @author Francisco Giordano (@frangio)
* @dev Library for managing addresses assigned to a Role.
* See RBAC.sol for example usage.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an address access to this role
*/
function add(Role storage role, address addr)
internal
{
role.bearer[addr] = true;
}
/**
* @dev remove an address' access to this role
*/
function remove(Role storage role, address addr)
internal
{
role.bearer[addr] = false;
}
/**
* @dev check if an address has this role
* // reverts
*/
function check(Role storage role, address addr)
view
internal
{
require(has(role, addr));
}
/**
* @dev check if an address has this role
* @return bool
*/
function has(Role storage role, address addr)
view
internal
returns (bool)
{
return role.bearer[addr];
}
}
// File: zeppelin-solidity/contracts/ownership/rbac/RBAC.sol
/**
* @title RBAC (Role-Based Access Control)
* @author Matt Condon (@Shrugs)
* @dev Stores and provides setters and getters for roles and addresses.
* Supports unlimited numbers of roles and addresses.
* See //contracts/examples/RBACExample.sol for an example of usage.
* This RBAC method uses strings to key roles. It may be beneficial
* for you to write your own implementation of this interface using Enums or similar.
* It's also recommended that you define constants in the contract, like ROLE_ADMIN below,
* to avoid typos.
*/
abstract contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address addr, string roleName);
event RoleRemoved(address addr, string roleName);
/**
* A constant role name for indicating admins.
*/
string public constant ROLE_ADMIN = "admin";
/**
* @dev constructor. Sets msg.sender as admin by default
*/
constructor () {
addRole(msg.sender, ROLE_ADMIN);
}
/**
* @dev add a role to an address
* @param addr address
* @param roleName the name of the role
*/
function addRole(address addr, string memory roleName)
internal
{
roles[roleName].add(addr);
emit RoleAdded(addr, roleName);
}
/**
* @dev remove a role from an address
* @param addr address
* @param roleName the name of the role
*/
function removeRole(address addr, string memory roleName)
internal
{
roles[roleName].remove(addr);
emit RoleRemoved(addr, roleName);
}
/**
* @dev reverts if addr does not have role
* @param addr address
* @param roleName the name of the role
* // reverts
*/
function checkRole(address addr, string memory roleName)
view
public
{
roles[roleName].check(addr);
}
/**
* @dev determine if addr has role
* @param addr address
* @param roleName the name of the role
* @return bool
*/
function hasRole(address addr, string memory roleName)
view
public
returns (bool)
{
return roles[roleName].has(addr);
}
/**
* @dev add a role to an address
* @param addr address
* @param roleName the name of the role
*/
function adminAddRole(address addr, string memory roleName)
onlyAdmin
public
{
addRole(addr, roleName);
}
/**
* @dev remove a role from an address
* @param addr address
* @param roleName the name of the role
*/
function adminRemoveRole(address addr, string memory roleName)
onlyAdmin
public
{
removeRole(addr, roleName);
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param roleName the name of the role
* // reverts
*/
modifier onlyRole(string memory roleName)
{
checkRole(msg.sender, roleName);
_;
}
/**
* @dev modifier to scope access to admins
* // reverts
*/
modifier onlyAdmin()
{
checkRole(msg.sender, ROLE_ADMIN);
_;
}
/**
* @dev modifier to scope access to a set of roles (uses msg.sender as addr)
* @param roleNames the names of the roles to scope access to
* // reverts
*
* @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this
* see: https://github.com/ethereum/solidity/issues/2467
*/
// modifier onlyRoles(string[] roleNames) {
// bool hasAnyRole = false;
// for (uint8 i = 0; i < roleNames.length; i++) {
// if (hasRole(msg.sender, roleNames[i])) {
// hasAnyRole = true;
// break;
// }
// }
// require(hasAnyRole);
// _;
// }
}
// File: zeppelin-solidity/contracts/math/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;
}
}
// File: zeppelin-solidity/contracts/token/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
abstract contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view virtual returns (uint256);
function transfer(address to, uint256 value) public virtual returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: zeppelin-solidity/contracts/token/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
using SafeMath for uint;
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 override 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);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return balance uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view override returns (uint256 balance) {
return balances[_owner];
}
}
// File: zeppelin-solidity/contracts/token/BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
using SafeMath for uint;
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(burner, _value);
}
}
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: zeppelin-solidity/contracts/token/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
abstract contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view virtual returns (uint256);
function transferFrom(address from, address to, uint256 value) public virtual returns (bool);
function approve(address spender, uint256 value) public virtual returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc. athaine
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
// File: zeppelin-solidity/contracts/token/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 {
using SafeMath for uint;
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 override returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public override returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view override 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);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: zeppelin-solidity/contracts/token/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 {
using SafeMath for uint;
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);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
// File: contracts/Recurly.sol
contract Recurly is StandardToken, BurnableToken, MintableToken, RBAC {
using SafeMath for uint;
string public constant name = "Recurly";
string public constant symbol = "RCR";
uint8 public constant decimals = 18;
string constant public ROLE_TRANSFER = "transfer";
constructor() {
totalSupply = 0;
}
// used by hodler contract to transfer users tokens to it
function hodlerTransfer(address _from, uint256 _value) external onlyRole(ROLE_TRANSFER) returns (bool) {
require(_from != address(0));
require(_value > 0);
// hodler
address _hodler = msg.sender;
// update state
balances[_from] = balances[_from].sub(_value);
balances[_hodler] = balances[_hodler].add(_value);
// logs
emit Transfer(_from, _hodler, _value);
return true;
}
}
// File: contracts/CLERK.sol
contract CLERK is StandardToken, BurnableToken, RBAC {
using SafeMath for uint;
string public constant name = "Defi Clerk";
string public constant symbol = "CLERK";
uint8 public constant decimals = 18;
string constant public ROLE_MINT = "mint";
event MintLog(address indexed to, uint256 amount);
constructor() {
totalSupply = 0;
}
// used by contracts to mint CLERK tokens
function mint(address _to, uint256 _amount) external onlyRole(ROLE_MINT) returns (bool) {
require(_to != address(0));
require(_amount > 0);
// update state
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
// logs
emit MintLog(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
}
contract Hodler is Ownable {
using SafeMath for uint256;
using SafeERC20 for Recurly;
using SafeERC20 for CLERK;
Recurly public recurly;
CLERK public clerk;
struct Item {
uint256 id;
address beneficiary;
uint256 value;
uint256 releaseTime;
bool fulfilled;
}
mapping(address => mapping(uint256 => Item)) private items;
constructor(address _recurly, address _clerk) {
require(_recurly != address(0));
recurly = Recurly(_recurly);
changeClerkAddress(_clerk);
}
function changeClerkAddress(address _clerk) public onlyOwner {
require(_clerk != address(0));
clerk = CLERK(_clerk);
}
function hodl(uint256 _id, uint256 _value, uint256 _months) external {
require(_id > 0);
require(_value > 0);
// only 3 types are allowed
require(_months == 3 || _months == 6 || _months == 12);
// user
address _user = msg.sender;
// get clerk item
Item storage item = items[_user][_id];
// make sure clerk doesnt exist already
require(item.id != _id);
// turn months to seconds
uint256 _seconds = _months.mul(2628000);
//current time
uint256 _now = block.timestamp;
// get release time
uint256 _releaseTime = _now.add(_seconds);
require(_releaseTime > _now);
// check if user has enough balance
uint256 balance = recurly.balanceOf(_user);
require(balance >= _value);
// calculate percentage to mint for user: 3 months = 1% => _months / 3 = x
uint256 userPercentage = _months.div(3);
// get clerk amount: => (_value * userPercentage) / 100
uint256 userClerkAmount = _value.mul(userPercentage).div(100);
// update state
items[_user][_id] = Item(_id, _user, _value, _releaseTime, false);
// transfer tokens to hodler
assert(recurly.hodlerTransfer(_user, _value));
// mint tokens for user
assert(clerk.mint(_user, userClerkAmount));
}
function release(uint256 _id) external {
require(_id > 0);
// user
address _user = msg.sender;
// get item
Item storage item = items[_user][_id];
// check if it exists
require(item.id == _id);
// check if its not already fulfilled
require(!item.fulfilled);
// check time
require(block.timestamp >= item.releaseTime);
// check if there is enough tokens
uint256 balance = recurly.balanceOf(address(this));
require(balance >= item.value);
// update state
item.fulfilled = true;
// transfer tokens to beneficiary
recurly.safeTransfer(item.beneficiary, item.value);
}
function getItem(address _user, uint256 _id) public view returns (uint256, address, uint256, uint256, bool) {
Item storage item = items[_user][_id];
return (
item.id,
item.beneficiary,
item.value,
item.releaseTime,
item.fulfilled
);
}
} | remove a role from an address addr address roleName the name of the role/ | function adminRemoveRole(address addr, string memory roleName)
onlyAdmin
public
{
removeRole(addr, roleName);
}
| 1,343,228 |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "./spool/SpoolExternal.sol";
/**
* @notice Implementation of the central Spool contract.
*
* @dev
* The Spool implementation is the central part of the system.
* All the assets flow through this contract and are deposited
* to the integrated protocols.
*
* Spool implementation consists of following contracts:
* 1. BaseStorage: stores common variables with all the strategy adapters (they are execuret as delegatecode)
* 2. SpoolBase: holds Spool state variables and provides some of the common vault functions
* 3. SpoolStrategy: implements the logic of how to interact with the strategies
* 4. SpoolDoHardWork: implements functions to process the do hard work
* 5. SpoolReallocation: adjusts vault reallocation that takes place at the next do hard work
* 6. SpoolExternal: exposes functons to interact with the Spool from the vault (deposit/withdraw/redeem)
* 7. Spool: implements a constructor to deploy a contracts
*/
contract Spool is SpoolExternal {
/**
* @notice Initializes the central Spool contract values
*
* @param _spoolOwner the spool owner contract
* @param _controller responsible for providing the source of truth
* @param _fastWithdraw allows fast withdraw of user shares
*/
constructor(
ISpoolOwner _spoolOwner,
IController _controller,
address _fastWithdraw
)
SpoolBase(
_spoolOwner,
_controller,
_fastWithdraw
)
{}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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 `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
require(value <= type(uint192).max, "SafeCast: value doesn't fit in 128 bits");
return uint192(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "../external/@openzeppelin/token/ERC20/IERC20.sol";
import "./ISwapData.sol";
interface IBaseStrategy {
function underlying() external view returns (IERC20);
function getStrategyBalance() external view returns (uint128);
function getStrategyUnderlyingWithRewards() external view returns(uint128);
function process(uint256[] calldata, bool, SwapData[] calldata) external;
function processReallocation(uint256[] calldata, ProcessReallocationData calldata) external returns(uint128);
function processDeposit(uint256[] calldata) external;
function fastWithdraw(uint128, uint256[] calldata, SwapData[] calldata) external returns(uint128);
function claimRewards(SwapData[] calldata) external;
function emergencyWithdraw(address recipient, uint256[] calldata data) external;
function initialize() external;
function disable() external;
}
struct ProcessReallocationData {
uint128 sharesToWithdraw;
uint128 optimizedShares;
uint128 optimizedWithdrawnAmount;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "../external/@openzeppelin/token/ERC20/IERC20.sol";
interface IController {
/* ========== FUNCTIONS ========== */
function strategies(uint256 i) external view returns (address);
function validStrategy(address strategy) external view returns (bool);
function validVault(address vault) external view returns (bool);
function getStrategiesCount() external view returns(uint8);
function supportedUnderlying(IERC20 underlying)
external
view
returns (bool);
function getAllStrategies() external view returns (address[] memory);
function verifyStrategies(address[] calldata _strategies) external view;
function transferToSpool(
address transferFrom,
uint256 amount
) external;
function checkPaused() external view;
/* ========== EVENTS ========== */
event EmergencyWithdrawStrategy(address indexed strategy);
event EmergencyRecipientUpdated(address indexed recipient);
event EmergencyWithdrawerUpdated(address indexed withdrawer, bool set);
event PauserUpdated(address indexed user, bool set);
event UnpauserUpdated(address indexed user, bool set);
event VaultCreated(address indexed vault, address underlying, address[] strategies, uint256[] proportions,
uint16 vaultFee, address riskProvider, int8 riskTolerance);
event StrategyAdded(address strategy);
event StrategyRemoved(address strategy);
event VaultInvalid(address vault);
event DisableStrategy(address strategy);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
interface ISpoolOwner {
function isSpoolOwner(address user) external view returns(bool);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
/**
* @notice Strict holding information how to swap the asset
* @member slippage minumum output amount
* @member path swap path, first byte represents an action (e.g. Uniswap V2 custom swap), rest is swap specific path
*/
struct SwapData {
uint256 slippage; // min amount out
bytes path; // 1st byte is action, then path
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "./vault/IVaultRestricted.sol";
import "./vault/IVaultIndexActions.sol";
import "./vault/IRewardDrip.sol";
import "./vault/IVaultBase.sol";
import "./vault/IVaultImmutable.sol";
interface IVault is IVaultRestricted, IVaultIndexActions, IRewardDrip, IVaultBase, IVaultImmutable {}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
interface ISpoolBase {
/* ========== FUNCTIONS ========== */
function getCompletedGlobalIndex() external view returns(uint24);
function getActiveGlobalIndex() external view returns(uint24);
function isMidReallocation() external view returns (bool);
/* ========== EVENTS ========== */
event ReallocationTableUpdated(
uint24 indexed index,
bytes32 reallocationTableHash
);
event ReallocationTableUpdatedWithTable(
uint24 indexed index,
bytes32 reallocationTableHash,
uint256[][] reallocationTable
);
event DoHardWorkCompleted(uint24 indexed index);
event SetAllocationProvider(address actor, bool isAllocationProvider);
event SetIsDoHardWorker(address actor, bool isDoHardWorker);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
interface ISpoolDoHardWork {
/* ========== EVENTS ========== */
event DoHardWorkStrategyCompleted(address indexed strat, uint256 indexed index);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "../ISwapData.sol";
interface ISpoolExternal {
/* ========== FUNCTIONS ========== */
function deposit(address strategy, uint128 amount, uint256 index) external;
function withdraw(address strategy, uint256 vaultProportion, uint256 index) external;
function fastWithdrawStrat(address strat, address underlying, uint256 shares, uint256[] calldata slippages, SwapData[] calldata swapData) external returns(uint128);
function redeem(address strat, uint256 index) external returns (uint128, uint128);
function redeemUnderlying(uint128 amount) external;
function redeemReallocation(address[] calldata vaultStrategies, uint256 depositProportions, uint256 index) external;
function removeShares(address[] calldata vaultStrategies, uint256 vaultProportion) external returns(uint128[] memory);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
interface ISpoolReallocation {
event StartReallocation(uint24 indexed index);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
interface ISpoolStrategy {
/* ========== FUNCTIONS ========== */
function getUnderlying(address strat) external returns (uint128);
function getVaultTotalUnderlyingAtIndex(address strat, uint256 index) external view returns(uint128);
function addStrategy(address strat) external;
function disableStrategy(address strategy, bool skipDisable) external;
function runDisableStrategy(address strategy) external;
function emergencyWithdraw(
address strat,
address withdrawRecipient,
uint256[] calldata data
) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "../../external/@openzeppelin/token/ERC20/IERC20.sol";
interface IRewardDrip {
/* ========== STRUCTS ========== */
// The reward configuration struct, containing all the necessary data of a typical Synthetix StakingReward contract
struct RewardConfiguration {
uint32 rewardsDuration;
uint32 periodFinish;
uint192 rewardRate; // rewards per second multiplied by accuracy
uint32 lastUpdateTime;
uint224 rewardPerTokenStored;
mapping(address => uint256) userRewardPerTokenPaid;
mapping(address => uint256) rewards;
}
/* ========== FUNCTIONS ========== */
function getActiveRewards(address account) external;
function tokenBlacklist(IERC20 token) view external returns(bool);
/* ========== EVENTS ========== */
event RewardPaid(IERC20 token, address indexed user, uint256 reward);
event RewardAdded(IERC20 indexed token, uint256 amount, uint256 duration);
event RewardExtended(IERC20 indexed token, uint256 amount, uint256 leftover, uint256 duration, uint32 periodFinish);
event RewardRemoved(IERC20 indexed token);
event PeriodFinishUpdated(IERC20 indexed token, uint32 periodFinish);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "./IVaultDetails.sol";
interface IVaultBase {
/* ========== FUNCTIONS ========== */
function initialize(VaultInitializable calldata vaultInitializable) external;
/* ========== STRUCTS ========== */
struct User {
uint128 instantDeposit; // used for calculating rewards
uint128 activeDeposit; // users deposit after deposit process and claim
uint128 owed; // users owed underlying amount after withdraw has been processed and claimed
uint128 withdrawnDeposits; // users withdrawn deposit, used to calculate performance fees
uint128 shares; // users shares after deposit process and claim
}
/* ========== EVENTS ========== */
event Claimed(address indexed member, uint256 claimAmount);
event Deposit(address indexed member, uint256 indexed index, uint256 amount);
event Withdraw(address indexed member, uint256 indexed index, uint256 shares);
event WithdrawFast(address indexed member, uint256 shares);
event StrategyRemoved(uint256 i, address strategy);
event TransferVaultOwner(address owner);
event LowerVaultFee(uint16 fee);
event UpdateName(string name);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
struct VaultDetails {
address underlying;
address[] strategies;
uint256[] proportions;
address creator;
uint16 vaultFee;
address riskProvider;
int8 riskTolerance;
string name;
}
struct VaultInitializable {
string name;
address owner;
uint16 fee;
address[] strategies;
uint256[] proportions;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "../../external/@openzeppelin/token/ERC20/IERC20.sol";
struct VaultImmutables {
IERC20 underlying;
address riskProvider;
int8 riskTolerance;
}
interface IVaultImmutable {
/* ========== FUNCTIONS ========== */
function underlying() external view returns (IERC20);
function riskProvider() external view returns (address);
function riskTolerance() external view returns (int8);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
interface IVaultIndexActions {
/* ========== STRUCTS ========== */
struct IndexAction {
uint128 depositAmount;
uint128 withdrawShares;
}
struct LastIndexInteracted {
uint128 index1;
uint128 index2;
}
struct Redeem {
uint128 depositShares;
uint128 withdrawnAmount;
}
/* ========== EVENTS ========== */
event VaultRedeem(uint indexed globalIndex);
event UserRedeem(address indexed member, uint indexed globalIndex);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
interface IVaultRestricted {
/* ========== FUNCTIONS ========== */
function reallocate(
address[] calldata vaultStrategies,
uint256 newVaultProportions,
uint256 finishedIndex,
uint24 activeIndex
) external returns (uint256[] memory, uint256);
function payFees(uint256 profit) external returns (uint256 feesPaid);
/* ========== EVENTS ========== */
event Reallocate(uint24 indexed index, uint256 newProportions);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
library Bitwise {
function get8BitUintByIndex(uint256 bitwiseData, uint256 i) internal pure returns(uint256) {
return (bitwiseData >> (8 * i)) & type(uint8).max;
}
// 14 bits is used for strategy proportions in a vault as FULL_PERCENT is 10_000
function get14BitUintByIndex(uint256 bitwiseData, uint256 i) internal pure returns(uint256) {
return (bitwiseData >> (14 * i)) & (16_383); // 16.383 is 2^14 - 1
}
function set14BitUintByIndex(uint256 bitwiseData, uint256 i, uint256 num14bit) internal pure returns(uint256) {
return bitwiseData + (num14bit << (14 * i));
}
function reset14BitUintByIndex(uint256 bitwiseData, uint256 i) internal pure returns(uint256) {
return bitwiseData & (~(16_383 << (14 * i)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
/**
* @notice Library to provide utils for hashing and hash compatison of Spool related data
*/
library Hash {
function hashReallocationTable(uint256[][] memory reallocationTable) internal pure returns(bytes32) {
return keccak256(abi.encode(reallocationTable));
}
function hashStrategies(address[] memory strategies) internal pure returns(bytes32) {
return keccak256(abi.encodePacked(strategies));
}
function sameStrategies(address[] memory strategies1, address[] memory strategies2) internal pure returns(bool) {
return hashStrategies(strategies1) == hashStrategies(strategies2);
}
function sameStrategies(address[] memory strategies, bytes32 strategiesHash) internal pure returns(bool) {
return hashStrategies(strategies) == strategiesHash;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "../external/@openzeppelin/utils/SafeCast.sol";
/**
* @notice A collection of custom math ustils used throughout the system
*/
library Math {
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? b : a;
}
function getProportion128(uint256 mul1, uint256 mul2, uint256 div) internal pure returns (uint128) {
return SafeCast.toUint128(((mul1 * mul2) / div));
}
function getProportion128Unchecked(uint256 mul1, uint256 mul2, uint256 div) internal pure returns (uint128) {
unchecked {
return uint128((mul1 * mul2) / div);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
/** @notice Handle setting zero value in a storage word as uint128 max value.
*
* @dev
* The purpose of this is to avoid resetting a storage word to the zero value;
* the gas cost of re-initializing the value is the same as setting the word originally.
* so instead, if word is to be set to zero, we set it to uint128 max.
*
* - anytime a word is loaded from storage: call "get"
* - anytime a word is written to storage: call "set"
* - common operations on uints are also bundled here.
*
* NOTE: This library should ONLY be used when reading or writing *directly* from storage.
*/
library Max128Bit {
uint128 internal constant ZERO = type(uint128).max;
function get(uint128 a) internal pure returns(uint128) {
return (a == ZERO) ? 0 : a;
}
function set(uint128 a) internal pure returns(uint128){
return (a == 0) ? ZERO : a;
}
function add(uint128 a, uint128 b) internal pure returns(uint128 c){
a = get(a);
c = set(a + b);
}
}
// SPDX-License-Identifier: BUSL-1.1
import "../interfaces/ISwapData.sol";
pragma solidity 0.8.11;
/// @notice Strategy struct for all strategies
struct Strategy {
uint128 totalShares;
/// @notice Denotes strategy completed index
uint24 index;
/// @notice Denotes whether strategy is removed
/// @dev after removing this value can never change, hence strategy cannot be added back again
bool isRemoved;
/// @notice Pending geposit amount and pending shares withdrawn by all users for next index
Pending pendingUser;
/// @notice Used if strategies "dohardwork" hasn't been executed yet in the current index
Pending pendingUserNext;
/// @dev Usually a temp variable when compounding
mapping(address => uint256) pendingRewards;
/// @dev Usually a temp variable when compounding
uint128 pendingDepositReward;
/// @notice Amount of lp tokens the strategy holds, NOTE: not all strategies use it
uint256 lpTokens;
// ----- REALLOCATION VARIABLES -----
bool isInDepositPhase;
/// @notice Used to store amount of optimized shares, so they can be substracted at the end
/// @dev Only for temporary use, should be reset to 0 in same transaction
uint128 optimizedSharesWithdrawn;
/// @dev Underlying amount pending to be deposited from other strategies at reallocation
/// @dev resets after the strategy reallocation DHW is finished
uint128 pendingReallocateDeposit;
/// @notice Stores amount of optimized underlying amount when reallocating
/// @dev resets after the strategy reallocation DHW is finished
/// @dev This is "virtual" amount that was matched between this strategy and others when reallocating
uint128 pendingReallocateOptimizedDeposit;
// ------------------------------------
/// @notice Total underlying amoung at index
mapping(uint256 => TotalUnderlying) totalUnderlying;
/// @notice Batches stored after each DHW with index as a key
/// @dev Holds information for vauls to redeem newly gained shares and withdrawn amounts belonging to users
mapping(uint256 => Batch) batches;
/// @notice Batches stored after each DHW reallocating (if strategy was set to reallocate)
/// @dev Holds information for vauls to redeem newly gained shares and withdrawn shares to complete reallocation
mapping(uint256 => BatchReallocation) reallocationBatches;
/// @notice Vaults holding this strategy shares
mapping(address => Vault) vaults;
/// @notice Future proof storage
mapping(bytes32 => AdditionalStorage) additionalStorage;
/// @dev Make sure to reset it to 0 after emergency withdrawal
uint256 emergencyPending;
}
/// @notice Unprocessed deposit underlying amount and strategy share amount from users
struct Pending {
uint128 deposit;
uint128 sharesToWithdraw;
}
/// @notice Struct storing total underlying balance of a strategy for an index, along with total shares at same index
struct TotalUnderlying {
uint128 amount;
uint128 totalShares;
}
/// @notice Stored after executing DHW for each index.
/// @dev This is used for vaults to redeem their deposit.
struct Batch {
/// @notice total underlying deposited in index
uint128 deposited;
uint128 depositedReceived;
uint128 depositedSharesReceived;
uint128 withdrawnShares;
uint128 withdrawnReceived;
}
/// @notice Stored after executing reallocation DHW each index.
struct BatchReallocation {
/// @notice Deposited amount received from reallocation
uint128 depositedReallocation;
/// @notice Received shares from reallocation
uint128 depositedReallocationSharesReceived;
/// @notice Used to know how much tokens was received for reallocating
uint128 withdrawnReallocationReceived;
/// @notice Amount of shares to withdraw for reallocation
uint128 withdrawnReallocationShares;
}
/// @notice VaultBatches could be refactored so we only have 2 structs current and next (see how Pending is working)
struct Vault {
uint128 shares;
/// @notice Withdrawn amount as part of the reallocation
uint128 withdrawnReallocationShares;
/// @notice Index to action
mapping(uint256 => VaultBatch) vaultBatches;
}
/// @notice Stores deposited and withdrawn shares by the vault
struct VaultBatch {
/// @notice Vault index to deposited amount mapping
uint128 deposited;
/// @notice Vault index to withdrawn user shares mapping
uint128 withdrawnShares;
}
/// @notice Used for reallocation calldata
struct VaultData {
address vault;
uint8 strategiesCount;
uint256 strategiesBitwise;
uint256 newProportions;
}
/// @notice Calldata when executing reallocatin DHW
/// @notice Used in the withdraw part of the reallocation DHW
struct ReallocationWithdrawData {
uint256[][] reallocationTable;
StratUnderlyingSlippage[] priceSlippages;
RewardSlippages[] rewardSlippages;
uint256[] stratIndexes;
uint256[][] slippages;
}
/// @notice Calldata when executing reallocatin DHW
/// @notice Used in the deposit part of the reallocation DHW
struct ReallocationData {
uint256[] stratIndexes;
uint256[][] slippages;
}
/// @notice In case some adapters need extra storage
struct AdditionalStorage {
uint256 value;
address addressValue;
uint96 value96;
}
/// @notice Strategy total underlying slippage, to verify validity of the strategy state
struct StratUnderlyingSlippage {
uint128 min;
uint128 max;
}
/// @notice Containig information if and how to swap strategy rewards at the DHW
/// @dev Passed in by the do-hard-worker
struct RewardSlippages {
bool doClaim;
SwapData[] swapData;
}
/// @notice Helper struct to compare strategy share between eachother
/// @dev Used for reallocation optimization of shares (strategy matching deposits and withdrawals between eachother when reallocating)
struct PriceData {
uint128 totalValue;
uint128 totalShares;
}
/// @notice Strategy reallocation values after reallocation optimization of shares was calculated
struct ReallocationShares {
uint128[] optimizedWithdraws;
uint128[] optimizedShares;
uint128[] totalSharesWithdrawn;
}
/// @notice Shared storage for multiple strategies
/// @dev This is used when strategies are part of the same proticil (e.g. Curve 3pool)
struct StrategiesShared {
uint184 value;
uint32 lastClaimBlock;
uint32 lastUpdateBlock;
uint8 stratsCount;
mapping(uint256 => address) stratAddresses;
mapping(bytes32 => uint256) bytesValues;
}
/// @notice Base storage shared betweek Spool contract and Strategies
/// @dev this way we can use same values when performing delegate call
/// to strategy implementations from the Spool contract
abstract contract BaseStorage {
// ----- DHW VARIABLES -----
/// @notice Force while DHW (all strategies) to be executed in only one transaction
/// @dev This is enforced to increase the gas efficiency of the system
/// Can be removed by the DAO if gas gost of the strategies goes over the block limit
bool internal forceOneTxDoHardWork;
/// @notice Global index of the system
/// @dev Insures the correct strategy DHW execution.
/// Every strategy in the system must be equal or one less than global index value
/// Global index increments by 1 on every do-hard-work
uint24 public globalIndex;
/// @notice number of strategies unprocessed (by the do-hard-work) in the current index to be completed
uint8 internal doHardWorksLeft;
// ----- REALLOCATION VARIABLES -----
/// @notice Used for offchain execution to get the new reallocation table.
bool internal logReallocationTable;
/// @notice number of withdrawal strategies unprocessed (by the do-hard-work) in the current index
/// @dev only used when reallocating
/// after it reaches 0, deposit phase of the reallocation can begin
uint8 public withdrawalDoHardWorksLeft;
/// @notice Index at which next reallocation is set
uint24 public reallocationIndex;
/// @notice 2D table hash containing information of how strategies should be reallocated between eachother
/// @dev Created when allocation provider sets reallocation for the vaults
/// This table is stored as a hash in the system and verified on reallocation DHW
/// Resets to 0 after reallocation DHW is completed
bytes32 internal reallocationTableHash;
/// @notice Hash of all the strategies array in the system at the time when reallocation was set for index
/// @dev this array is used for the whole reallocation period even if a strategy gets exploited when reallocating.
/// This way we can remove the strategy from the system and not breaking the flow of the reallocaton
/// Resets when DHW is completed
bytes32 internal reallocationStrategiesHash;
// -----------------------------------
/// @notice Denoting if an address is the do-hard-worker
mapping(address => bool) public isDoHardWorker;
/// @notice Denoting if an address is the allocation provider
mapping(address => bool) public isAllocationProvider;
/// @notice Strategies shared storage
/// @dev used as a helper storage to save common inoramation
mapping(bytes32 => StrategiesShared) internal strategiesShared;
/// @notice Mapping of strategy implementation address to strategy system values
mapping(address => Strategy) public strategies;
/// @notice Flag showing if disable was skipped when a strategy has been removed
/// @dev If true disable can still be run
mapping(address => bool) internal _skippedDisable;
/// @notice Flag showing if after removing a strategy emergency withdraw can still be executed
/// @dev If true emergency withdraw can still be executed
mapping(address => bool) internal _awaitingEmergencyWithdraw;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "../external/@openzeppelin/token/ERC20/IERC20.sol";
/// @title Common Spool contracts constants
abstract contract BaseConstants {
/// @dev 2 digits precision
uint256 internal constant FULL_PERCENT = 100_00;
/// @dev Accuracy when doing shares arithmetics
uint256 internal constant ACCURACY = 10**30;
}
/// @title Contains USDC token related values
abstract contract USDC {
/// @notice USDC token contract address
IERC20 internal constant USDC_ADDRESS = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "../interfaces/ISpoolOwner.sol";
/// @title Logic to help check whether the caller is the Spool owner
abstract contract SpoolOwnable {
/// @notice Contract that checks if address is Spool owner
ISpoolOwner internal immutable spoolOwner;
/**
* @notice Sets correct initial values
* @param _spoolOwner Spool owner contract address
*/
constructor(ISpoolOwner _spoolOwner) {
require(
address(_spoolOwner) != address(0),
"SpoolOwnable::constructor: Spool owner contract address cannot be 0"
);
spoolOwner = _spoolOwner;
}
/**
* @notice Checks if caller is Spool owner
* @return True if caller is Spool owner, false otherwise
*/
function isSpoolOwner() internal view returns(bool) {
return spoolOwner.isSpoolOwner(msg.sender);
}
/// @notice Checks and throws if caller is not Spool owner
function _onlyOwner() private view {
require(isSpoolOwner(), "SpoolOwnable::onlyOwner: Caller is not the Spool owner");
}
/// @notice Checks and throws if caller is not Spool owner
modifier onlyOwner() {
_onlyOwner();
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "../interfaces/IController.sol";
/// @title Facilitates checking if the system is paused or not
abstract contract SpoolPausable {
/* ========== STATE VARIABLES ========== */
/// @notice The controller contract that is consulted for a strategy's and vault's validity
IController public immutable controller;
/**
* @notice Sets initial values
* @param _controller Controller contract address
*/
constructor(IController _controller) {
require(
address(_controller) != address(0),
"SpoolPausable::constructor: Controller contract address cannot be 0"
);
controller = _controller;
}
/* ========== MODIFIERS ========== */
/// @notice Throws if system is paused
modifier systemNotPaused() {
controller.checkPaused();
_;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
// extends
import "../interfaces/spool/ISpoolBase.sol";
import "../shared/BaseStorage.sol";
import "../shared/SpoolOwnable.sol";
import "../shared/Constants.sol";
// libraries
import "../libraries/Hash.sol";
// other imports
import "../interfaces/IController.sol";
import "../shared/SpoolPausable.sol";
/**
* @notice Implementation of the {ISpoolBase} interface.
*
* @dev
* This implementation acts as the central code execution point of the Spool
* system and is responsible for maintaining the balance sheet of each vault
* based on the asynchronous deposit and withdraw system, redeeming vault
* shares and withdrawals and performing doHardWork.
*/
abstract contract SpoolBase is
ISpoolBase,
BaseStorage,
SpoolOwnable,
SpoolPausable,
BaseConstants
{
/* ========== STATE VARIABLES ========== */
/// @notice The fast withdraw contract that is used to quickly remove shares
address internal immutable fastWithdraw;
/* ========== CONSTRUCTOR ========== */
/**
* @notice Sets the contract initial values
*
* @dev
* Additionally, initializes the SPL reward data for
* do hard work invocations.
*
* It performs certain pre-conditional validations to ensure the contract
* has been initialized properly, such as valid addresses and reward configuration.
*
* @param _spoolOwner the spool owner contract address
* @param _controller the controller contract address
* @param _fastWithdraw the fast withdraw contract address
*/
constructor(
ISpoolOwner _spoolOwner,
IController _controller,
address _fastWithdraw
)
SpoolOwnable(_spoolOwner)
SpoolPausable(_controller)
{
require(
_fastWithdraw != address(0),
"BaseSpool::constructor: FastWithdraw address cannot be 0"
);
fastWithdraw = _fastWithdraw;
globalIndex = 1;
}
/* ========== VIEWS ========== */
/**
* @notice Checks whether Spool is mid reallocation
* @return _isMidReallocation True if Spool is mid reallocation
*/
function isMidReallocation() public view override returns (bool _isMidReallocation) {
if (reallocationIndex == globalIndex && !_isBatchComplete()) {
_isMidReallocation = true;
}
}
/**
* @notice Returns strategy shares belonging to a vauld
* @param strat Strategy address
* @param vault Vault address
* @return Shares for a specific vault - strategy combination
*/
function getStratVaultShares(address strat, address vault) external view returns(uint128) {
return strategies[strat].vaults[vault].shares;
}
/**
* @notice Returns completed index (all strategies in the do hard work have been processed)
* @return Completed index
*/
function getCompletedGlobalIndex() public override view returns(uint24) {
if (_isBatchComplete()) {
return globalIndex;
}
return globalIndex - 1;
}
/**
* @notice Returns next possible index to interact with
* @return Next active global index
*/
function getActiveGlobalIndex() public override view returns(uint24) {
return globalIndex + 1;
}
/**
* @notice Check if batch complete
* @return isComplete True if all strategies have the same index
*/
function _isBatchComplete() internal view returns(bool isComplete) {
if (doHardWorksLeft == 0) {
isComplete = true;
}
}
/**
* @notice Decode revert message
* @param _returnData Data returned by delegatecall
* @return Revert string
*/
function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {
// if the _res length is less than 68, then the transaction failed silently (without a revert message)
if (_returnData.length < 68) return "SILENT";
assembly {
// slice the sig hash
_returnData := add(_returnData, 0x04)
}
return abi.decode(_returnData, (string)); // all that remains is the revert string
}
/* ========== DELEGATECALL HELPERS ========== */
/**
* @notice this function allows static-calling an arbitrary write function from Spool, off-chain, and returning the result. The general purpose is for the calculation of
* rewards in an implementation contract, where the reward calculation contains state changes that can't be easily gathered without calling from the Spool contract.
* The require statement ensure that this comes from a static call off-chain, which can substitute an arbitrary address.
* The 'one' address is used. The zero address could be used, but due to the prevalence of zero address checks, the internal calls would likely fail.
* It has the same level of security as finding any arbitrary address, including address zero.
*
* @param implementation Address which to relay the call to
* @param payload Payload to relay to the implementation
* @return Response returned by the relayed call
*/
function relay(address implementation, bytes memory payload) external returns(bytes memory) {
require(msg.sender == address(1));
return _relay(implementation, payload);
}
/**
* @notice Relays the particular action to the strategy via delegatecall.
* @param strategy Strategy address to delegate the call to
* @param payload Data to pass when delegating call
* @return Response received when delegating call
*/
function _relay(address strategy, bytes memory payload)
internal
returns (bytes memory)
{
(bool success, bytes memory data) = strategy.delegatecall(payload);
if (!success) revert(_getRevertMsg(data));
return data;
}
/* ========== CONFIGURATION ========== */
/**
* @notice Set allocation provider role for given user
* Requirements:
* - the caller must be the Spool owner (Spool DAO)
*
* @param user Address to set the role for
* @param _isAllocationProvider Whether the user is assigned the role or not
*/
function setAllocationProvider(address user, bool _isAllocationProvider) external onlyOwner {
isAllocationProvider[user] = _isAllocationProvider;
emit SetAllocationProvider(user, _isAllocationProvider);
}
/**
* @notice Set doHardWorker role for given user
* Requirements:
* - the caller must be the Spool owner (Spool DAO)
*
* @param user Address to set the role for
* @param _isDoHardWorker Whether the user is assigned the role or not
*/
function setDoHardWorker(address user, bool _isDoHardWorker) external onlyOwner {
isDoHardWorker[user] = _isDoHardWorker;
emit SetIsDoHardWorker(user, _isDoHardWorker);
}
/**
* @notice Set the flag to force "do hard work" to be executed in one transaction.
* Requirements:
* - the caller must be the Spool owner (Spool DAO)
*
* @param doForce Enable/disable running in one transactions
*/
function setForceOneTxDoHardWork(bool doForce) external onlyOwner {
forceOneTxDoHardWork = doForce;
}
/**
* @notice Set the flag to log reallocation proportions on change.
* Requirements:
* - the caller must be the Spool owner (Spool DAO)
*
* @dev Used for offchain execution to get the new reallocation table.
* @param doLog Whether to log or not
*/
function setLogReallocationTable(bool doLog) external onlyOwner {
logReallocationTable = doLog;
}
/**
* @notice Set awaiting emergency withdraw flag for the strategy.
*
* @dev
* Only for emergency case where withdrawing the first time doesn't fully work.
*
* Requirements:
*
* - the caller must be the Spool owner (Spool DAO)
*
* @param strat strategy to set
* @param isAwaiting Flag value
*/
function setAwaitingEmergencyWithdraw(address strat, bool isAwaiting) external onlyOwner {
_awaitingEmergencyWithdraw[strat] = isAwaiting;
}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @notice Ensures that given address is a valid vault
*/
function _isVault(address vault) internal view {
require(
controller.validVault(vault),
"NTVLT"
);
}
/**
* @notice Ensures that strategy wasn't removed
*/
function _notRemoved(address strat) internal view {
require(
!strategies[strat].isRemoved,
"OKSTRT"
);
}
/**
* @notice If batch is complete it resets reallocation variables and emits an event
* @param isReallocation If true, reset the reallocation variables
*/
function _finishDhw(bool isReallocation) internal {
if (_isBatchComplete()) {
// reset reallocation variables
if (isReallocation) {
reallocationIndex = 0;
reallocationTableHash = 0;
}
emit DoHardWorkCompleted(globalIndex);
}
}
/* ========== PRIVATE FUNCTIONS ========== */
/**
* @notice Ensures that the caller is the controller
*/
function _onlyController() private view {
require(
msg.sender == address(controller),
"OCTRL"
);
}
/**
* @notice Ensures that the caller is the fast withdraw
*/
function _onlyFastWithdraw() private view {
require(
msg.sender == fastWithdraw,
"OFWD"
);
}
/**
* @notice Ensures that there is no pending reallocation
*/
function _noPendingReallocation() private view {
require(
reallocationTableHash == 0,
"NORLC"
);
}
/**
* @notice Ensures that strategy is removed
*/
function _onlyRemoved(address strat) private view {
require(
strategies[strat].isRemoved,
"RMSTR"
);
}
/**
* @notice Verifies given strategies
* @param strategies Array of strategies to verify
*/
function _verifyStrategies(address[] memory strategies) internal view {
controller.verifyStrategies(strategies);
}
/**
* @notice Ensures that the caller is allowed to execute do hard work
*/
function _onlyDoHardWorker() private view {
require(
isDoHardWorker[msg.sender],
"ODHW"
);
}
/**
* @notice Verifies the reallocation table against the stored hash
* @param reallocationTable The data to verify
*/
function _verifyReallocationTable(uint256[][] memory reallocationTable) internal view {
require(reallocationTableHash == Hash.hashReallocationTable(reallocationTable), "BRLC");
}
/**
* @notice Verifies the reallocation strategies against the stored hash
* @param strategies Array of strategies to verify
*/
function _verifyReallocationStrategies(address[] memory strategies) internal view {
require(Hash.sameStrategies(strategies, reallocationStrategiesHash), "BRLCSTR");
}
/* ========== MODIFIERS ========== */
/**
* @notice Throws if called by anyone else other than the controller
*/
modifier onlyDoHardWorker() {
_onlyDoHardWorker();
_;
}
/**
* @notice Throws if called by a non-valid vault
*/
modifier onlyVault() {
_isVault(msg.sender);
_;
}
/**
* @notice Throws if called by anyone else other than the controller
*/
modifier onlyController() {
_onlyController();
_;
}
/**
* @notice Throws if the caller is not fast withdraw
*/
modifier onlyFastWithdraw() {
_onlyFastWithdraw();
_;
}
/**
* @notice Throws if given array of strategies is not valid
*/
modifier verifyStrategies(address[] memory strategies) {
_verifyStrategies(strategies);
_;
}
/**
* @notice Throws if given array of reallocation strategies is not valid
*/
modifier verifyReallocationStrategies(address[] memory strategies) {
_verifyReallocationStrategies(strategies);
_;
}
/**
* @notice Throws if caller does not have the allocation provider role
*/
modifier onlyAllocationProvider() {
require(
isAllocationProvider[msg.sender],
"OALC"
);
_;
}
/**
* @notice Ensures that there is no pending reallocation
*/
modifier noPendingReallocation() {
_noPendingReallocation();
_;
}
/**
* @notice Throws strategy is removed
*/
modifier notRemoved(address strat) {
_notRemoved(strat);
_;
}
/**
* @notice Throws strategy isn't removed
*/
modifier onlyRemoved(address strat) {
_onlyRemoved(strat);
_;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
// extends
import "../interfaces/spool/ISpoolDoHardWork.sol";
import "./SpoolStrategy.sol";
/**
* @notice Spool part of implementation dealing with the do hard work
*
* @dev
* Do hard work is the process of interacting with other protocols.
* This process aggregates many actions together to act in as optimized
* manner as possible. It optimizes for underlying assets and gas cost.
*
* Do hard work (DHW) is executed periodically. As users are depositing
* and withdrawing, these actions are stored in the buffer system.
* When executed the deposits and withdrawals are matched against
* eachother to minimize slippage and protocol fees. This means that
* for a normal DHW only deposit or withdrawal is executed and never
* both in the same index. Both can only be if the DHW is processing
* the reallocation as well.
*
* Each strategy DHW is executed once per index and then incremented.
* When all strategies are incremented to the same index, the batch
* is considered complete. As soon as a new batch starts (first strategy
* in the new batch is processed) global index is incremented.
*
* Global index is always one more or equal to the strategy index.
* This constraints the system so that all strategy DHWs have to be
* executed to complete the batch.
*
* Do hard work can only be executed by the whitelisted addresses.
* The whitelisting can be done only by the Spool DAO.
*
* Do hard work actions:
* - deposit
* - withdrawal
* - compound rewards
* - reallocate assets across protocols
*
*/
abstract contract SpoolDoHardWork is ISpoolDoHardWork, SpoolStrategy {
/* ========== DO HARD WORK ========== */
/**
* @notice Executes do hard work of specified strategies.
*
* @dev
* Requirements:
*
* - caller must be a valid do hard worker
* - provided strategies must be valid
* - reallocation is not pending for current index
* - if `forceOneTxDoHardWork` flag is true all strategies should be executed in one transaction
* - at least one strategy must be processed
* - the system should not be paused
*
* @param stratIndexes Array of strategy indexes
* @param slippages Array of slippage values to be used when depositing into protocols (e.g. minOut)
* @param rewardSlippages Array of values containing information of if and how to swap reward tokens to strategy underlying
* @param allStrategies Array of all valid strategy addresses in the system
*/
function batchDoHardWork(
uint256[] memory stratIndexes,
uint256[][] memory slippages,
RewardSlippages[] memory rewardSlippages,
address[] memory allStrategies
)
external
systemNotPaused
onlyDoHardWorker
verifyStrategies(allStrategies)
{
// update global index if this are first strategies in index
if (_isBatchComplete()) {
globalIndex++;
doHardWorksLeft = uint8(allStrategies.length);
}
// verify reallocation is not set for the current index
if (reallocationIndex == globalIndex) {
// if reallocation is set, verify it was disabled
require(reallocationTableHash == 0, "RLC");
// if yes, reset reallocation index
reallocationIndex = 0;
}
require(
stratIndexes.length > 0 &&
stratIndexes.length == slippages.length &&
stratIndexes.length == rewardSlippages.length,
"BIPT"
);
// check if DHW is forcen to be executen on one transaction
if (forceOneTxDoHardWork) {
require(stratIndexes.length == allStrategies.length, "1TX");
}
// go over withdrawals and deposits
for (uint256 i = 0; i < stratIndexes.length; i++) {
address stratAddress = allStrategies[stratIndexes[i]];
_doHardWork(stratAddress, slippages[i], rewardSlippages[i]);
_updatePending(stratAddress);
_finishStrategyDoHardWork(stratAddress);
}
_updateDoHardWorksLeft(stratIndexes.length);
// if DHW for index finished
_finishDhw(false);
}
/**
* @notice Process strategy DHW, deposit wnd withdraw
* @dev Only executed when there is no reallocation for the DHW
* @param strat Strategy address
* @param slippages Array of slippage values to be used when depositing into protocols (e.g. minOut)
* @param rewardSlippages Array of values containing information of if and how to swap reward tokens to strategy underlying
*/
function _doHardWork(
address strat,
uint256[] memory slippages,
RewardSlippages memory rewardSlippages
) private {
Strategy storage strategy = strategies[strat];
// Check if strategy wasn't exected in current index yet
require(strategy.index < globalIndex, "SFIN");
_process(strat, slippages, rewardSlippages.doClaim, rewardSlippages.swapData);
}
/* ========== DO HARD WORK when REALLOCATING ========== */
/**
* @notice Executes do hard work of specified strategies if reallocation is in progress.
*
* @dev
* Requirements:
*
* - caller must be a valid do hard worker
* - provided strategies must be valid
* - reallocation is pending for current index
* - at least one strategy must be processed
* - the system should not be paused
*
* @param withdrawData Reallocation values addressing withdrawal part of the reallocation DHW
* @param depositData Reallocation values addressing deposit part of the reallocation DHW
* @param allStrategies Array of all strategy addresses in the system for current set reallocation
* @param isOneTransaction Flag denoting if the DHW should execute in one transaction
*/
function batchDoHardWorkReallocation(
ReallocationWithdrawData memory withdrawData,
ReallocationData memory depositData,
address[] memory allStrategies,
bool isOneTransaction
) external systemNotPaused onlyDoHardWorker verifyReallocationStrategies(allStrategies) {
if (_isBatchComplete()) {
globalIndex++;
doHardWorksLeft = uint8(allStrategies.length);
withdrawalDoHardWorksLeft = uint8(allStrategies.length);
}
// verify reallocation is set for the current index, and not disabled
require(
reallocationIndex == globalIndex &&
reallocationTableHash != 0,
"XNRLC"
);
// add all indexes if DHW is in one transaction
if (isOneTransaction) {
require(
withdrawData.stratIndexes.length == allStrategies.length &&
depositData.stratIndexes.length == allStrategies.length,
"1TX"
);
} else {
require(!forceOneTxDoHardWork, "F1TX");
require(withdrawData.stratIndexes.length > 0 || depositData.stratIndexes.length > 0, "NOSTR");
}
// execute deposits and withdrawals
_batchDoHardWorkReallocation(withdrawData, depositData, allStrategies);
// update if DHW for index finished
_finishDhw(true);
}
/**
* @notice Executes do hard work of specified strategies if reallocation is in progress.
* @param withdrawData Reallocation values addressing withdrawal part of the reallocation DHW
* @param depositData Reallocation values addressing deposit part of the reallocation DHW
* @param allStrategies Array of all strategy addresses in the system for current set reallocation
*/
function _batchDoHardWorkReallocation(
ReallocationWithdrawData memory withdrawData,
ReallocationData memory depositData,
address[] memory allStrategies
) private {
// WITHDRAWALS
// reallocation withdraw
// process users deposit and withdrawals
if (withdrawData.stratIndexes.length > 0) {
// check parameters
require(
withdrawData.stratIndexes.length == withdrawData.slippages.length &&
withdrawalDoHardWorksLeft >= withdrawData.stratIndexes.length,
"BWI"
);
// verify if reallocation table matches the reallocationtable hash
_verifyReallocationTable(withdrawData.reallocationTable);
// get current strategy price data
// this is later used to calculate the amount that can me matched
// between 2 strategies when they deposit in eachother
PriceData[] memory spotPrices = _getPriceData(withdrawData, allStrategies);
// process the withdraw part of the reallocation
// process the deposit and the withdrawal part of the users deposits/withdrawals
_processWithdraw(
withdrawData,
allStrategies,
spotPrices
);
// update number of strategies needing to be processed for the current reallocation DHW
// can continue to deposit only when it reaches 0
_updateWithdrawalDohardWorksleft(withdrawData.stratIndexes.length);
}
// check if withdrawal phase was finished before starting deposit
require(
!(depositData.stratIndexes.length > 0 && withdrawalDoHardWorksLeft > 0),
"WNF"
);
// DEPOSITS
// deposit reallocated amounts withdrawn above into strategies
if (depositData.stratIndexes.length > 0) {
// check parameters
require(
doHardWorksLeft >= depositData.stratIndexes.length &&
depositData.stratIndexes.length == depositData.slippages.length,
"BDI"
);
// deposit reallocated amounts into strategies
// this only deals with the reallocated amounts as users were already processed in the withdrawal phase
for (uint128 i = 0; i < depositData.stratIndexes.length; i++) {
uint256 stratIndex = depositData.stratIndexes[i];
address stratAddress = allStrategies[stratIndex];
Strategy storage strategy = strategies[stratAddress];
// verify the strategy was not removed (it could be removed in the middle of the DHW if the DHW was executed in multiple transactions)
_notRemoved(stratAddress);
require(strategy.isInDepositPhase, "SWNP");
// deposit reallocation withdrawn amounts according to the calculations
_doHardWorkDeposit(stratAddress, depositData.slippages[stratIndex]);
// mark strategy as finished for the current index
_finishStrategyDoHardWork(stratAddress);
// remove the flag indicating strategy should deposit reallocated amount
strategy.isInDepositPhase = false;
}
// update number of strategies left in the current index
// if this reaches 0, DHW is considered complete
_updateDoHardWorksLeft(depositData.stratIndexes.length);
}
}
/**
* @notice Executes user process and withdraw part of the do-hard-work for the specified strategies when reallocation is in progress.
* @param withdrawData Reallocation values addressing withdrawal part of the reallocation DHW
* @param allStrategies Array of all strategy addresses in the system for current set reallocation
* @param spotPrices current strategy share price data, used to calculate the amount that can me matched between 2 strategies when reallcating
*/
function _processWithdraw(
ReallocationWithdrawData memory withdrawData,
address[] memory allStrategies,
PriceData[] memory spotPrices
) private {
// go over reallocation table and calculate what amount of shares can be optimized when reallocating
// we can optimize if two strategies deposit into eachother. With the `spotPrices` we can compare the strategy values.
ReallocationShares memory reallocation = _optimizeReallocation(withdrawData, spotPrices);
// go over withdrawals
for (uint256 i = 0; i < withdrawData.stratIndexes.length; i++) {
uint256 stratIndex = withdrawData.stratIndexes[i];
address stratAddress = allStrategies[stratIndex];
Strategy storage strategy = strategies[stratAddress];
_notRemoved(stratAddress);
require(!strategy.isInDepositPhase, "SWP");
uint128 withdrawnReallocationReceived;
{
uint128 sharesToWithdraw = reallocation.totalSharesWithdrawn[stratIndex] - reallocation.optimizedShares[stratIndex];
ProcessReallocationData memory processReallocationData = ProcessReallocationData(
sharesToWithdraw,
reallocation.optimizedShares[stratIndex],
reallocation.optimizedWithdraws[stratIndex]
);
// withdraw reallocation / returns non-optimized withdrawn amount
withdrawnReallocationReceived = _doHardWorkReallocation(stratAddress, withdrawData.slippages[stratIndex], processReallocationData);
}
// reallocate withdrawn to other strategies
_depositReallocatedAmount(
reallocation.totalSharesWithdrawn[stratIndex],
withdrawnReallocationReceived,
reallocation.optimizedWithdraws[stratIndex],
allStrategies,
withdrawData.reallocationTable[stratIndex]
);
_updatePending(stratAddress);
strategy.isInDepositPhase = true;
}
}
/**
* @notice Process strategy DHW, including reallocation
* @dev Only executed when reallocation is set for the DHW
* @param strat Strategy address
* @param slippages Array of slippage values
* @param processReallocationData Reallocation data (see ProcessReallocationData)
* @return Received withdrawn reallocation
*/
function _doHardWorkReallocation(
address strat,
uint256[] memory slippages,
ProcessReallocationData memory processReallocationData
) private returns(uint128){
Strategy storage strategy = strategies[strat];
// Check if strategy wasn't exected in current index yet
require(strategy.index < globalIndex, "SFIN");
uint128 withdrawnReallocationReceived = _processReallocation(strat, slippages, processReallocationData);
return withdrawnReallocationReceived;
}
/**
* @notice Process deposit collected form the reallocation
* @dev Only executed when reallocation is set for the DHW
* @param strat Strategy address
* @param slippages Array of slippage values
*/
function _doHardWorkDeposit(
address strat,
uint256[] memory slippages
) private {
_processDeposit(strat, slippages);
}
/**
* @notice Calculate amount of shares that can be swapped between a pair of strategies (without withdrawing from the protocols)
*
* @dev This is done to ensure only the necessary amoun gets withdrawn from protocols and lower the total slippage and fee.
* NOTE: We know strategies depositing into eachother must have the same underlying asset
* The underlying asset is used to compare the amount ob both strategies withdrawing (depositing) into eachother.
*
* Returns:
* - amount of optimized collateral amount for each strategy
* - amount of optimized shares for each strategy
* - total non-optimized amount of shares for each strategy
*
* @param withdrawData Withdraw data (see WithdrawData)
* @param priceData An array of price data (see PriceData)
* @return reallocationShares Containing arrays showing the optimized share and underlying token amounts
*/
function _optimizeReallocation(
ReallocationWithdrawData memory withdrawData,
PriceData[] memory priceData
) private pure returns (ReallocationShares memory) {
// amount of optimized collateral amount for each strategy
uint128[] memory optimizedWithdraws = new uint128[](withdrawData.reallocationTable.length);
// amount of optimized shares for each strategy
uint128[] memory optimizedShares = new uint128[](withdrawData.reallocationTable.length);
// total non-optimized amount of shares for each strategy
uint128[] memory totalShares = new uint128[](withdrawData.reallocationTable.length);
// go over all the strategies (over reallcation table)
for (uint128 i = 0; i < withdrawData.reallocationTable.length; i++) {
for (uint128 j = i + 1; j < withdrawData.reallocationTable.length; j++) {
// check if both strategies are depositing to eachother, if yes - optimize
if (withdrawData.reallocationTable[i][j] > 0 && withdrawData.reallocationTable[j][i] > 0) {
// calculate strategy I underlying collateral amout withdrawing
uint128 amountI = uint128(withdrawData.reallocationTable[i][j] * priceData[i].totalValue / priceData[i].totalShares);
// calculate strategy I underlying collateral amout withdrawing
uint128 amountJ = uint128(withdrawData.reallocationTable[j][i] * priceData[j].totalValue / priceData[j].totalShares);
uint128 optimizedAmount;
// check which strategy is withdrawing less
if (amountI > amountJ) {
optimizedAmount = amountJ;
} else {
optimizedAmount = amountI;
}
// use the lesser value of both to save maximum possible optimized amount withdrawing
optimizedWithdraws[i] += optimizedAmount;
optimizedWithdraws[j] += optimizedAmount;
}
// sum total shares withdrawing for each strategy
unchecked {
totalShares[i] += uint128(withdrawData.reallocationTable[i][j]);
totalShares[j] += uint128(withdrawData.reallocationTable[j][i]);
}
}
// If we optimized for a strategy, calculate the total shares optimized back from the collateral amount.
// The optimized shares amount will never be withdrawn from the strategy, as we know other strategies are
// depositing to the strategy in the equal amount and we know how to mach them.
if (optimizedWithdraws[i] > 0) {
optimizedShares[i] = Math.getProportion128(optimizedWithdraws[i], priceData[i].totalShares, priceData[i].totalValue);
}
}
ReallocationShares memory reallocationShares = ReallocationShares(
optimizedWithdraws,
optimizedShares,
totalShares
);
return reallocationShares;
}
/**
* @notice Get urrent strategy price data, containing total balance and total shares
* @dev Also verify if the total strategy value is according to the defined values
*
* @param withdrawData Withdraw data (see WithdrawData)
* @param allStrategies Array of strategy addresses
* @return Price data (see PriceData)
*/
function _getPriceData(
ReallocationWithdrawData memory withdrawData,
address[] memory allStrategies
) private returns(PriceData[] memory) {
PriceData[] memory spotPrices = new PriceData[](allStrategies.length);
for (uint128 i = 0; i < allStrategies.length; i++) {
// claim rewards before getting the price
if (withdrawData.rewardSlippages[i].doClaim) {
_claimRewards(allStrategies[i], withdrawData.rewardSlippages[i].swapData);
}
for (uint128 j = 0; j < allStrategies.length; j++) {
// if a strategy is withdrawing in reallocation get its spot price
if (withdrawData.reallocationTable[i][j] > 0) {
// if strategy is removed treat it's value as 0
if (!strategies[allStrategies[i]].isRemoved) {
spotPrices[i].totalValue = _getStratValue(allStrategies[i]);
}
spotPrices[i].totalShares = strategies[allStrategies[i]].totalShares;
require(
spotPrices[i].totalValue >= withdrawData.priceSlippages[i].min &&
spotPrices[i].totalValue <= withdrawData.priceSlippages[i].max,
"BPRC"
);
break;
}
}
}
return spotPrices;
}
/**
* @notice Processes reallocated amount deposits.
* @param reallocateSharesToWithdraw Reallocate shares to withdraw
* @param withdrawnReallocationReceived Received withdrawn reallocation
* @param optimizedWithdraw Optimized withdraw
* @param _strategies Array of strategy addresses
* @param stratReallocationShares Array of strategy reallocation shares
*/
function _depositReallocatedAmount(
uint128 reallocateSharesToWithdraw,
uint128 withdrawnReallocationReceived,
uint128 optimizedWithdraw,
address[] memory _strategies,
uint256[] memory stratReallocationShares
) private {
for (uint256 i = 0; i < stratReallocationShares.length; i++) {
if (stratReallocationShares[i] > 0) {
Strategy storage depositStrategy = strategies[_strategies[i]];
// add actual withdrawn deposit
depositStrategy.pendingReallocateDeposit +=
Math.getProportion128(withdrawnReallocationReceived, stratReallocationShares[i], reallocateSharesToWithdraw);
// add optimized deposit
depositStrategy.pendingReallocateOptimizedDeposit +=
Math.getProportion128(optimizedWithdraw, stratReallocationShares[i], reallocateSharesToWithdraw);
}
}
}
/* ========== SHARED FUNCTIONS ========== */
/**
* @notice After strategy DHW is complete increment strategy index
* @param strat Strategy address
*/
function _finishStrategyDoHardWork(address strat) private {
Strategy storage strategy = strategies[strat];
strategy.index++;
emit DoHardWorkStrategyCompleted(strat, strategy.index);
}
/**
* @notice After strategy DHW process update strategy pending values
* @dev set pending next as pending and reset pending next
* @param strat Strategy address
*/
function _updatePending(address strat) private {
Strategy storage strategy = strategies[strat];
Pending memory pendingUserNext = strategy.pendingUserNext;
strategy.pendingUser = pendingUserNext;
if (
pendingUserNext.deposit != Max128Bit.ZERO ||
pendingUserNext.sharesToWithdraw != Max128Bit.ZERO
) {
strategy.pendingUserNext = Pending(Max128Bit.ZERO, Max128Bit.ZERO);
}
}
/**
* @notice Update the number of "do hard work" processes left.
* @param processedCount Number of completed actions
*/
function _updateDoHardWorksLeft(uint256 processedCount) private {
doHardWorksLeft -= uint8(processedCount);
}
/**
* @notice Update the number of "withdrawal do hard work" processes left.
* @param processedCount Number of completed actions
*/
function _updateWithdrawalDohardWorksleft(uint256 processedCount) private {
withdrawalDoHardWorksLeft -= uint8(processedCount);
}
/**
* @notice Hash a reallocation table after it was updated
* @param reallocationTable 2D table showing amount of shares withdrawing to each strategy
*/
function _hashReallocationTable(uint256[][] memory reallocationTable) internal {
reallocationTableHash = Hash.hashReallocationTable(reallocationTable);
if (logReallocationTable) {
// this is only meant to be emitted when debugging
emit ReallocationTableUpdatedWithTable(reallocationIndex, reallocationTableHash, reallocationTable);
} else {
emit ReallocationTableUpdated(reallocationIndex, reallocationTableHash);
}
}
/**
* @notice Calculate and store the hash of the given strategy array
* @param strategies Strategy addresses to hash
*/
function _hashReallocationStrategies(address[] memory strategies) internal {
reallocationStrategiesHash = Hash.hashStrategies(strategies);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
// extends
import "../interfaces/spool/ISpoolExternal.sol";
import "./SpoolReallocation.sol";
/**
* @notice Exposes spool functions to set and redeem actions.
*
* @dev
* Most of the functions are restricted to vaults. The action is
* recorded in the buffer system and is processed at the next
* do hard work.
* A user cannot interact with any of the Spool functions directly.
*
* Complete interaction with Spool consists of 4 steps
* 1. deposit
* 2. redeem shares
* 3. withdraw
* 4. redeem underlying asset
*
* Redeems (step 2. and 4.) are done at the same time. Redeem is
* processed automatically on first vault interaction after the DHW
* is completed.
*
* As the system works asynchronously, between every step
* a do hard work needs to be executed. The shares and actual
* withdrawn amount are only calculated at the time of action (DHW).
*/
abstract contract SpoolExternal is ISpoolExternal, SpoolReallocation {
using Bitwise for uint256;
using SafeERC20 for IERC20;
using Max128Bit for uint128;
/* ========== DEPOSIT ========== */
/**
* @notice Allows a vault to queue a deposit to a strategy.
*
* @dev
* Requirements:
*
* - the caller must be a vault
* - strategy shouldn't be removed
*
* @param strat Strategy address to deposit to
* @param amount Amount to deposit
* @param index Global index vault is depositing at (active global index)
*/
function deposit(address strat, uint128 amount, uint256 index)
external
override
onlyVault
notRemoved(strat)
{
Strategy storage strategy = strategies[strat];
Pending storage strategyPending = _getStrategyPending(strategy, index);
Vault storage vault = strategy.vaults[msg.sender];
VaultBatch storage vaultBatch = vault.vaultBatches[index];
// save to storage
strategyPending.deposit = strategyPending.deposit.add(amount);
vaultBatch.deposited += amount;
}
/* ========== WITHDRAW ========== */
/**
* @notice Allows a vault to queue a withdrawal from a strategy.
*
* @dev
* Requirements:
*
* - the caller must be a vault
* - strategy shouldn't be removed
*
* @param strat Strategy address to withdraw from
* @param vaultProportion Proportion of all vault-strategy shares a vault wants to withdraw, denoted in basis points (10_000 is 100%)
* @param index Global index vault is depositing at (active global index)
*/
function withdraw(address strat, uint256 vaultProportion, uint256 index)
external
override
onlyVault
{
Strategy storage strategy = strategies[strat];
Pending storage strategyPending = _getStrategyPending(strategy, index);
Vault storage vault = strategy.vaults[msg.sender];
VaultBatch storage vaultBatch = vault.vaultBatches[index];
// calculate new shares to withdraw
uint128 sharesToWithdraw = Math.getProportion128(vault.shares, vaultProportion, ACCURACY);
// save to storage
strategyPending.sharesToWithdraw = strategyPending.sharesToWithdraw.add(sharesToWithdraw);
vaultBatch.withdrawnShares += sharesToWithdraw;
}
/* ========== DEPOSIT/WITHDRAW SHARED ========== */
/**
* @notice Get strategy pending struct, depending on if the strategy do hard work has already been executed in the current index
* @param strategy Strategy data (see Strategy struct)
* @param interactingIndex Global index for which to get the struct
* @return pending Storage struct containing all unprocessed deposits and withdrawals for the `interactingIndex`
*/
function _getStrategyPending(Strategy storage strategy, uint256 interactingIndex) private view returns (Pending storage pending) {
// if index we are interacting with (active global index) is same as strategy index, then DHW has already been executed in index
if (_isNextStrategyIndex(strategy, interactingIndex)) {
pending = strategy.pendingUser;
} else {
pending = strategy.pendingUserNext;
}
}
/* ========== REDEEM ========== */
/**
* @notice Allows a vault to redeem deposit and withdrawals for the processed index.
* @dev
*
* Requirements:
*
* - the caller must be a valid vault
*
* @param strat Strategy address
* @param index Global index the vault is redeeming for
* @return Received vault received shares from the deposit and received vault underlying withdrawn amounts
*/
function redeem(address strat, uint256 index)
external
override
onlyVault
returns (uint128, uint128)
{
Strategy storage strategy = strategies[strat];
Batch storage batch = strategy.batches[index];
Vault storage vault = strategy.vaults[msg.sender];
VaultBatch storage vaultBatch = vault.vaultBatches[index];
uint128 vaultBatchDeposited = vaultBatch.deposited;
uint128 vaultBatchWithdrawnShares = vaultBatch.withdrawnShares;
uint128 vaultDepositReceived = 0;
uint128 vaultWithdrawnReceived = 0;
uint128 vaultShares = vault.shares;
// Make calculations if deposit in vault batch was performed
if (vaultBatchDeposited > 0 && batch.deposited > 0) {
vaultDepositReceived = Math.getProportion128(batch.depositedReceived, vaultBatchDeposited, batch.deposited);
// calculate new vault-strategy shares
// new shares are calculated at the DHW time, here vault only
// takes the proportion of the vault deposit compared to the total deposit
vaultShares += Math.getProportion128(batch.depositedSharesReceived, vaultBatchDeposited, batch.deposited);
// reset to 0 to get the gas reimbursement
vaultBatch.deposited = 0;
}
// Make calculations if withdraw in vault batch was performed
if (vaultBatchWithdrawnShares > 0 && batch.withdrawnShares > 0) {
// Withdrawn recieved represents the total underlying a strategy got back after DHW has processed the withdrawn shares.
// This is stored at the DHW time, here vault only takes the proportion
// of the vault shares withdrwan compared to the total shares withdrawn
vaultWithdrawnReceived = Math.getProportion128(batch.withdrawnReceived, vaultBatchWithdrawnShares, batch.withdrawnShares);
// substract all the shares withdrawn in the index after collecting the withdrawn recieved
vaultShares -= vaultBatchWithdrawnShares;
// reset to 0 to get the gas reimbursement
vaultBatch.withdrawnShares = 0;
}
// store the updated shares
vault.shares = vaultShares;
return (vaultDepositReceived, vaultWithdrawnReceived);
}
/**
* @notice Redeem underlying token
* @dev
* This function is only called by the vault after the vault redeem is processed
* As redeem is called by each strategy separately, we don't want to transfer the
* withdrawn underlyin tokens x amount of times.
*
* Requirements:
* - Can only be invoked by vault
*
* @param amount Amount to redeem
*/
function redeemUnderlying(uint128 amount) external override onlyVault {
IVault(msg.sender).underlying().safeTransfer(msg.sender, amount);
}
/* ========== REDEEM REALLOCATION ========== */
/**
* @notice Redeem vault shares after reallocation has been processed for the vault
* @dev
*
* Requirements:
* - Can only be invoked by vault
*
* @param vaultStrategies Array of vault strategy addresses
* @param depositProportions Values representing how the vault has deposited it's withdrawn shares
* @param index Index at which the reallocation was perofmed
*/
function redeemReallocation(
address[] memory vaultStrategies,
uint256 depositProportions,
uint256 index
) external override onlyVault {
// count number of strategies we deposit into
uint128 depositStratsCount = 0;
for (uint256 i = 0; i < vaultStrategies.length; i++) {
uint256 prop = depositProportions.get14BitUintByIndex(i);
if (prop > 0) {
depositStratsCount++;
}
}
// init deposit and withdrawal strategy arrays
address[] memory withdrawStrats = new address[](vaultStrategies.length - depositStratsCount);
address[] memory depositStrats = new address[](depositStratsCount);
uint256[] memory depositProps = new uint256[](depositStratsCount);
// fill deposit and withdrawal strategy arrays
{
uint128 k = 0;
uint128 l = 0;
for (uint256 i = 0; i < vaultStrategies.length; i++) {
uint256 prop = depositProportions.get14BitUintByIndex(i);
if (prop > 0) {
depositStrats[k] = vaultStrategies[i];
depositProps[k] = prop;
k++;
} else {
withdrawStrats[l] = vaultStrategies[i];
l++;
}
}
}
uint256 totalVaultWithdrawnReceived = 0;
// calculate total withdrawal amount
for (uint256 i = 0; i < withdrawStrats.length; i++) {
Strategy storage strategy = strategies[withdrawStrats[i]];
BatchReallocation storage reallocationBatch = strategy.reallocationBatches[index];
Vault storage vault = strategy.vaults[msg.sender];
// if we withdrawed from strategy, claim and spread across deposits
uint256 vaultWithdrawnReallocationShares = vault.withdrawnReallocationShares;
if (vaultWithdrawnReallocationShares > 0) {
// if batch withdrawn shares is 0, reallocation was canceled as a strategy was removed
// if so, skip calculation and reset withdrawn reallcoation shares to 0
if (reallocationBatch.withdrawnReallocationShares > 0) {
totalVaultWithdrawnReceived +=
(reallocationBatch.withdrawnReallocationReceived * vaultWithdrawnReallocationShares) / reallocationBatch.withdrawnReallocationShares;
// substract the shares withdrawn from in the reallocation
vault.shares -= uint128(vaultWithdrawnReallocationShares);
}
vault.withdrawnReallocationShares = 0;
}
}
// calculate how the withdrawn amount was deposited to the depositing strategies
uint256 vaultWithdrawnReceivedLeft = totalVaultWithdrawnReceived;
uint256 lastDepositStratIndex = depositStratsCount - 1;
for (uint256 i = 0; i < depositStratsCount; i++) {
Strategy storage depositStrategy = strategies[depositStrats[i]];
Vault storage depositVault = depositStrategy.vaults[msg.sender];
BatchReallocation storage reallocationBatch = depositStrategy.reallocationBatches[index];
if (reallocationBatch.depositedReallocation > 0) {
// calculate reallocation strat deposit amount
uint256 depositAmount;
// if the strategy is last among the depositing ones, use the amount left to calculate the new shares
// (same pattern was used when distributing the withdrawn shares to the depositing strategies - last strategy got what was left of shares)
if (i < lastDepositStratIndex) {
depositAmount = (totalVaultWithdrawnReceived * depositProps[i]) / FULL_PERCENT;
vaultWithdrawnReceivedLeft -= depositAmount;
} else { // if strat is last, use deposit left
depositAmount = vaultWithdrawnReceivedLeft;
}
// based on calculated deposited amount calculate/redeem the new strategy shares belonging to a vault
depositVault.shares +=
SafeCast.toUint128((reallocationBatch.depositedReallocationSharesReceived * depositAmount) / reallocationBatch.depositedReallocation);
}
}
}
/* ========== FAST WITHDRAW ========== */
/**
* @notice Instantly withdraw shares from a strategy and return recieved underlying tokens.
* @dev
* User can execute the withdrawal of his shares from the vault at any time (except when
* the reallocation is pending) without waiting for the DHW to process it. This is done
* independently of other events. The gas cost is paid entirely by the user.
* Withdrawn amount is sent back to the caller (FastWithdraw) contract, that later on,
* sends it to a user.
*
* Requirements:
*
* - the caller must be a fast withdraw contract
* - strategy shouldn't be removed
*
* @param strat Strategy address
* @param underlying Address of underlying asset
* @param shares Amount of shares to withdraw
* @param slippages Strategy slippage values verifying the validity of the strategy state
* @param swapData Array containig data to swap unclaimed strategy reward tokens for underlying asset
* @return Withdrawn Underlying asset withdrarn amount
*/
function fastWithdrawStrat(
address strat,
address underlying,
uint256 shares,
uint256[] memory slippages,
SwapData[] memory swapData
)
external
override
onlyFastWithdraw
notRemoved(strat)
returns(uint128)
{
// returns withdrawn amount
return _fastWithdrawStrat(strat, underlying, shares, slippages, swapData);
}
/* ========== REMOVE SHARES (prepare for fast withdraw) ========== */
/**
* @notice Remove vault shares.
*
* @dev
* Called by the vault when a user requested a fast withdraw
* These shares are either withdrawn from the strategies immidiately or
* stored as user-strategy shares in the FastWithdraw contract.
*
* Requirements:
*
* - can only be called by the vault
*
* @param vaultStrategies Array of strategy addresses
* @param vaultProportion Proportion of all vault-strategy shares a vault wants to remove, denoted in basis points (10_000 is 100%)
* @return Array of removed shares per strategy
*/
function removeShares(
address[] memory vaultStrategies,
uint256 vaultProportion
)
external
override
onlyVault
returns(uint128[] memory)
{
uint128[] memory removedShares = new uint128[](vaultStrategies.length);
for (uint128 i = 0; i < vaultStrategies.length; i++) {
_notRemoved(vaultStrategies[i]);
Strategy storage strategy = strategies[vaultStrategies[i]];
Vault storage vault = strategy.vaults[msg.sender];
uint128 sharesToWithdraw = Math.getProportion128(vault.shares, vaultProportion, ACCURACY);
removedShares[i] = sharesToWithdraw;
vault.shares -= sharesToWithdraw;
}
return removedShares;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
// extends
import "../interfaces/spool/ISpoolReallocation.sol";
import "./SpoolDoHardWork.sol";
// libraries
import "../libraries/Bitwise.sol";
// other imports
import "../interfaces/IVault.sol";
/**
* @notice Spool part of implementation dealing with the reallocation of assets
*
* @dev
* Allocation provider can update vault allocation across strategies.
* This requires vault to withdraw from some and deposit to other strategies.
* This happens across multiple vaults. The system handles all vault reallocations
* at once and optimizes it between eachother and users.
*
*/
abstract contract SpoolReallocation is ISpoolReallocation, SpoolDoHardWork {
using Bitwise for uint256;
/* ========== SET REALLOCATION ========== */
/**
* @notice Set vaults to reallocate on next do hard work
* Requirements:
* - Caller must have allocation provider role
* - Vaults array must not be empty
* - Vaults must be valid
* - Strategies must be valid
* - If reallocation was already initialized before:
* - Reallocation table hash must be set
* - Reallocation table must be valid
*
* @param vaults Array of vault addresses
* @param strategies Array of strategy addresses
* @param reallocationTable Reallocation details
*/
function reallocateVaults(
VaultData[] memory vaults,
address[] memory strategies,
uint256[][] memory reallocationTable
) external onlyAllocationProvider {
require(vaults.length > 0, "NOVRLC");
uint24 activeGlobalIndex = getActiveGlobalIndex();
// If reallocation was already initialized before,
// verify state and parameters before continuing
if (reallocationIndex > 0) {
// If reallocation was started for index and table hash is 0,
// the reallocation was canceled. Prevent from setting it in same index again.
require(reallocationTableHash != 0, "RLCSTP");
// check if reallocation can still be set for same global index as before
require(reallocationIndex == activeGlobalIndex, "RLCINP");
// verifies strategies agains current reallocation strategies hash
_verifyReallocationStrategies(strategies);
_verifyReallocationTable(reallocationTable);
} else { // if new reallocation, init empty reallocation shares table
// verifies all system strategies using Controller contract
_verifyStrategies(strategies);
// hash and save strategies
// this strategies hash is then used to verify strategies during the reallocation
// if the strat is exploited and removed from the system, this hash is used to be consistent
// with reallocation table ordering as system strategies change.
_hashReallocationStrategies(strategies);
reallocationIndex = activeGlobalIndex;
reallocationTable = new uint256[][](strategies.length);
for (uint256 i = 0; i < strategies.length; i++) {
reallocationTable[i] = new uint256[](strategies.length);
}
emit StartReallocation(reallocationIndex);
}
// loop over vaults
for (uint128 i = 0; i < vaults.length; i++) {
// check if address is a valid vault
_isVault(vaults[i].vault);
// reallocate vault
//address[] memory vaultStrategies = _buildVaultStrategiesArray(vaults[i].strategiesBitwise, vaults[i].strategiesCount, strategies);
(uint256[] memory withdrawProportions, uint256 depositProportions) =
IVault(vaults[i].vault).reallocate(
_buildVaultStrategiesArray(vaults[i].strategiesBitwise, vaults[i].strategiesCount, strategies),
vaults[i].newProportions,
getCompletedGlobalIndex(), // NOTE: move to var if call stack not too deeep
activeGlobalIndex);
// withdraw and deposit from vault strategies
for (uint128 j = 0; j < vaults[i].strategiesCount; j++) {
if (withdrawProportions[j] > 0) {
uint256 withdrawStratIndex = vaults[i].strategiesBitwise.get8BitUintByIndex(j);
(uint128 newSharesWithdrawn) =
_reallocateVaultStratWithdraw(
vaults[i].vault,
strategies[withdrawStratIndex],
withdrawProportions[j],
activeGlobalIndex
);
_updateDepositReallocationForStrat(
newSharesWithdrawn,
vaults[i],
depositProportions,
reallocationTable[withdrawStratIndex]
);
}
}
}
// Hash reallocation proportions
_hashReallocationTable(reallocationTable);
}
/**
* @notice Remove shares from strategy to set them for a reallocation
* @param vaultAddress Vault address
* @param strat Strategy address to remove shares
* @param vaultProportion Proportion of all vault-strategy shares a vault wants to reallocate
* @param index Global index we're reallocating for
* @return newSharesWithdrawn New shares withdrawn fro reallocation
*/
function _reallocateVaultStratWithdraw(
address vaultAddress,
address strat,
uint256 vaultProportion,
uint256 index
)
private returns (uint128 newSharesWithdrawn)
{
Strategy storage strategy = strategies[strat];
Vault storage vault = strategy.vaults[vaultAddress];
VaultBatch storage vaultBatch = vault.vaultBatches[index];
// calculate new shares to withdraw
uint128 unwithdrawnVaultShares = vault.shares - vaultBatch.withdrawnShares;
// if strategy wasn't executed in current batch yet, also substract unprocessed withdrawal shares in current batch
if(!_isNextStrategyIndex(strategy, index)) {
VaultBatch storage vaultBatchPrevious = vault.vaultBatches[index - 1];
unwithdrawnVaultShares -= vaultBatchPrevious.withdrawnShares;
}
// return data
newSharesWithdrawn = Math.getProportion128(unwithdrawnVaultShares, vaultProportion, ACCURACY);
// save to storage
vault.withdrawnReallocationShares = newSharesWithdrawn;
}
/**
* @notice Checks whether the given index is next index for the strategy
* @param strategy Strategy data (see Strategy struct)
* @param interactingIndex Index to check
* @return isNextStrategyIndex True if given index is the next strategy index
*/
function _isNextStrategyIndex(
Strategy storage strategy,
uint256 interactingIndex
) internal view returns (bool isNextStrategyIndex) {
if (strategy.index + 1 == interactingIndex) {
isNextStrategyIndex = true;
}
}
/**
* @notice Update deposit reallocation for strategy
* @param sharesWithdrawn Withdrawn shares
* @param vaultData Vault data (see VaultData struct)
* @param depositProportions Deposit proportions
* @param stratReallocationTable Strategy reallocation table
*/
function _updateDepositReallocationForStrat(
uint128 sharesWithdrawn,
VaultData memory vaultData,
uint256 depositProportions,
uint256[] memory stratReallocationTable
) private pure {
// sharesToDeposit = sharesWithdrawn * deposit_strat%
uint128 sharesWithdrawnleft = sharesWithdrawn;
uint128 lastDepositedIndex = 0;
for (uint128 i = 0; i < vaultData.strategiesCount; i++) {
uint256 stratDepositProportion = depositProportions.get14BitUintByIndex(i);
if (stratDepositProportion > 0) {
uint256 globalStratIndex = vaultData.strategiesBitwise.get8BitUintByIndex(i);
uint128 withdrawnSharesForStrat = Math.getProportion128(sharesWithdrawn, stratDepositProportion, FULL_PERCENT);
stratReallocationTable[globalStratIndex] += withdrawnSharesForStrat;
sharesWithdrawnleft -= withdrawnSharesForStrat;
lastDepositedIndex = i;
}
}
// add shares left from rounding error to last deposit strat
stratReallocationTable[lastDepositedIndex] += sharesWithdrawnleft;
}
/* ========== SHARED ========== */
/**
* @notice Build vault strategies array from a 256bit word.
* @dev Each vault index takes 8bits.
*
* @param bitwiseAddressIndexes Bitwise address indexes
* @param strategiesCount Strategies count
* @param strategies Array of strategy addresses
* @return vaultStrategies Array of vault strategy addresses
*/
function _buildVaultStrategiesArray(
uint256 bitwiseAddressIndexes,
uint8 strategiesCount,
address[] memory strategies
) private pure returns(address[] memory vaultStrategies) {
vaultStrategies = new address[](strategiesCount);
for (uint128 i = 0; i < strategiesCount; i++) {
uint256 stratIndex = bitwiseAddressIndexes.get8BitUintByIndex(i);
vaultStrategies[i] = strategies[stratIndex];
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
// extends
import "../interfaces/spool/ISpoolStrategy.sol";
import "./SpoolBase.sol";
// libraries
import "../external/@openzeppelin/token/ERC20/utils/SafeERC20.sol";
import "../libraries/Max/128Bit.sol";
import "../libraries/Math.sol";
// other imports
import "../interfaces/IBaseStrategy.sol";
/**
* @notice Spool part of implementation dealing with strategy related processing
*/
abstract contract SpoolStrategy is ISpoolStrategy, SpoolBase {
using SafeERC20 for IERC20;
/* ========== VIEWS ========== */
/**
* @notice Returns the amount of funds the vault caller has in total
* deployed to a particular strategy.
*
* @dev
* Although not set as a view function due to the delegatecall
* instructions performed by it, its value can be acquired
* without actually executing the function by both off-chain
* and on-chain code via simulating the transaction's execution.
*
* @param strat strategy address
*
* @return amount
*/
function getUnderlying(address strat) external override returns (uint128) {
Strategy storage strategy = strategies[strat];
uint128 totalStrategyShares = strategy.totalShares;
if (totalStrategyShares == 0) return 0;
return Math.getProportion128(_totalUnderlying(strat), strategy.vaults[msg.sender].shares, totalStrategyShares);
}
/**
* @notice Returns total strategy underlying value.
* @param strat Strategy address
* @return Total strategy underlying value
*/
function getStratUnderlying(address strat) external returns (uint128) {
return _totalUnderlying(strat); // deletagecall
}
/**
* @notice Get total vault underlying at index.
*
* @dev
* NOTE: Call ONLY if vault shares are correct for the index.
* Meaning vault has just redeemed for this index or this is current index.
*
* @param strat strategy address
* @param index index in total underlying
* @return Total vault underlying at index
*/
function getVaultTotalUnderlyingAtIndex(address strat, uint256 index) external override view returns(uint128) {
Strategy storage strategy = strategies[strat];
Vault storage vault = strategy.vaults[msg.sender];
TotalUnderlying memory totalUnderlying = strategy.totalUnderlying[index];
if (totalUnderlying.totalShares > 0) {
return Math.getProportion128(totalUnderlying.amount, vault.shares, totalUnderlying.totalShares);
}
return 0;
}
/**
* @notice Yields the total underlying funds of a strategy.
*
* @dev
* The function is not set as view given that it performs a delegate call
* instruction to the strategy.
* @param strategy Strategy address
* @return Total underlying funds
*/
function _totalUnderlying(address strategy)
internal
returns (uint128)
{
bytes memory data = _relay(
strategy,
abi.encodeWithSelector(IBaseStrategy.getStrategyBalance.selector)
);
return abi.decode(data, (uint128));
}
/**
* @notice Get strategy total underlying balance including rewards
* @param strategy Strategy address
* @return strategyBačance Returns strategy balance with the rewards
*/
function _getStratValue(
address strategy
) internal returns(uint128) {
bytes memory data = _relay(
strategy,
abi.encodeWithSelector(
IBaseStrategy.getStrategyUnderlyingWithRewards.selector
)
);
return abi.decode(data, (uint128));
}
/**
* @notice Returns pending rewards for a strategy
* @param strat Strategy for which to return rewards
* @param reward Reward address
* @return Pending rewards
*/
function getPendingRewards(address strat, address reward) external view returns(uint256) {
return strategies[strat].pendingRewards[reward];
}
/**
* @notice Returns strat address in shared strategies mapping for index
* @param sharedKey Shared strategies key
* @param index Strategy addresses index
* @return Strategy address
*/
function getStratSharedAddress(bytes32 sharedKey, uint256 index) external view returns(address) {
return strategiesShared[sharedKey].stratAddresses[index];
}
/* ========== MUTATIVE EXTERNAL FUNCTIONS ========== */
/**
* @notice Adds and initializes a new strategy
*
* @dev
* Requirements:
*
* - the caller must be the controller
* - reallcation must not be pending
* - strategy shouldn't be previously removed
*
* @param strat Strategy to be added
*/
function addStrategy(address strat)
external
override
onlyController
noPendingReallocation
notRemoved(strat)
{
Strategy storage strategy = strategies[strat];
strategy.index = globalIndex;
// init as max zero, so first user interaction will be cheaper (non-zero to non-zero storage change)
strategy.pendingUser = Pending(Max128Bit.ZERO, Max128Bit.ZERO);
strategy.pendingUserNext = Pending(Max128Bit.ZERO, Max128Bit.ZERO);
// initialize strategy specific values
_initializeStrategy(strat);
}
/**
* @notice Disables a strategy by liquidating all actively deployed funds
* within it to its underlying collateral.
*
* @dev
* This function is invoked whenever a strategy is disabled at the controller
* level as an emergency.
*
* Requirements:
*
* - the caller must be the controller
* - strategy shouldn't be previously removed
*
* @param strat strategy being disabled
* @param skipDisable flag to skip executing strategy specific disable function
* NOTE: Should always be false, except if `IBaseStrategy.disable` is failing and there is no other way
*/
function disableStrategy(
address strat,
bool skipDisable
)
external
override
onlyController
notRemoved(strat)
{
if (isMidReallocation()) { // when reallocating
_disableStrategyWhenReallocating(strat);
} else { // no reallocation in progress
_disableStrategyNoReallocation(strat);
}
Strategy storage strategy = strategies[strat];
strategy.isRemoved = true;
if (!skipDisable) {
_disableStrategy(strat);
} else {
_skippedDisable[strat] = true;
}
_awaitingEmergencyWithdraw[strat] = true;
}
/**
* @notice Disable strategy when reallocating
* @param strat Strategy to disable
*/
function _disableStrategyWhenReallocating(address strat) private {
Strategy storage strategy = strategies[strat];
if(strategy.index < globalIndex) {
// is in withdrawal phase
if (!strategy.isInDepositPhase) {
// decrease do hard work withdrawals left
if (withdrawalDoHardWorksLeft > 0) {
withdrawalDoHardWorksLeft--;
}
} else {
// if user withdrawal was already performed, collect withdrawn amount to be emergency withdrawn
// NOTE: `strategy.index + 1` has to be used as the strategy index has not increased yet
_removeNondistributedWithdrawnReceived(strategy, strategy.index + 1);
}
_decreaseDoHardWorksLeft(true);
// save waiting reallocation deposit to be emergency withdrawn
strategy.emergencyPending += strategy.pendingReallocateDeposit;
strategy.pendingReallocateDeposit = 0;
}
}
/**
* @notice Disable strategy when there is no reallocation
* @param strat Strategy to disable
*/
function _disableStrategyNoReallocation(address strat) private {
Strategy storage strategy = strategies[strat];
// check if the strategy has already been processed in ongoing do hard work
if (strategy.index < globalIndex) {
_decreaseDoHardWorksLeft(false);
} else if (!_isBatchComplete()) {
// if user withdrawal was already performed, collect withdrawn amount to be emergency withdrawn
_removeNondistributedWithdrawnReceived(strategy, strategy.index);
}
// if reallocation is set to be processed, reset reallocation table to cancel it for set index
if (reallocationTableHash != 0) {
reallocationTableHash = 0;
}
}
/**
* @notice Decrease "do hard work" actions left
* @notice isMidReallocation Whether system is mid-reallocation
*/
function _decreaseDoHardWorksLeft(bool isMidReallocation) private {
if (doHardWorksLeft > 0) {
doHardWorksLeft--;
// check if this was last strategy, to complete the do hard work
_finishDhw(isMidReallocation);
}
}
/**
* @notice Removes the nondistributed amounts recieved, if any
* @dev used when emergency withdrawing
*
* @param strategy Strategy address
* @param index index remove from
*/
function _removeNondistributedWithdrawnReceived(Strategy storage strategy, uint256 index) private {
strategy.emergencyPending += strategy.batches[index].withdrawnReceived;
strategy.batches[index].withdrawnReceived = 0;
strategy.totalUnderlying[index].amount = 0;
}
/**
* @notice Liquidating all actively deployed funds within a strategy after it was disabled.
*
* @dev
* Requirements:
*
* - the caller must be the controller
* - the strategy must be disabled
* - the strategy must be awaiting emergency withdraw
*
* @param strat strategy being disabled
* @param data data to perform the withdrawal
* @param withdrawRecipient recipient of the withdrawn funds
*/
function emergencyWithdraw(
address strat,
address withdrawRecipient,
uint256[] memory data
)
external
override
onlyController
onlyRemoved(strat)
{
if (_awaitingEmergencyWithdraw[strat]) {
_emergencyWithdraw(strat, withdrawRecipient, data);
_awaitingEmergencyWithdraw[strat] = false;
} else if (strategies[strat].emergencyPending > 0) {
IBaseStrategy(strat).underlying().transfer(withdrawRecipient, strategies[strat].emergencyPending);
strategies[strat].emergencyPending = 0;
}
}
/**
* @notice Runs strategy specific disable function if it was skipped when disabling the strategy.
* Requirements:
* - the caller must be the controller
* - the strategy must be disabled
*
* @param strat Strategy to remove
*/
function runDisableStrategy(address strat)
external
override
onlyController
onlyRemoved(strat)
{
require(_skippedDisable[strat], "SDEX");
_disableStrategy(strat);
_skippedDisable[strat] = false;
}
/* ========== MUTATIVE INTERNAL FUNCTIONS ========== */
/**
* @notice Invokes the process function on the strategy to process teh pending actions
* @dev executed deposit or withdrawal and compound of the reward tokens
*
* @param strategy Strategy address
* @param slippages Array of slippage parameters to apply when depositing or withdrawing
* @param harvestRewards Whether to harvest (swap and deposit) strategy rewards or not
* @param swapData Array containig data to swap unclaimed strategy reward tokens for underlying asset
*/
function _process(
address strategy,
uint256[] memory slippages,
bool harvestRewards,
SwapData[] memory swapData
) internal {
_relay(
strategy,
abi.encodeWithSelector(
IBaseStrategy.process.selector,
slippages,
harvestRewards,
swapData
)
);
}
/**
* @notice Invoke process reallocation for a strategy
* @dev This is the first par of the strategy DHW when reallocating
*
* @param strategy Strategy address
* @param slippages Array of slippage parameters to apply when withdrawing
* @param processReallocationData Reallocation values used when processing
* @return withdrawnUnderlying Actual withdrawn reallocation underlying assets received
*/
function _processReallocation(
address strategy,
uint256[] memory slippages,
ProcessReallocationData memory processReallocationData
) internal returns(uint128) {
bytes memory data = _relay(
strategy,
abi.encodeWithSelector(
IBaseStrategy.processReallocation.selector,
slippages,
processReallocationData
)
);
// return actual withdrawn reallocation underlying assets received
return abi.decode(data, (uint128));
}
/**
* @notice Invoke process deposit for a strategy
* @param strategy Strategy address
* @param slippages Array of slippage parameters to apply when depositing
*/
function _processDeposit(
address strategy,
uint256[] memory slippages
) internal {
_relay(
strategy,
abi.encodeWithSelector(
IBaseStrategy.processDeposit.selector,
slippages
)
);
}
/**
* @notice Invoke fast withdraw for a strategy
* @param strategy Strategy to withdraw from
* @param underlying Asset to withdraw
* @param shares Amount of shares to withdraw
* @param slippages Array of slippage parameters to apply when withdrawing
* @param swapData Swap slippage and path array
* @return Withdrawn amount
*/
function _fastWithdrawStrat(
address strategy,
address underlying,
uint256 shares,
uint256[] memory slippages,
SwapData[] memory swapData
) internal returns(uint128) {
bytes memory data = _relay(
strategy,
abi.encodeWithSelector(
IBaseStrategy.fastWithdraw.selector,
shares,
slippages,
swapData
)
);
(uint128 withdrawnAmount) = abi.decode(data, (uint128));
IERC20(underlying).safeTransfer(msg.sender, withdrawnAmount);
return withdrawnAmount;
}
/**
* @notice Invoke claim rewards for a strategy
* @param strategy Strategy address
* @param swapData Swap slippage and path
*/
function _claimRewards(
address strategy,
SwapData[] memory swapData
) internal {
_relay(
strategy,
abi.encodeWithSelector(
IBaseStrategy.claimRewards.selector,
swapData
)
);
}
/**
* @notice Invokes the emergencyWithdraw function on a strategy
* @param strategy Strategy to which to relay the call to
* @param recipient Address to which to withdraw to
* @param data Strategy specific data to perorm energency withdraw on a strategy
*/
function _emergencyWithdraw(address strategy, address recipient, uint256[] memory data) internal {
_relay(
strategy,
abi.encodeWithSelector(
IBaseStrategy.emergencyWithdraw.selector,
recipient,
data
)
);
}
/**
* @notice Initializes strategy specific values
* @param strategy Strategy to initialize
*/
function _initializeStrategy(address strategy) internal {
_relay(
strategy,
abi.encodeWithSelector(IBaseStrategy.initialize.selector)
);
}
/**
* @notice Cleans strategy specific values after disabling
* @param strategy Strategy to disable
*/
function _disableStrategy(address strategy) internal {
_relay(
strategy,
abi.encodeWithSelector(IBaseStrategy.disable.selector)
);
}
} | Returns strat address in shared strategies mapping for index sharedKey Shared strategies key index Strategy addresses index return Strategy address/ | function getStratSharedAddress(bytes32 sharedKey, uint256 index) external view returns(address) {
return strategiesShared[sharedKey].stratAddresses[index];
}
| 11,832,808 |
./full_match/1/0x5E16CA75000fb2B9d7B1184Fa24fF5D938a345Ef/sources/src/Scribe.sol | @custom:invariant Reverts iff out of gas. @custom:invariant Runtime is Θ(bar). Let signerIndex be the current signer's index read from schnorrData. Let signerPubKey be the public key stored for signerIndex. Let signer be the address of signerPubKey. Let lastSigner be the previous processed signer. Let aggPubKey be the sum of processed signers' public keys. Note that Jacobian coordinates are used. Fail if number signers unequal to bar. Note that requiring equality constrains the verification's runtime from Ω(bar) to Θ(bar). Fail if signer not feed. Aggregate remaining encoded signers. Update Signer Variables. Fail if signer not feed. Fail if signers not strictly monotonically increasing. Note that this prevents double signing attacks and enforces strict ordering. | function _verifySchnorrSignature(
bytes32 message,
SchnorrData calldata schnorrData
) internal view returns (bool, bytes memory) {
uint signerIndex;
LibSecp256k1.Point memory signerPubKey;
address signer;
address lastSigner;
LibSecp256k1.JacobianPoint memory aggPubKey;
uint numberSigners = schnorrData.getSignerIndexLength();
if (numberSigners != bar) {
return (false, _errorBarNotReached(uint8(numberSigners), bar));
}
signerPubKey = _unsafeLoadPubKeyAt(signerIndex);
signer = signerPubKey.toAddress();
if (signerPubKey.isZeroPoint()) {
return (false, _errorSignerNotFeed(signer));
}
for (uint i = 1; i < bar;) {
lastSigner = signer;
signerIndex = schnorrData.getSignerIndex(i);
signerPubKey = _unsafeLoadPubKeyAt(signerIndex);
signer = signerPubKey.toAddress();
if (signerPubKey.isZeroPoint()) {
return (false, _errorSignerNotFeed(signer));
}
if (uint160(lastSigner) >= uint160(signer)) {
return (false, _errorSignersNotOrdered());
}
}
message, schnorrData.signature, schnorrData.commitment
);
if (!ok) {
return (false, _errorSchnorrSignatureInvalid());
}
}
| 17,126,881 |
//██████╗ █████╗ ██╗ █████╗ ██████╗ ██╗███╗ ██╗
//██╔══██╗██╔══██╗██║ ██╔══██╗██╔══██╗██║████╗ ██║
//██████╔╝███████║██║ ███████║██║ ██║██║██╔██╗ ██║
//██╔═══╝ ██╔══██║██║ ██╔══██║██║ ██║██║██║╚██╗██║
//██║ ██║ ██║███████╗██║ ██║██████╔╝██║██║ ╚████║
//╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝╚═╝ ╚═══╝
pragma solidity ^0.7.6;
pragma abicoder v2;
//SPDX-License-Identifier: MIT
import "./IPalLoanToken.sol";
import "./utils/ERC165.sol";
import "./utils/SafeMath.sol";
import "./utils/Strings.sol";
import "./utils/Admin.sol";
import "./IPaladinController.sol";
import "./BurnedPalLoanToken.sol";
import {Errors} from "./utils/Errors.sol";
/** @title palLoanToken contract */
/// @author Paladin
contract PalLoanToken is IPalLoanToken, ERC165, Admin {
using SafeMath for uint;
using Strings for uint;
//Storage
// Token name
string public name;
// Token symbol
string public symbol;
// Token base URI
string public baseURI;
//Incremental index for next token ID
uint256 private index;
uint256 public totalSupply;
// 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 owner to list of owned token ID
mapping(address => uint256[]) private ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private ownedTokensIndex;
// Mapping from token ID to approved address
mapping(uint256 => address) private approvals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private operatorApprovals;
// Paladin controller
IPaladinController public controller;
// Burned Token contract
BurnedPalLoanToken public burnedToken;
// Mapping from token ID to origin PalPool
mapping(uint256 => address) private pools;
// Mapping from token ID to PalLoan address
mapping(uint256 => address) private loans;
//Modifiers
modifier controllerOnly() {
//allows only the Controller and the admin to call the function
require(msg.sender == admin || msg.sender == address(controller), Errors.CALLER_NOT_CONTROLLER);
_;
}
modifier poolsOnly() {
//allows only a PalPool listed in the Controller
require(controller.isPalPool(msg.sender), Errors.CALLER_NOT_ALLOWED_POOL);
_;
}
//Constructor
constructor(address _controller, string memory _baseURI) {
admin = msg.sender;
// ERC721 parameters + storage data
name = "PalLoan Token";
symbol = "PLT";
controller = IPaladinController(_controller);
baseURI = _baseURI;
//Create the Burned version of this ERC721
burnedToken = new BurnedPalLoanToken("burnedPalLoan Token", "bPLT");
}
//Functions
//Required ERC165 function
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
super.supportsInterface(interfaceId);
}
//URI method
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return string(abi.encodePacked(baseURI, tokenId.toString()));
}
/**
* @notice Return the user balance (total number of token owned)
* @param owner Address of the user
* @return uint256 : number of token owned (in this contract only)
*/
function balanceOf(address owner) external view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return balances[owner];
}
/**
* @notice Return owner of the token
* @param tokenId Id of the token
* @return address : owner address
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
address owner = owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @notice Return the tokenId for a given owner and index
* @param tokenIndex Index of the token
* @return uint256 : tokenId
*/
function tokenOfByIndex(address owner, uint256 tokenIndex) external view override returns (uint256) {
require(tokenIndex < balances[owner], "ERC721: token query out of bonds");
return ownedTokens[owner][tokenIndex];
}
/**
* @notice Return owner of the token, even if the token was burned
* @dev Check if the given id has an owner in this contract, and then if it was burned and has an owner
* @param tokenId Id of the token
* @return address : address of the owner
*/
function allOwnerOf(uint256 tokenId) external view override returns (address) {
require(tokenId < index, "ERC721: owner query for nonexistent token");
return owners[tokenId] != address(0) ? owners[tokenId] : burnedToken.ownerOf(tokenId);
}
/**
* @notice Return the address of the palLoan for this token
* @param tokenId Id of the token
* @return address : address of the palLoan
*/
function loanOf(uint256 tokenId) external view override returns(address){
return loans[tokenId];
}
/**
* @notice Return the palPool that issued this token
* @param tokenId Id of the token
* @return address : address of the palPool
*/
function poolOf(uint256 tokenId) external view override returns(address){
return pools[tokenId];
}
/**
* @notice Return the list of all active palLoans owned by the user
* @dev Find all the token owned by the user, and return the list of palLoans linked to the found tokens
* @param owner User address
* @return address[] : list of owned active palLoans
*/
function loansOf(address owner) external view override returns(address[] memory){
require(index > 0);
uint256 tokenCount = balances[owner];
address[] memory result = new address[](tokenCount);
for(uint256 i = 0; i < tokenCount; i++){
result[i] = loans[ownedTokens[owner][i]];
}
return result;
}
/**
* @notice Return the list of all tokens owned by the user
* @dev Find all the token owned by the user
* @param owner User address
* @return uint256[] : list of owned tokens
*/
function tokensOf(address owner) external view override returns(uint256[] memory){
require(index > 0);
return ownedTokens[owner];
}
/**
* @notice Return the list of all active palLoans owned by the user for the given palPool
* @dev Find all the token owned by the user issued by the given Pool, and return the list of palLoans linked to the found tokens
* @param owner User address
* @return address[] : list of owned active palLoans for the given palPool
*/
function loansOfForPool(address owner, address palPool) external view override returns(address[] memory){
require(index > 0);
uint j = 0;
uint256 tokenCount = balances[owner];
address[] memory result = new address[](tokenCount);
for(uint256 i = 0; i < tokenCount; i++){
if(pools[ownedTokens[owner][i]] == palPool){
result[j] = loans[ownedTokens[owner][i]];
j++;
}
}
//put the result in a new array with correct size to avoid 0x00 addresses in the return array
address[] memory filteredResult = new address[](j);
for(uint256 k = 0; k < j; k++){
filteredResult[k] = result[k];
}
return filteredResult;
}
/**
* @notice Return the list of all tokens owned by the user
* @dev Find all the token owned by the user (in this contract and in the Burned contract)
* @param owner User address
* @return uint256[] : list of owned tokens
*/
function allTokensOf(address owner) external view override returns(uint256[] memory){
require(index > 0);
uint256 tokenCount = balances[owner];
uint256 totalCount = tokenCount.add(burnedToken.balanceOf(owner));
uint256[] memory result = new uint256[](totalCount);
uint256[] memory ownerTokens = ownedTokens[owner];
for(uint256 i = 0; i < tokenCount; i++){
result[i] = ownerTokens[i];
}
uint256[] memory burned = burnedToken.tokensOf(owner);
for(uint256 j = tokenCount; j < totalCount; j++){
result[j] = burned[j.sub(tokenCount)];
}
return result;
}
/**
* @notice Return the list of all palLoans (active and closed) owned by the user
* @dev Find all the token owned by the user, and all the burned tokens owned by the user,
* and return the list of palLoans linked to the found tokens
* @param owner User address
* @return address[] : list of owned palLoans
*/
function allLoansOf(address owner) external view override returns(address[] memory){
require(index > 0);
uint256 tokenCount = balances[owner];
uint256 totalCount = tokenCount.add(burnedToken.balanceOf(owner));
address[] memory result = new address[](totalCount);
uint256[] memory ownerTokens = ownedTokens[owner];
for(uint256 i = 0; i < tokenCount; i++){
result[i] = loans[ownerTokens[i]];
}
uint256[] memory burned = burnedToken.tokensOf(owner);
for(uint256 j = tokenCount; j < totalCount; j++){
result[j] = loans[burned[j.sub(tokenCount)]];
}
return result;
}
/**
* @notice Return the list of all palLoans owned by the user for the given palPool
* @dev Find all the token owned by the user issued by the given Pool, and return the list of palLoans linked to the found tokens
* @param owner User address
* @return address[] : list of owned palLoans (active & closed) for the given palPool
*/
function allLoansOfForPool(address owner, address palPool) external view override returns(address[] memory){
require(index > 0);
uint m = 0;
uint256 tokenCount = balances[owner];
uint256 totalCount = tokenCount.add(burnedToken.balanceOf(owner));
address[] memory result = new address[](totalCount);
uint256[] memory ownerTokens = ownedTokens[owner];
for(uint256 i = 0; i < tokenCount; i++){
if(pools[ownerTokens[i]] == palPool){
result[m] = loans[ownerTokens[i]];
m++;
}
}
uint256[] memory burned = burnedToken.tokensOf(owner);
for(uint256 j = tokenCount; j < totalCount; j++){
uint256 burnedId = burned[j.sub(tokenCount)];
if(pools[burnedId] == palPool){
result[m] = loans[burnedId];
m++;
}
}
//put the result in a new array with correct size to avoid 0x00 addresses in the return array
address[] memory filteredResult = new address[](m);
for(uint256 k = 0; k < m; k++){
filteredResult[k] = result[k];
}
return filteredResult;
}
/**
* @notice Check if the token was burned
* @param tokenId Id of the token
* @return bool : true if burned
*/
function isBurned(uint256 tokenId) external view override returns(bool){
return burnedToken.ownerOf(tokenId) != address(0);
}
/**
* @notice Approve the address to spend the token
* @param to Address of the spender
* @param tokenId Id of the token to approve
*/
function approve(address to, uint256 tokenId) external virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @notice Return the approved address for the token
* @param tokenId Id of the token
* @return address : spender's address
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return approvals[tokenId];
}
/**
* @notice Give the operator approval on all tokens owned by the user, or remove it by setting it to false
* @param operator Address of the operator to approve
* @param approved Boolean : give or remove approval
*/
function setApprovalForAll(address operator, bool approved) external virtual override {
require(operator != msg.sender, "ERC721: approve to caller");
operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
/**
* @notice Return true if the operator is approved for the given user
* @param owner Amount of the owner
* @param operator Address of the operator
* @return bool : result
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return operatorApprovals[owner][operator];
}
/**
* @notice Transfer the token from the owner to the recipient (if allowed)
* @param from Address of the owner
* @param to Address of the recipient
* @param tokenId Id of the token
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external virtual override {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @notice Safe transfer the token from the owner to the recipient (if allowed)
* @param from Address of the owner
* @param to Address of the recipient
* @param tokenId Id of the token
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external virtual override {
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
require(_transfer(from, to, tokenId), "ERC721: transfer failed");
}
/**
* @notice Safe transfer the token from the owner to the recipient (if allowed)
* @param from Address of the owner
* @param to Address of the recipient
* @param tokenId Id of the token
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) external virtual override {
_data;
require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved");
require(_transfer(from, to, tokenId), "ERC721: transfer failed");
}
/**
* @notice Mint a new token to the given address
* @dev Mint the new token, and list it with the given palLoan and palPool
* @param to Address of the user to mint the token to
* @param palPool Address of the palPool issuing the token
* @param palLoan Address of the palLoan linked to the token
* @return uint256 : new token Id
*/
function mint(address to, address palPool, address palLoan) external override poolsOnly returns(uint256){
require(palLoan != address(0), Errors.ZERO_ADDRESS);
//Call the internal mint method, and get the new token Id
uint256 newId = _mint(to);
//Set the correct data in mappings for this token
loans[newId] = palLoan;
pools[newId] = palPool;
//Emit the Mint Event
emit NewLoanToken(palPool, to, palLoan, newId);
//Return the new token Id
return newId;
}
/**
* @notice Burn the given token
* @dev Burn the token, and mint the BurnedToken for this token
* @param tokenId Id of the token to burn
* @return bool : success
*/
function burn(uint256 tokenId) external override poolsOnly returns(bool){
address owner = ownerOf(tokenId);
require(owner != address(0), "ERC721: token nonexistant");
//Mint the Burned version of this token
burnedToken.mint(owner, tokenId);
//Emit the correct event
emit BurnLoanToken(pools[tokenId], owner, loans[tokenId], tokenId);
//call the internal burn method
return _burn(owner, tokenId);
}
/**
* @notice Check if a token exists
* @param tokenId Id of the token
* @return bool : true if token exists (active or burned)
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return owners[tokenId] != address(0) || burnedToken.ownerOf(tokenId) != address(0);
}
/**
* @notice Check if the given user is approved for the given token
* @param spender Address of the user to check
* @param tokenId Id of the token
* @return bool : true if approved
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
function _addTokenToOwner(address to, uint tokenId) internal {
uint ownerIndex = balances[to];
ownedTokens[to].push(tokenId);
ownedTokensIndex[tokenId] = ownerIndex;
balances[to] = balances[to].add(1);
}
function _removeTokenToOwner(address from, uint tokenId) internal {
// To prevent any gap in the array, we subsitute the last token with the one to remove,
// and pop the last element in the array
uint256 lastTokenIndex = balances[from].sub(1);
uint256 tokenIndex = ownedTokensIndex[tokenId];
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = ownedTokens[from][lastTokenIndex];
ownedTokens[from][tokenIndex] = lastTokenId;
ownedTokensIndex[lastTokenId] = tokenIndex;
}
delete ownedTokensIndex[tokenId];
ownedTokens[from].pop();
balances[from] = balances[from].sub(1);
}
/**
* @notice Mint the new token
* @param to Address of the user to mint the token to
* @return uint : Id of the new token
*/
function _mint(address to) internal virtual returns(uint) {
require(to != address(0), "ERC721: mint to the zero address");
//Get the new token Id, and increase the global index
uint tokenId = index;
index = index.add(1);
totalSupply = totalSupply.add(1);
//Write this token in the storage
_addTokenToOwner(to, tokenId);
owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
//Return the new token Id
return tokenId;
}
/**
* @notice Burn the given token
* @param owner Address of the token owner
* @param tokenId Id of the token to burn
* @return bool : success
*/
function _burn(address owner, uint256 tokenId) internal virtual returns(bool) {
//Reset the token approval
_approve(address(0), tokenId);
//Update data in storage
totalSupply = totalSupply.sub(1);
_removeTokenToOwner(owner, tokenId);
owners[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
return true;
}
/**
* @notice Transfer the token from the owner to the recipient
* @dev Deposit underlying, and mints palToken for the user
* @param from Address of the owner
* @param to Address of the recipient
* @param tokenId Id of the token
* @return bool : success
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual returns(bool) {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
//Reset token approval
_approve(address(0), tokenId);
//Update storage data
_removeTokenToOwner(from, tokenId);
_addTokenToOwner(to, tokenId);
owners[tokenId] = to;
emit Transfer(from, to, tokenId);
return true;
}
/**
* @notice Approve the given address to spend the token
* @param to Address to approve
* @param tokenId Id of the token to approve
*/
function _approve(address to, uint256 tokenId) internal virtual {
approvals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
//Admin functions
/**
* @notice Set a new Controller
* @dev Loads the new Controller for the Pool
* @param _newController address of the new Controller
*/
function setNewController(address _newController) external override controllerOnly {
controller = IPaladinController(_newController);
}
function setNewBaseURI(string memory _newBaseURI) external override adminOnly {
baseURI = _newBaseURI;
}
} | Return owner of the token, even if the token was burned Check if the given id has an owner in this contract, and then if it was burned and has an owner tokenId Id of the token return address : address of the owner/ | function allOwnerOf(uint256 tokenId) external view override returns (address) {
require(tokenId < index, "ERC721: owner query for nonexistent token");
return owners[tokenId] != address(0) ? owners[tokenId] : burnedToken.ownerOf(tokenId);
}
| 12,938,542 |
// SPDX-License-Identifier: MIT
/**
* Original code taken from: https://github.com/balancer-labs/erc20-redeemable/blob/13d478a043ec7bfce7abefe708d027dfe3e2ea84/merkle/contracts/MerkleRedeem.sol
* Only comments and events were added, some variable names changed for clarity and the compiler version was upgraded to 0.7.x.
*
* @reviewers: [@hbarcelos]
* @auditors: []
* @bounties: []
* @deployments: []
*/
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title Distribution of tokens in a recurrent fashion.
*/
contract MerkleRedeem is Ownable {
/// @dev The address of the token being distributed.
IERC20 public token;
/**
* @dev To be emitted when a claim is made.
* @param _claimant The address of the claimant.
* @param _balance The amount being claimed.
*/
event Claimed(address _claimant, uint256 _balance);
/// @dev The merkle roots of each week. weekMerkleRoots[week].
mapping(uint => bytes32) public weekMerkleRoots;
/// @dev Keeps track of the claim status for the given period and claimant. claimed[period][claimant].
mapping(uint => mapping(address => bool)) public claimed;
/**
* @param _token The address of the token being distributed.
*/
constructor(
address _token
) public {
token = IERC20(_token);
}
/**
* @dev Effectively pays a claimant.
* @param _liquidityProvider The address of the claimant.
* @param _balance The amount being claimed.
*/
function disburse(
address _liquidityProvider,
uint _balance
)
private
{
if (_balance > 0) {
emit Claimed(_liquidityProvider, _balance);
require(token.transfer(_liquidityProvider, _balance), "ERR_TRANSFER_FAILED");
}
}
/**
* @notice Makes a claim for a given claimant in a week.
* @param _liquidityProvider The address of the claimant.
* @param _week The week for the claim.
* @param _claimedBalance The amount being claimed.
* @param _merkleProof The merkle proof for the claim, sorted from the leaf to the root of the tree.
*/
function claimWeek(
address _liquidityProvider,
uint _week,
uint _claimedBalance,
bytes32[] memory _merkleProof
)
public
{
require(!claimed[_week][_liquidityProvider]);
require(verifyClaim(_liquidityProvider, _week, _claimedBalance, _merkleProof), 'Incorrect merkle proof');
claimed[_week][_liquidityProvider] = true;
disburse(_liquidityProvider, _claimedBalance);
}
struct Claim {
// The week the claim is related to.
uint week;
// The amount being claimed.
uint balance;
// The merkle proof for the claim, sorted from the leaf to the root of the tree.
bytes32[] merkleProof;
}
/**
* @notice Makes multiple claims for a given claimant.
* @param _liquidityProvider The address of the claimant.
* @param claims An array of claims containing the week, balance and the merkle proof.
*/
function claimWeeks(
address _liquidityProvider,
Claim[] memory claims
)
public
{
uint totalBalance = 0;
Claim memory claim ;
for(uint i = 0; i < claims.length; i++) {
claim = claims[i];
require(!claimed[claim.week][_liquidityProvider]);
require(verifyClaim(_liquidityProvider, claim.week, claim.balance, claim.merkleProof), 'Incorrect merkle proof');
totalBalance += claim.balance;
claimed[claim.week][_liquidityProvider] = true;
}
disburse(_liquidityProvider, totalBalance);
}
/**
* @notice Gets the claim status for given claimant from `_begin` to `_end` weeks.
* @param _liquidityProvider The address of the claimant.
* @param _begin The week to start with (inclusive).
* @param _end The week to end with (inclusive).
*/
function claimStatus(
address _liquidityProvider,
uint _begin,
uint _end
)
external
view
returns (bool[] memory)
{
uint size = 1 + _end - _begin;
bool[] memory arr = new bool[](size);
for(uint i = 0; i < size; i++) {
arr[i] = claimed[_begin + i][_liquidityProvider];
}
return arr;
}
/**
* @notice Gets all merkle roots for from `_begin` to `_end` weeks.
* @param _begin The week to start with (inclusive).
* @param _end The week to end with (inclusive).
*/
function merkleRoots(
uint _begin,
uint _end
)
external
view
returns (bytes32[] memory)
{
uint size = 1 + _end - _begin;
bytes32[] memory arr = new bytes32[](size);
for(uint i = 0; i < size; i++) {
arr[i] = weekMerkleRoots[_begin + i];
}
return arr;
}
/**
* @notice Verifies a claim.
* @param _liquidityProvider The address of the claimant.
* @param _week The week for the claim.
* @param _claimedBalance The amount being claimed.
* @param _merkleProof The merkle proof for the claim, sorted from the leaf to the root of the tree.
*/
function verifyClaim(
address _liquidityProvider,
uint _week,
uint _claimedBalance,
bytes32[] memory _merkleProof
)
public
view
returns (bool valid)
{
bytes32 leaf = keccak256(abi.encodePacked(_liquidityProvider, _claimedBalance));
return MerkleProof.verify(_merkleProof, weekMerkleRoots[_week], leaf);
}
/**
* @notice Seeds a new round for the airdrop.
* @dev Will transfer tokens from the owner to this contract.
* @param _week The airdrop week.
* @param _merkleRoot The merkle root of the claims for that period.
* @param _totalAllocation The amount of tokens allocated for the distribution.
*/
function seedAllocations(
uint _week,
bytes32 _merkleRoot,
uint _totalAllocation
)
external
onlyOwner
{
require(weekMerkleRoots[_week] == bytes32(0), "cannot rewrite merkle root");
weekMerkleRoots[_week] = _merkleRoot;
require(token.transferFrom(msg.sender, address(this), _totalAllocation), "ERR_TRANSFER_FAILED");
}
}
| Verifies a claim. _liquidityProvider The address of the claimant. _week The week for the claim. _claimedBalance The amount being claimed. _merkleProof The merkle proof for the claim, sorted from the leaf to the root of the tree./ | function verifyClaim(
address _liquidityProvider,
uint _week,
uint _claimedBalance,
bytes32[] memory _merkleProof
)
public
view
returns (bool valid)
{
bytes32 leaf = keccak256(abi.encodePacked(_liquidityProvider, _claimedBalance));
return MerkleProof.verify(_merkleProof, weekMerkleRoots[_week], leaf);
}
| 6,451,423 |
./full_match/80001/0x0aCca12ade732F5Dc6afbad42ad1Eb5F0163e663/sources/contracts/dev/functions/FunctionsOracle.sol | validate within _report to save gas | function _validateReport(
bytes32, /* configDigest */
uint40, /* epochAndRound */
bytes memory /* report */
) internal pure override returns (bool) {
return true;
}
| 5,561,757 |
./partial_match/1/0x8ABb6cc2810c22Df468E5fC491AB693F0901c927/sources/PriceOracle.sol | x to the power of y power(base, exponent)/ | function pow(uint256 base, uint256 exponent) public pure returns (uint256) {
if (exponent == 0) {
return 1;
return base;
return 0;
uint256 z = base;
for (uint256 i = 1; i < exponent; i++) z = srcMul(z, base);
return z;
}
}
| 3,661,591 |
./partial_match/1/0xec3ac374897d72654b85AfC53064A32dbE478dC3/sources/IdfToken.sol | Transfer `amount` tokens from `src` to `dst` src The address of the source account dst The address of the destination account rawAmount The number of tokens to transfer return Whether or not the transfer succeeded/ | function transferFrom(address src, address dst, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
| 9,119,879 |
./full_match/43113/0xE9Cc97730a4e951BbfF27bbE998282cE73579C72/sources/contracts/BaseChain.sol | creates leaf hash, that has is used in merkle tree _key key under which we store the value _value value itself as bytes return leaf hash | function hashLeaf(bytes memory _key, bytes memory _value) public pure returns (bytes32) {
return keccak256(abi.encodePacked(_key, _value));
}
| 7,206,345 |
./partial_match/97/0xBEaDCd9f89B444B0CE60073A85B05744cD874942/sources/CrowFarmContract.sol | Delegates votes from signatory to `delegatee` delegatee The address to delegate votes to nonce The contract state required to match the signature expiry The time at which to expire the signature v The recovery byte of the signature r Half of the ECDSA signature pair s Half of the ECDSA signature pair/ | function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "CROW::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "CROW::delegateBySig: invalid nonce");
require(now <= expiry, "CROW::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
| 11,447,387 |
// SPDX-License-Identifier: MIT-open-group
pragma solidity ^0.8.0;
import {AdminErrorCodes} from "contracts/libraries/errorCodes/AdminErrorCodes.sol";
abstract contract Admin {
// _admin is a privileged role
address internal _admin;
/// @dev onlyAdmin enforces msg.sender is _admin
modifier onlyAdmin() {
require(
msg.sender == _admin,
string(abi.encodePacked(AdminErrorCodes.ADMIN_SENDER_MUST_BE_ADMIN))
);
_;
}
constructor(address admin_) {
_admin = admin_;
}
/// @dev assigns a new admin may only be called by _admin
function setAdmin(address admin_) public virtual onlyAdmin {
_setAdmin(admin_);
}
/// @dev getAdmin returns the current _admin
function getAdmin() public view returns (address) {
return _admin;
}
// assigns a new admin may only be called by _admin
function _setAdmin(address admin_) internal {
_admin = admin_;
}
}
| assigns a new admin may only be called by _admin | function _setAdmin(address admin_) internal {
_admin = admin_;
}
| 15,813,444 |
./full_match/1/0xffdAe6724380828178EA290444116BcF5d56cF3D/sources/contracts/EricOrb.sol | Triggers the orb (otherwise known as Orb Invocation). Allows the holder to submit content hash, that represents a question to the orb issuer. Puts the orb on cooldown. The Orb can only be triggered by solvent holders. Content hash is keccak256 of the cleartext. triggersCount is used to track the id of the next trigger. Emits Triggered(). contentHash Required keccak256 hash of the cleartext./ | function triggerWithHash(bytes32 contentHash) public onlyHolder onlyHolderHeld onlyHolderSolvent {
if (block.timestamp < lastTriggerTime + cooldown) {
revert CooldownIncomplete(lastTriggerTime + cooldown - block.timestamp);
}
uint256 triggerId = triggersCount;
triggers[triggerId] = contentHash;
lastTriggerTime = block.timestamp;
triggersCount += 1;
emit Triggered(msg.sender, triggerId, contentHash, block.timestamp);
}
| 4,995,406 |
pragma solidity ^0.4.24;
import "../access/roles/OwnerRole.sol";
import "../storage/AddressList.sol";
import "../utils/Address.sol";
/**
* @title Blacklistable
*
* @dev Base contract which allows children to restrict functions based on whether an account is on a blacklist.
* This contract inherits the OwnerRole contract to use RBAC for updating the blacklist reference.
* This contract references an external AddressList contract that stores the mapping of blacklisted accounts.
*/
contract Blacklistable is OwnerRole {
/** External AddressList contract storing account addresses that are blacklisted. */
AddressList private _blacklist;
/** Event emitted whenever the address of the AddressList contract is updated. */
event BlacklistUpdated(address indexed previousBlacklist, address indexed newBlacklist);
/** Event emitted whenever tokens are transferred from a blacklisted account to another. */
event TransferFromBlacklisted(address indexed sender, address indexed from, address indexed to, uint256 value);
/**
* @dev Modifier to make a function callable only when the given `account` is blacklisted.
*
* @param account The account address to check
*/
modifier blacklisted(address account) {
require(_blacklist.onList(account));
_;
}
/**
* @dev Modifier to make a function callable only when the given `account` is NOT blacklisted.
*
* @param account The account address to check
*/
modifier notBlacklisted(address account) {
require(!_blacklist.onList(account));
_;
}
/**
* @return The address of the `_blacklist` contract
*/
function blacklist() external view returns (address) {
return address(_blacklist);
}
/**
* @dev Assert if the given `account` is the address of the current blacklist contract.
*
* @param account The address being queried
* @return True if the given `account` is the address of the current blacklist contract, otherwise false
*/
function isBlacklist(address account) external view returns (bool) {
return address(_blacklist) == account;
}
/**
* @dev Asserts if the given `account` is blacklisted.
*
* @param account The account address to check
* @return True if the given `account` is blacklisted, otherwise false
*/
function isBlacklisted(address account) external view returns (bool) {
return _blacklist.onList(account);
}
/**
* @dev Update the `_blacklist` to a new contract address.
* Callable by an account with the owner role.
*
* @param newBlacklist The address of the new blacklist contract
*/
function updateBlacklist(address newBlacklist) external onlyOwner {
_updateBlacklist(newBlacklist);
}
/**
* @dev Internal function that updates the `_blacklist` to a new contract address.
* Emits a BlacklistUpdated event.
*
* @param newBlacklist The address of the new blacklist contract
*/
function _updateBlacklist(address newBlacklist) internal {
require(newBlacklist != address(0));
require(Address.isContract(newBlacklist));
emit BlacklistUpdated(address(_blacklist), newBlacklist);
_blacklist = AddressList(newBlacklist);
}
/**
* @dev Internal function that should be called whenever tokens are transferred from a blacklisted account.
* Emits a TransferFromBlacklisted event.
*
* @param sender The account that is initiating the transfer
* @param from The blacklisted account tokens are being transferred from
* @param to The account the tokens are being transferred to
* @param value The amount of tokens being transferred
*/
function _transferFromBlacklisted(address sender, address from, address to, uint256 value) internal {
// Assert that the from and to address are not the null account and that the value is greater than zero
require(from != address(0));
require(to != address(0));
require(value > 0);
// Emit the TransferFromBlacklisted event
emit TransferFromBlacklisted(sender, from, to, value);
}
} | Internal function that updates the `_blacklist` to a new contract address. Emits a BlacklistUpdated event. newBlacklist The address of the new blacklist contract/ | function _updateBlacklist(address newBlacklist) internal {
require(newBlacklist != address(0));
require(Address.isContract(newBlacklist));
emit BlacklistUpdated(address(_blacklist), newBlacklist);
_blacklist = AddressList(newBlacklist);
}
| 1,823,259 |
./full_match/84531/0x33f0aB57a54493D06c27a3Cd9CB62CC1f7e9F4ED/sources/contract-v2.sol | transfer funds from the contract to the owner of the contract./ | function claimTreasury() external onlyOwner {
require(treasuryAmount > 0, "No treasury to claim");
uint256 currentTreasuryAmount = treasuryAmount;
treasuryAmount = 0;
Address.sendValue(payable(msg.sender), currentTreasuryAmount);
}
| 14,320,745 |
./full_match/1/0x62BF548B95e48ff169C1bAcC59B9BC99B014e273/sources/contracts/FeePoolUpgradeable.sol | uint256 noOfDepositors = bridgeUtilsUpgradeable.getEpochTotalDepositors(_tokenTicker, epochsLength); for child token bridges | function getLastEpochLpFees(
string memory _tokenTicker
) public view returns (uint256) {
uint256 epochsLength = bridgeUpgradeable.getEpochsLength(_tokenTicker);
if(epochsLength == 0)
return 0;
(
,
,
uint256 totalFeesCollected,
uint256 totalActiveLiquidity,
uint256 noOfDepositors
) = bridgeUpgradeable.epochs(_tokenTicker, epochsLength-1);
if(noOfDepositors == 0) {
return 0;
}
uint256 totalBoostedLiquidity = bridgeUpgradeable.totalBoostedLiquidity(_tokenTicker, epochsLength);
uint256 totalNormalLiquidity = totalActiveLiquidity - totalBoostedLiquidity;
uint256 boostedFees = (totalBoostedLiquidity * totalFeesCollected * 3) / (totalActiveLiquidity * 4);
uint256 normalFees = (totalNormalLiquidity * totalFeesCollected) / (totalActiveLiquidity * 2);
return (normalFees + boostedFees);
}
| 2,932,563 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.4.0;
import '../libraries/FullMath.sol';
contract FullMathEchidnaTest {
function checkH(uint256 x, uint256 y) public pure {
// if the mul doesn't overflow in 256-bit space, h should be 0
if (x == 0 || ((x * y) / x == y)) {
(, uint256 h) = FullMath.fullMul(x, y);
assert(h == 0);
}
}
}
| if the mul doesn't overflow in 256-bit space, h should be 0 | function checkH(uint256 x, uint256 y) public pure {
if (x == 0 || ((x * y) / x == y)) {
(, uint256 h) = FullMath.fullMul(x, y);
assert(h == 0);
}
}
| 12,617,184 |
./full_match/42161/0x902Dd246e66d8C3CE652375a723F2a52b43b9AAE/sources/contracts/signature-drop/SignatureDrop.sol | Claim lazy minted tokens via signature. Set royalties, if applicable. | function mintWithSignature(MintRequest calldata _req, bytes calldata _signature)
external
payable
returns (address signer)
{
uint256 tokenIdToMint = _currentIndex;
if (tokenIdToMint + _req.quantity > nextTokenIdToLazyMint) {
revert("Not enough tokens");
}
address receiver = _req.to;
if (_req.royaltyRecipient != address(0) && _req.royaltyBps != 0) {
_setupRoyaltyInfoForToken(tokenIdToMint, _req.royaltyRecipient, _req.royaltyBps);
}
emit TokensMintedWithSignature(signer, receiver, tokenIdToMint, _req);
}
| 16,303,542 |
./partial_match/3/0x93aE15BC2454C138e79F3F9EB26F9743c0c25C77/sources/pool.sol | clear history price before given timestamp/ unmark time table replace with the last price recorded; pop out the last price recorded from the history | function _clearHistoryPrice(uint beforeTs) internal {
uint count;
for (uint i=0;i<_priceHistory.length;i++) {
delete _timeTable[_priceHistory[i].time];
_priceHistory[i] = _priceHistory[_priceHistory.length - 1];
_priceHistory.pop();
count++;
}
}
| 5,151,149 |
/**
*Submitted for verification at Etherscan.io on 2022-02-18
*/
// SPDX-License-Identifier: MIT
// //// //
/// ////// ///
//// //////// ////
///// ////////// /////
////// //////////// //////
/////// ////////////// ///////
//////// //////////////// ////////
///////// ////////////////// /////////
////////// //////////////////// //////////
/////////// ////////////////////// ///////////
//////////// //////////////////////// ////////////
///////////// ////////////////////////// /////////////
////////////// //////////////////////////// //////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/**
As luck would have it... you made it.
My name is Botolf, a messenger of King Zev.
King Zev left me an urgent message to pass along.
Pray thee take the time to read as we need your help saving the Realm.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Anon,
The Whales of the Realm may be in possession of the 9 gems.
Their intentions are unknown, and now the Kingdom is at risk.
The gems are the key to a treasure trove.
If the treasure falls into their hands, the Realm will recede into darkness for 420 years.
I cry your mercy, collect the gems and find the treasure before the Whales.
Fortunately, you'll need more than the gems alone to unlock the vault the treasure resides.
There are hidden secrets planted throughout the Kingdom to mislead the Whales.
Tread carefully scavenger, you will soon realize things may not always appear as they seem.
I mustn't say anymore.
Resolutely,
King Zev
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Botolf here again.
King Zev's message was quite cryptic.
To help clear things up, I was authorized to tell you the following:
1) King Zev's Gems are completely on-chain. They will persist forever as long as there is an Ethereum blockchain.
2) King Zev's Gems have
- No website
- No IPFS
- No Arweave
- No Twitter
- No Discord
- No APIs
- No external dependencies
3) Botolf will look for the hashtag #KingZevsGems on Twitter to see if a community website, Twitter, and/or Discord is created.
4) Keep an eye out for any contracts the deploying address may create. Your gems may be useful there.
5) Last, but not least, if it isn't clear what the treasure is, ask your smartest mate to review the code.
Oh, and if you've never minted with Etherscan before, read this tutorial https://blog.logrocket.com/how-to-mint-an-nft-with-etherscan/
Happy Treasure Hunting frens
*/
// 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/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/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. 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/KingZevsGems.sol
pragma solidity ^0.8.0;
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides functions for encoding/decoding base64
library Base64 {
string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000"
hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000"
hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000"
hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE_ENCODE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {} lt(dataPtr, endPtr) {}
{
// read 3 bytes
dataPtr := add(dataPtr, 3)
let input := mload(dataPtr)
// write 4 characters
mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F))))
resultPtr := add(resultPtr, 1)
mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F))))
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
}
return result;
}
function decode(string memory _data) internal pure returns (bytes memory) {
bytes memory data = bytes(_data);
if (data.length == 0) return new bytes(0);
require(data.length % 4 == 0, "invalid base64 decoder input");
// load the table into memory
bytes memory table = TABLE_DECODE;
// every 4 characters represent 3 bytes
uint256 decodedLen = (data.length / 4) * 3;
// add some extra buffer at the end required for the writing
bytes memory result = new bytes(decodedLen + 32);
assembly {
// padding with '='
let lastBytes := mload(add(data, mload(data)))
if eq(and(lastBytes, 0xFF), 0x3d) {
decodedLen := sub(decodedLen, 1)
if eq(and(lastBytes, 0xFFFF), 0x3d3d) {
decodedLen := sub(decodedLen, 1)
}
}
// set the actual output length
mstore(result, decodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 4 characters at a time
for {} lt(dataPtr, endPtr) {}
{
// read 4 characters
dataPtr := add(dataPtr, 4)
let input := mload(dataPtr)
// write 3 bytes
let output := add(
add(
shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)),
shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))),
add(
shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)),
and(mload(add(tablePtr, and( input , 0xFF))), 0xFF)
)
)
mstore(resultPtr, shl(232, output))
resultPtr := add(resultPtr, 3)
}
}
return result;
}
}
//// ~~~~~~~~~~~~~~~~~~~~~~~~~ ////
//// ~~~~ King Zev's Gems ~~~~ ////
//// ~~~~~~~~~~~~~~~~~~~~~~~~~ ////
interface ExternalInterface {
function ownerOf(uint256 tokenId) external view returns (address owner);
}
contract KingZevsGems is ERC721, Ownable {
using Strings for uint256;
using SafeMath for uint256;
using Counters for Counters.Counter;
Counters.Counter private _gemCounter;
uint256 public constant MAX_GEMS = 8888;
uint256 public constant MAX_YOU_ARE_EARLY = 1111;
uint256 public constant MAX_GEMS_MINTED = 10;
uint256 public constant GEM_MINT_PRICE = 8 * 10**16; // 0.08 ETH
uint256 private pinKeyB = 0;
bool public isTreasureInVault = false;
bool public isPortcullisOpen = false;
bool public isWhales = false;
string[] private gems = ["topaz", "ruby", "sapphire", "emerald", "opal", "zircon", "onyx", "jadeite", "amber"];
string[] private gemsColorOne = ["#ffa830", "#990c41", "#093373", "#319b54", "#c0ebff", "#681a1a", "#000000", "#005c3a", "#b38600"];
string[] private gemsColorTwo = ["#ffe8c9", "#f14c8a", "#2875ee", "#8adaa5", "#ffc0cb", "#d14a4a", "#404040", "#00f59c", "#ffd24d"];
string[] private gemPoints = [
"50,25 75,50 50,75 25,50",
"50,12.5 75,50 50,87.5 25,50",
"50,25 87.5,50 50,75 12.5,50",
"40,25 60,25 87.5,50 60,75 40,75 12.5,50",
"50,12.5 75,30 75,70 50,87.5 25,70 25,30",
"12.5,50 25,35 75,35 87.5,50 75,65 25,65",
"40,25 60,25 87.5,44 87.5,55 60,75 40,75 12.5,55 12.5,45"
];
ExternalInterface externalContract;
event CreateGem(uint256 indexed id);
constructor() public ERC721("King Zevs Gems", "GEM") {}
function totalSupply() public view returns (uint256) {
return _gemCounter.current();
}
function MINT_TO_THE_WHALE_OF_KING_ZEVS_KINGDOM_SO_THIS_POPS_UP_ON_NANSEN_AND_ICY_TOOLS_AND_STUFF() public payable {
require(!isWhales);
_mintManyGems(0xF7DcF798971452737f1E6196D36Dd215b43b428D, 0);
_mintManyGems(0x6Cd2D84298F731fa443061255a9a84a09dbCA769, 1);
_mintManyGems(0xA442dDf27063320789B59A8fdcA5b849Cd2CDeAC, 2);
_mintManyGems(0x72FAe93d08A060A7f0A8919708c0Db74Ca46cbB6, 3);
_mintManyGems(0xC46Db2d89327D4C41Eb81c43ED5e3dfF111f9A8f, 4);
_mintManyGems(0xCb96594AbA4627e6064731b0098Dc97547b397BE, 5);
_mintManyGems(0x4385FF4B76d8A7fa8075Ed1ee27c82fFE0951456, 6);
_mintManyGems(0xaf469C4a0914938e6149CF621c54FB4b1EC0c202, 7);
_mintManyGems(0xe9F1E4dC4D1F3F62d54d70Ea73A8c9B4Cd2BDE2D, 8);
_mintManyGems(0xe1D29d0a39962a9a8d2A297ebe82e166F8b8EC18, 9);
_mintManyGems(0xaBF107de3E01c7c257e64E0a18d60A733Aad395d, 10);
_mintManyGems(0x442DCCEe68425828C106A3662014B4F131e3BD9b, 11);
_mintManyGems(0xD387A6E4e84a6C86bd90C158C6028A58CC8Ac459, 12);
_mintManyGems(0x7500935C3C34D0d48e9c388b3dFFa0AbBda52633, 13);
_mintManyGems(0x11360F0c5552443b33720a44408aba01a809905e, 14);
_mintManyGems(0xc5F59709974262c4AFacc5386287820bDBC7eB3A, 15);
isWhales = true;
}
function unlockTheGates(address _contract) public {
require(totalSupply() >= MAX_GEMS, "not permitted until all gems are minted");
externalContract = ExternalInterface(_contract);
}
function openTheGates(uint256 _tokenId) public {
require(totalSupply() >= MAX_GEMS, "not permitted until all gems are minted");
require(balanceOf(_msgSender()) > 0, "need to own a gem, ser");
require(externalContract.ownerOf(_tokenId) == msg.sender);
isPortcullisOpen = true;
}
/**
* @dev See {ERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(isPortcullisOpen);
super.setApprovalForAll(operator, approved);
}
/**
* @dev See {ERC721-_beforeTokenTranfser}.
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
require(from == address(0) || isPortcullisOpen);
pinKeyB = tokenId % 420;
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev Mint your gems. payableAmount (ether) is 0.08 for 1, 0.16 for 2, 0.24 for 3, ..., 0.8 for 10.
* @param _count The number of gems you want to mint. Max 10 per wallet.
*/
function mintGem(uint256 _count) public payable {
uint256 total = totalSupply();
require(total + _count <= MAX_GEMS, "gems r minted silly scavenger");
require(total <= MAX_GEMS, "gems r minted silly scavenger");
require(balanceOf(_msgSender()) + _count <= MAX_GEMS_MINTED, "greedy, ser");
// let the first 1111 scavengers mint for free, they're early
require(msg.value >= GEM_MINT_PRICE.mul(_count) || total + _count < MAX_YOU_ARE_EARLY, "not enough ether, ser");
_mintManyGems(msg.sender, _count);
}
function _mintManyGems(address _to, uint256 _count) private {
for (uint256 i = 0; i < _count; i++) {
_mintGem(_to);
}
}
function _mintGem(address _to) private {
uint256 id = totalSupply();
_gemCounter.increment();
_safeMint(_to, id);
emit CreateGem(id);
}
function getGemId(uint256 _tokenId) internal pure returns (uint256) {
uint256 rarity = uint256(keccak256(abi.encodePacked("GEM", Strings.toString(_tokenId)))) % 101;
uint256 gemId = 0;
if (rarity >= 25) {
gemId = 1;
}
if (rarity >= 50) {
gemId = 2;
}
if (rarity >= 75) {
gemId = 3;
}
if (rarity >= 90) {
gemId = 4;
}
if (rarity >= 96) {
gemId = 5;
}
if (rarity >= 99) {
gemId = 6;
}
if (rarity == 69) {
gemId = 7;
}
if (rarity > 100) {
gemId = 8;
}
return gemId;
}
function getGemGrade(uint256 _tokenId) internal pure returns (uint256) {
uint256 rarity = uint256(keccak256(abi.encodePacked("GEM GRADE", Strings.toString(_tokenId)))) % 101;
uint256 grade = 1;
if (rarity >= 15) {
grade = 2;
}
if (rarity >= 30) {
grade = 3;
}
if (rarity >= 90) {
grade = 4;
}
if (rarity >= 99) {
grade = 5;
}
return grade;
}
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
uint256 _gemId = getGemId(_tokenId);
string memory _gem = gems[_gemId];
string memory _gemGrade = Strings.toString(getGemGrade(_tokenId));
if (totalSupply() < MAX_GEMS) {
_gem = "oN-cHaIn rEVeAl afTeR MinT";
_gemGrade = "oN-cHaIn rEVeAl afTeR MinT";
}
string memory json = Base64.encode(abi.encodePacked(
'{"name":"Gem ',
Strings.toString(_tokenId),
'", "description":"A quest to find King Zev',
"'",
's treasure trove. Collect gems, find clues, solve puzzles. On-chain, no website, no IPFS.", "attributes":[{"trait_type":"gem","value":"',
_gem,
'"}, {"trait_type":"Rarity Grade","value":"',
_gemGrade,
'"}], "image":"',
gemImage(_tokenId),
'"}'
));
string memory jsonUri = string(abi.encodePacked("data:application/json;base64,", json));
return jsonUri;
}
function gemImage(uint256 _tokenId) private view returns(string memory) {
uint256 _gemId = getGemId(_tokenId);
string memory colorOne = gemsColorOne[_gemId];
string memory colorTwo = gemsColorTwo[_gemId];
string memory path = '<ellipse fill="url(#linear-gradient)" cx="50" cy="50" rx="30" ry="20"/></svg>';
string[14] memory parts;
parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><defs><linearGradient id="linear-gradient" x1="0" y1="0" x2="100%" y2="0" ><stop offset="0"><animate attributeName="stop-color" values="';
parts[1] = colorOne;
parts[2] = ";";
parts[3] = colorTwo;
parts[4] = ";";
parts[5] = colorOne;
parts[6] = '" dur="1s" repeatCount="indefinite" /></stop><stop offset="1"><animate attributeName="stop-color" values="';
parts[7] = colorTwo;
parts[8] = ";";
parts[9] = colorOne;
parts[10] = ";";
parts[11] = colorTwo;
parts[12] = '" dur="1s" repeatCount="indefinite" /></stop></linearGradient></defs>';
if (_gemId != 6) {
string memory gemPoint = gemPoints[_tokenId % gemPoints.length];
path = string(abi.encodePacked(
'<polygon fill="url(#linear-gradient)" points="',
gemPoint,
'"/></svg>'
));
}
parts[13] = path;
string memory svg = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8]));
svg = string(abi.encodePacked(svg, parts[9], parts[10], parts[11], parts[12], parts[13]));
if (totalSupply() < MAX_GEMS) {
svg = string(abi.encodePacked(
'<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><defs><linearGradient id="linear-gradient" x1="0" y1="0" x2="100%" y2="0" ><stop offset="0"><animate attributeName="stop-color" values="#990c41;#f14c8a;#990c41" dur="1s" repeatCount="indefinite" /></stop><stop offset="1"><animate attributeName="stop-color" values="#f14c8a;#990c41;#f14c8a" dur="1s" repeatCount="indefinite" /></stop></linearGradient></defs><polygon fill="url(#linear-gradient)" points="12.5,70 25,55 75,55 87.5,70 75,85 25,85"/><text x="50%" y="25%" text-anchor="middle" font-family="monospace" font-weight="bold" fill="url(#linear-gradient)">King Zev',
"'",
's</text> <text x="50%" y="45%" text-anchor="middle" font-family="monospace" font-weight="bold" fill="url(#linear-gradient)">Gems</text></svg>'
));
}
string memory svgUri = string(abi.encodePacked('data:image/svg+xml;base64,', Base64.encode(abi.encodePacked(svg))));
return svgUri;
}
function lockTreasureInVault() public payable onlyOwner {
require(!isTreasureInVault);
uint256 balance = address(this).balance.div(2);
require(balance > 0);
_withdraw(msg.sender, balance);
// lock the owner so they can only call this once
isTreasureInVault = true;
}
function claimKingZevsTreasure(uint256[] memory unlockIds) public payable {
require(isTreasureInVault);
require(unlockIds.length >= 14);
require(balanceOf(_msgSender()) >= 25);
for (uint256 i = 0; i < 10; i++) {
uint256 _tokenId = unlockIds[i];
require(ownerOf(_tokenId) == msg.sender);
if (i < 9) {
if (i == 8) {
require(getGemId(_tokenId) == 6);
} else {
require(getGemId(_tokenId) == i);
}
} else {
require(_tokenId < 1111);
}
}
uint256 _pinKeyA = uint256(keccak256(abi.encodePacked("KING ZEV PIN KEY"))) % 420;
uint256 _pinKeyB = uint256(keccak256(abi.encodePacked(Strings.toString(pinKeyB)))) % 420;
uint256 _pinKeyC = uint256(keccak256(abi.encodePacked(Strings.toString(_pinKeyA)))) % 420;
uint256 _pinKeyD = 69; // nice
require(unlockIds[10] == _pinKeyA, "oooooh, try again ser");
require(unlockIds[11] == pinKeyB, "oooooh, try againn ser");
require(unlockIds[12] == _pinKeyD, "oooooh, try againnn ser");
require(unlockIds[13] == _pinKeyC, "oooooh, try againnnn ser");
uint256 balance = address(this).balance.div(2);
require(balance > 0);
_withdraw(msg.sender, balance);
for (uint256 i = 0; i < 9; i++) {
_transfer(msg.sender, 0x000000000000000000000000000000000000dEaD, unlockIds[i]);
}
}
function _withdraw(address _address, uint256 _amount) private {
(bool success, ) = _address.call{value: _amount}("");
require(success, "Transfer failed.");
}
} | Mint your gems. payableAmount (ether) is 0.08 for 1, 0.16 for 2, 0.24 for 3, ..., 0.8 for 10. _count The number of gems you want to mint. Max 10 per wallet./ let the first 1111 scavengers mint for free, they're early | function mintGem(uint256 _count) public payable {
uint256 total = totalSupply();
require(total + _count <= MAX_GEMS, "gems r minted silly scavenger");
require(total <= MAX_GEMS, "gems r minted silly scavenger");
require(balanceOf(_msgSender()) + _count <= MAX_GEMS_MINTED, "greedy, ser");
require(msg.value >= GEM_MINT_PRICE.mul(_count) || total + _count < MAX_YOU_ARE_EARLY, "not enough ether, ser");
_mintManyGems(msg.sender, _count);
}
| 2,154,276 |
./full_match/80001/0xCb27a94A51dA5D5F066B50087eFdF7FA3C76d103/sources/src/Contract.sol | Function to update the DAILY_REWARD value (within the range 5 to 10) allowed only for the owner | function updateDailyReward(uint256 newReward) external onlyOwner {
require(newReward >= 1 && newReward <= 10, "Reward should be between 1 and 10");
DAILY_REWARD = newReward;
}
| 846,838 |
./full_match/5/0x25427ba3411054899A181b473e6a1584f9D23341/sources/project_/contracts/superfluid/Superfluid.sol | assuming it's uups proxiable | function updateSuperTokenLogic(ISuperToken token)
external override
onlyGovernance
{
address code = address(_superTokenFactory.getSuperTokenLogic());
UUPSProxiable(address(token)).updateCode(code);
emit SuperTokenLogicUpdated(token, code);
}
| 1,898,334 |
//Address: 0x10a5f6dbd1f9e56fe09df25b1163cd299d5d2413
//Contract name: EthernautsExplore
//Balance: 0.251 Ether
//Verification Date: 4/24/2018
//Transacion Count: 727
// CODE STARTS HERE
pragma solidity ^0.4.19;
/// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
/// @author Ethernauts
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint256 total);
function balanceOf(address _owner) public view returns (uint256 balance);
function ownerOf(uint256 _tokenId) external view returns (address owner);
function approve(address _to, uint256 _tokenId) external;
function transfer(address _to, uint256 _tokenId) external;
function transferFrom(address _from, address _to, uint256 _tokenId) external;
function takeOwnership(uint256 _tokenId) public;
function implementsERC721() public pure returns (bool);
// Events
event Transfer(address from, address to, uint256 tokenId);
event Approval(address owner, address approved, uint256 tokenId);
// Optional
// function name() public view returns (string name);
// function symbol() public view returns (string symbol);
// function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds);
// function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl);
// ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165)
function supportsInterface(bytes4 _interfaceID) external view returns (bool);
}
// Extend this library for child contracts
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
/**
* @dev Compara two numbers, and return the bigger one.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
if (a > b) {
return a;
} else {
return b;
}
}
/**
* @dev Compara two numbers, and return the bigger one.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
if (a < b) {
return a;
} else {
return b;
}
}
}
/// @dev Base contract for all Ethernauts contracts holding global constants and functions.
contract EthernautsBase {
/*** CONSTANTS USED ACROSS CONTRACTS ***/
/// @dev Used by all contracts that interfaces with Ethernauts
/// The ERC-165 interface signature for ERC-721.
/// Ref: https://github.com/ethereum/EIPs/issues/165
/// Ref: https://github.com/ethereum/EIPs/issues/721
bytes4 constant InterfaceSignature_ERC721 =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('balanceOf(address)')) ^
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('transfer(address,uint256)')) ^
bytes4(keccak256('transferFrom(address,address,uint256)')) ^
bytes4(keccak256('takeOwnership(uint256)')) ^
bytes4(keccak256('tokensOfOwner(address)')) ^
bytes4(keccak256('tokenMetadata(uint256,string)'));
/// @dev due solidity limitation we cannot return dynamic array from methods
/// so it creates incompability between functions across different contracts
uint8 public constant STATS_SIZE = 10;
uint8 public constant SHIP_SLOTS = 5;
// Possible state of any asset
enum AssetState { Available, UpForLease, Used }
// Possible state of any asset
// NotValid is to avoid 0 in places where category must be bigger than zero
enum AssetCategory { NotValid, Sector, Manufacturer, Ship, Object, Factory, CrewMember }
/// @dev Sector stats
enum ShipStats {Level, Attack, Defense, Speed, Range, Luck}
/// @notice Possible attributes for each asset
/// 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals.
/// 00000010 - Producible - Product of a factory and/or factory contract.
/// 00000100 - Explorable- Product of exploration.
/// 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete.
/// 00010000 - Permanent - Cannot be removed, always owned by a user.
/// 00100000 - Consumable - Destroyed after N exploration expeditions.
/// 01000000 - Tradable - Buyable and sellable on the market.
/// 10000000 - Hot Potato - Automatically gets put up for sale after acquiring.
bytes2 public ATTR_SEEDED = bytes2(2**0);
bytes2 public ATTR_PRODUCIBLE = bytes2(2**1);
bytes2 public ATTR_EXPLORABLE = bytes2(2**2);
bytes2 public ATTR_LEASABLE = bytes2(2**3);
bytes2 public ATTR_PERMANENT = bytes2(2**4);
bytes2 public ATTR_CONSUMABLE = bytes2(2**5);
bytes2 public ATTR_TRADABLE = bytes2(2**6);
bytes2 public ATTR_GOLDENGOOSE = bytes2(2**7);
}
/// @notice This contract manages the various addresses and constraints for operations
// that can be executed only by specific roles. Namely CEO and CTO. it also includes pausable pattern.
contract EthernautsAccessControl is EthernautsBase {
// This facet controls access control for Ethernauts.
// All roles have same responsibilities and rights, but there is slight differences between them:
//
// - The CEO: The CEO can reassign other roles and only role that can unpause the smart contract.
// It is initially set to the address that created the smart contract.
//
// - The CTO: The CTO can change contract address, oracle address and plan for upgrades.
//
// - The COO: The COO can change contract address and add create assets.
//
/// @dev Emited when contract is upgraded - See README.md for updgrade plan
/// @param newContract address pointing to new contract
event ContractUpgrade(address newContract);
// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public ctoAddress;
address public cooAddress;
address public oracleAddress;
// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CTO-only functionality
modifier onlyCTO() {
require(msg.sender == ctoAddress);
_;
}
/// @dev Access modifier for CTO-only functionality
modifier onlyOracle() {
require(msg.sender == oracleAddress);
_;
}
modifier onlyCLevel() {
require(
msg.sender == ceoAddress ||
msg.sender == ctoAddress ||
msg.sender == cooAddress
);
_;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the CTO. Only available to the current CTO or CEO.
/// @param _newCTO The address of the new CTO
function setCTO(address _newCTO) external {
require(
msg.sender == ceoAddress ||
msg.sender == ctoAddress
);
require(_newCTO != address(0));
ctoAddress = _newCTO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current COO or CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) external {
require(
msg.sender == ceoAddress ||
msg.sender == cooAddress
);
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/// @dev Assigns a new address to act as oracle.
/// @param _newOracle The address of oracle
function setOracle(address _newOracle) external {
require(msg.sender == ctoAddress);
require(_newOracle != address(0));
oracleAddress = _newOracle;
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CTO account is compromised.
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause() public onlyCEO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
}
/// @title Storage contract for Ethernauts Data. Common structs and constants.
/// @notice This is our main data storage, constants and data types, plus
// internal functions for managing the assets. It is isolated and only interface with
// a list of granted contracts defined by CTO
/// @author Ethernauts - Fernando Pauer
contract EthernautsStorage is EthernautsAccessControl {
function EthernautsStorage() public {
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
// the creator of the contract is the initial CTO as well
ctoAddress = msg.sender;
// the creator of the contract is the initial CTO as well
cooAddress = msg.sender;
// the creator of the contract is the initial Oracle as well
oracleAddress = msg.sender;
}
/// @notice No tipping!
/// @dev Reject all Ether from being sent here. Hopefully, we can prevent user accidents.
function() external payable {
require(msg.sender == address(this));
}
/*** Mapping for Contracts with granted permission ***/
mapping (address => bool) public contractsGrantedAccess;
/// @dev grant access for a contract to interact with this contract.
/// @param _v2Address The contract address to grant access
function grantAccess(address _v2Address) public onlyCTO {
// See README.md for updgrade plan
contractsGrantedAccess[_v2Address] = true;
}
/// @dev remove access from a contract to interact with this contract.
/// @param _v2Address The contract address to be removed
function removeAccess(address _v2Address) public onlyCTO {
// See README.md for updgrade plan
delete contractsGrantedAccess[_v2Address];
}
/// @dev Only allow permitted contracts to interact with this contract
modifier onlyGrantedContracts() {
require(contractsGrantedAccess[msg.sender] == true);
_;
}
modifier validAsset(uint256 _tokenId) {
require(assets[_tokenId].ID > 0);
_;
}
/*** DATA TYPES ***/
/// @dev The main Ethernauts asset struct. Every asset in Ethernauts is represented by a copy
/// of this structure. Note that the order of the members in this structure
/// is important because of the byte-packing rules used by Ethereum.
/// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html
struct Asset {
// Asset ID is a identifier for look and feel in frontend
uint16 ID;
// Category = Sectors, Manufacturers, Ships, Objects (Upgrades/Misc), Factories and CrewMembers
uint8 category;
// The State of an asset: Available, On sale, Up for lease, Cooldown, Exploring
uint8 state;
// Attributes
// byte pos - Definition
// 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals.
// 00000010 - Producible - Product of a factory and/or factory contract.
// 00000100 - Explorable- Product of exploration.
// 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete.
// 00010000 - Permanent - Cannot be removed, always owned by a user.
// 00100000 - Consumable - Destroyed after N exploration expeditions.
// 01000000 - Tradable - Buyable and sellable on the market.
// 10000000 - Hot Potato - Automatically gets put up for sale after acquiring.
bytes2 attributes;
// The timestamp from the block when this asset was created.
uint64 createdAt;
// The minimum timestamp after which this asset can engage in exploring activities again.
uint64 cooldownEndBlock;
// The Asset's stats can be upgraded or changed based on exploration conditions.
// It will be defined per child contract, but all stats have a range from 0 to 255
// Examples
// 0 = Ship Level
// 1 = Ship Attack
uint8[STATS_SIZE] stats;
// Set to the cooldown time that represents exploration duration for this asset.
// Defined by a successful exploration action, regardless of whether this asset is acting as ship or a part.
uint256 cooldown;
// a reference to a super asset that manufactured the asset
uint256 builtBy;
}
/*** CONSTANTS ***/
// @dev Sanity check that allows us to ensure that we are pointing to the
// right storage contract in our EthernautsLogic(address _CStorageAddress) call.
bool public isEthernautsStorage = true;
/*** STORAGE ***/
/// @dev An array containing the Asset struct for all assets in existence. The Asset UniqueId
/// of each asset is actually an index into this array.
Asset[] public assets;
/// @dev A mapping from Asset UniqueIDs to the price of the token.
/// stored outside Asset Struct to save gas, because price can change frequently
mapping (uint256 => uint256) internal assetIndexToPrice;
/// @dev A mapping from asset UniqueIDs to the address that owns them. All assets have some valid owner address.
mapping (uint256 => address) internal assetIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) internal ownershipTokenCount;
/// @dev A mapping from AssetUniqueIDs to an address that has been approved to call
/// transferFrom(). Each Asset can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint256 => address) internal assetIndexToApproved;
/*** SETTERS ***/
/// @dev set new asset price
/// @param _tokenId asset UniqueId
/// @param _price asset price
function setPrice(uint256 _tokenId, uint256 _price) public onlyGrantedContracts {
assetIndexToPrice[_tokenId] = _price;
}
/// @dev Mark transfer as approved
/// @param _tokenId asset UniqueId
/// @param _approved address approved
function approve(uint256 _tokenId, address _approved) public onlyGrantedContracts {
assetIndexToApproved[_tokenId] = _approved;
}
/// @dev Assigns ownership of a specific Asset to an address.
/// @param _from current owner address
/// @param _to new owner address
/// @param _tokenId asset UniqueId
function transfer(address _from, address _to, uint256 _tokenId) public onlyGrantedContracts {
// Since the number of assets is capped to 2^32 we can't overflow this
ownershipTokenCount[_to]++;
// transfer ownership
assetIndexToOwner[_tokenId] = _to;
// When creating new assets _from is 0x0, but we can't account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete assetIndexToApproved[_tokenId];
}
}
/// @dev A public method that creates a new asset and stores it. This
/// method does basic checking and should only be called from other contract when the
/// input data is known to be valid. Will NOT generate any event it is delegate to business logic contracts.
/// @param _creatorTokenID The asset who is father of this asset
/// @param _owner First owner of this asset
/// @param _price asset price
/// @param _ID asset ID
/// @param _category see Asset Struct description
/// @param _state see Asset Struct description
/// @param _attributes see Asset Struct description
/// @param _stats see Asset Struct description
function createAsset(
uint256 _creatorTokenID,
address _owner,
uint256 _price,
uint16 _ID,
uint8 _category,
uint8 _state,
uint8 _attributes,
uint8[STATS_SIZE] _stats,
uint256 _cooldown,
uint64 _cooldownEndBlock
)
public onlyGrantedContracts
returns (uint256)
{
// Ensure our data structures are always valid.
require(_ID > 0);
require(_category > 0);
require(_attributes != 0x0);
require(_stats.length > 0);
Asset memory asset = Asset({
ID: _ID,
category: _category,
builtBy: _creatorTokenID,
attributes: bytes2(_attributes),
stats: _stats,
state: _state,
createdAt: uint64(now),
cooldownEndBlock: _cooldownEndBlock,
cooldown: _cooldown
});
uint256 newAssetUniqueId = assets.push(asset) - 1;
// Check it reached 4 billion assets but let's just be 100% sure.
require(newAssetUniqueId == uint256(uint32(newAssetUniqueId)));
// store price
assetIndexToPrice[newAssetUniqueId] = _price;
// This will assign ownership
transfer(address(0), _owner, newAssetUniqueId);
return newAssetUniqueId;
}
/// @dev A public method that edit asset in case of any mistake is done during process of creation by the developer. This
/// This method doesn't do any checking and should only be called when the
/// input data is known to be valid.
/// @param _tokenId The token ID
/// @param _creatorTokenID The asset that create that token
/// @param _price asset price
/// @param _ID asset ID
/// @param _category see Asset Struct description
/// @param _state see Asset Struct description
/// @param _attributes see Asset Struct description
/// @param _stats see Asset Struct description
/// @param _cooldown asset cooldown index
function editAsset(
uint256 _tokenId,
uint256 _creatorTokenID,
uint256 _price,
uint16 _ID,
uint8 _category,
uint8 _state,
uint8 _attributes,
uint8[STATS_SIZE] _stats,
uint16 _cooldown
)
external validAsset(_tokenId) onlyCLevel
returns (uint256)
{
// Ensure our data structures are always valid.
require(_ID > 0);
require(_category > 0);
require(_attributes != 0x0);
require(_stats.length > 0);
// store price
assetIndexToPrice[_tokenId] = _price;
Asset storage asset = assets[_tokenId];
asset.ID = _ID;
asset.category = _category;
asset.builtBy = _creatorTokenID;
asset.attributes = bytes2(_attributes);
asset.stats = _stats;
asset.state = _state;
asset.cooldown = _cooldown;
}
/// @dev Update only stats
/// @param _tokenId asset UniqueId
/// @param _stats asset state, see Asset Struct description
function updateStats(uint256 _tokenId, uint8[STATS_SIZE] _stats) public validAsset(_tokenId) onlyGrantedContracts {
assets[_tokenId].stats = _stats;
}
/// @dev Update only asset state
/// @param _tokenId asset UniqueId
/// @param _state asset state, see Asset Struct description
function updateState(uint256 _tokenId, uint8 _state) public validAsset(_tokenId) onlyGrantedContracts {
assets[_tokenId].state = _state;
}
/// @dev Update Cooldown for a single asset
/// @param _tokenId asset UniqueId
/// @param _cooldown asset state, see Asset Struct description
function setAssetCooldown(uint256 _tokenId, uint256 _cooldown, uint64 _cooldownEndBlock)
public validAsset(_tokenId) onlyGrantedContracts {
assets[_tokenId].cooldown = _cooldown;
assets[_tokenId].cooldownEndBlock = _cooldownEndBlock;
}
/*** GETTERS ***/
/// @notice Returns only stats data about a specific asset.
/// @dev it is necessary due solidity compiler limitations
/// when we have large qty of parameters it throws StackTooDeepException
/// @param _tokenId The UniqueId of the asset of interest.
function getStats(uint256 _tokenId) public view returns (uint8[STATS_SIZE]) {
return assets[_tokenId].stats;
}
/// @dev return current price of an asset
/// @param _tokenId asset UniqueId
function priceOf(uint256 _tokenId) public view returns (uint256 price) {
return assetIndexToPrice[_tokenId];
}
/// @notice Check if asset has all attributes passed by parameter
/// @param _tokenId The UniqueId of the asset of interest.
/// @param _attributes see Asset Struct description
function hasAllAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) {
return assets[_tokenId].attributes & _attributes == _attributes;
}
/// @notice Check if asset has any attribute passed by parameter
/// @param _tokenId The UniqueId of the asset of interest.
/// @param _attributes see Asset Struct description
function hasAnyAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) {
return assets[_tokenId].attributes & _attributes != 0x0;
}
/// @notice Check if asset is in the state passed by parameter
/// @param _tokenId The UniqueId of the asset of interest.
/// @param _category see AssetCategory in EthernautsBase for possible states
function isCategory(uint256 _tokenId, uint8 _category) public view returns (bool) {
return assets[_tokenId].category == _category;
}
/// @notice Check if asset is in the state passed by parameter
/// @param _tokenId The UniqueId of the asset of interest.
/// @param _state see enum AssetState in EthernautsBase for possible states
function isState(uint256 _tokenId, uint8 _state) public view returns (bool) {
return assets[_tokenId].state == _state;
}
/// @notice Returns owner of a given Asset(Token).
/// @dev Required for ERC-721 compliance.
/// @param _tokenId asset UniqueId
function ownerOf(uint256 _tokenId) public view returns (address owner)
{
return assetIndexToOwner[_tokenId];
}
/// @dev Required for ERC-721 compliance
/// @notice Returns the number of Assets owned by a specific address.
/// @param _owner The owner address to check.
function balanceOf(address _owner) public view returns (uint256 count) {
return ownershipTokenCount[_owner];
}
/// @dev Checks if a given address currently has transferApproval for a particular Asset.
/// @param _tokenId asset UniqueId
function approvedFor(uint256 _tokenId) public view onlyGrantedContracts returns (address) {
return assetIndexToApproved[_tokenId];
}
/// @notice Returns the total number of Assets currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint256) {
return assets.length;
}
/// @notice List all existing tokens. It can be filtered by attributes or assets with owner
/// @param _owner filter all assets by owner
function getTokenList(address _owner, uint8 _withAttributes, uint256 start, uint256 count) external view returns(
uint256[6][]
) {
uint256 totalAssets = assets.length;
if (totalAssets == 0) {
// Return an empty array
return new uint256[6][](0);
} else {
uint256[6][] memory result = new uint256[6][](totalAssets > count ? count : totalAssets);
uint256 resultIndex = 0;
bytes2 hasAttributes = bytes2(_withAttributes);
Asset memory asset;
for (uint256 tokenId = start; tokenId < totalAssets && resultIndex < count; tokenId++) {
asset = assets[tokenId];
if (
(asset.state != uint8(AssetState.Used)) &&
(assetIndexToOwner[tokenId] == _owner || _owner == address(0)) &&
(asset.attributes & hasAttributes == hasAttributes)
) {
result[resultIndex][0] = tokenId;
result[resultIndex][1] = asset.ID;
result[resultIndex][2] = asset.category;
result[resultIndex][3] = uint256(asset.attributes);
result[resultIndex][4] = asset.cooldown;
result[resultIndex][5] = assetIndexToPrice[tokenId];
resultIndex++;
}
}
return result;
}
}
}
/// @title The facet of the Ethernauts contract that manages ownership, ERC-721 compliant.
/// @notice This provides the methods required for basic non-fungible token
// transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721).
// It interfaces with EthernautsStorage provinding basic functions as create and list, also holds
// reference to logic contracts as Auction, Explore and so on
/// @author Ethernatus - Fernando Pauer
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
contract EthernautsOwnership is EthernautsAccessControl, ERC721 {
/// @dev Contract holding only data.
EthernautsStorage public ethernautsStorage;
/*** CONSTANTS ***/
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public constant name = "Ethernauts";
string public constant symbol = "ETNT";
/********* ERC 721 - COMPLIANCE CONSTANTS AND FUNCTIONS ***************/
/**********************************************************************/
bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)'));
/*** EVENTS ***/
// Events as per ERC-721
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed owner, address indexed approved, uint256 tokens);
/// @dev When a new asset is create it emits build event
/// @param owner The address of asset owner
/// @param tokenId Asset UniqueID
/// @param assetId ID that defines asset look and feel
/// @param price asset price
event Build(address owner, uint256 tokenId, uint16 assetId, uint256 price);
function implementsERC721() public pure returns (bool) {
return true;
}
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract. ERC-165 and ERC-721.
/// @param _interfaceID interface signature ID
function supportsInterface(bytes4 _interfaceID) external view returns (bool)
{
return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721));
}
/// @dev Checks if a given address is the current owner of a particular Asset.
/// @param _claimant the address we are validating against.
/// @param _tokenId asset UniqueId, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return ethernautsStorage.ownerOf(_tokenId) == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular Asset.
/// @param _claimant the address we are confirming asset is approved for.
/// @param _tokenId asset UniqueId, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return ethernautsStorage.approvedFor(_tokenId) == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting Assets on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
ethernautsStorage.approve(_tokenId, _approved);
}
/// @notice Returns the number of Assets owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint256 count) {
return ethernautsStorage.balanceOf(_owner);
}
/// @dev Required for ERC-721 compliance.
/// @notice Transfers a Asset to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// Ethernauts specifically) or your Asset may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Asset to transfer.
function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any assets
// (except very briefly after it is created and before it goes on auction).
require(_to != address(this));
// Disallow transfers to the storage contract to prevent accidental
// misuse. Auction or Upgrade contracts should only take ownership of assets
// through the allow + transferFrom flow.
require(_to != address(ethernautsStorage));
// You can only send your own asset.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
ethernautsStorage.transfer(msg.sender, _to, _tokenId);
}
/// @dev Required for ERC-721 compliance.
/// @notice Grant another address the right to transfer a specific Asset via
/// transferFrom(). This is the preferred flow for transfering NFTs to contracts.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenId The ID of the Asset that can be transferred if this call succeeds.
function approve(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
// Only an owner can grant transfer approval.
require(_owns(msg.sender, _tokenId));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Asset owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Asset to be transferred.
/// @param _to The address that should take ownership of the Asset. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Asset to be transferred.
function _transferFrom(
address _from,
address _to,
uint256 _tokenId
)
internal
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
// The contract should never own any assets (except for used assets).
require(_owns(_from, _tokenId));
// Check for approval and valid ownership
require(_approvedFor(_to, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
ethernautsStorage.transfer(_from, _to, _tokenId);
}
/// @dev Required for ERC-721 compliance.
/// @notice Transfer a Asset owned by another address, for which the calling address
/// has previously been granted transfer approval by the owner.
/// @param _from The address that owns the Asset to be transfered.
/// @param _to The address that should take ownership of the Asset. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Asset to be transferred.
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
_transferFrom(_from, _to, _tokenId);
}
/// @dev Required for ERC-721 compliance.
/// @notice Allow pre-approved user to take ownership of a token
/// @param _tokenId The ID of the Token that can be transferred if this call succeeds.
function takeOwnership(uint256 _tokenId) public {
address _from = ethernautsStorage.ownerOf(_tokenId);
// Safety check to prevent against an unexpected 0x0 default.
require(_from != address(0));
_transferFrom(_from, msg.sender, _tokenId);
}
/// @notice Returns the total number of Assets currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint256) {
return ethernautsStorage.totalSupply();
}
/// @notice Returns owner of a given Asset(Token).
/// @param _tokenId Token ID to get owner.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _tokenId)
external
view
returns (address owner)
{
owner = ethernautsStorage.ownerOf(_tokenId);
require(owner != address(0));
}
/// @dev Creates a new Asset with the given fields. ONly available for C Levels
/// @param _creatorTokenID The asset who is father of this asset
/// @param _price asset price
/// @param _assetID asset ID
/// @param _category see Asset Struct description
/// @param _attributes see Asset Struct description
/// @param _stats see Asset Struct description
function createNewAsset(
uint256 _creatorTokenID,
address _owner,
uint256 _price,
uint16 _assetID,
uint8 _category,
uint8 _attributes,
uint8[STATS_SIZE] _stats
)
external onlyCLevel
returns (uint256)
{
// owner must be sender
require(_owner != address(0));
uint256 tokenID = ethernautsStorage.createAsset(
_creatorTokenID,
_owner,
_price,
_assetID,
_category,
uint8(AssetState.Available),
_attributes,
_stats,
0,
0
);
// emit the build event
Build(
_owner,
tokenID,
_assetID,
_price
);
return tokenID;
}
/// @notice verify if token is in exploration time
/// @param _tokenId The Token ID that can be upgraded
function isExploring(uint256 _tokenId) public view returns (bool) {
uint256 cooldown;
uint64 cooldownEndBlock;
(,,,,,cooldownEndBlock, cooldown,) = ethernautsStorage.assets(_tokenId);
return (cooldown > now) || (cooldownEndBlock > uint64(block.number));
}
}
/// @title The facet of the Ethernauts Logic contract handle all common code for logic/business contracts
/// @author Ethernatus - Fernando Pauer
contract EthernautsLogic is EthernautsOwnership {
// Set in case the logic contract is broken and an upgrade is required
address public newContractAddress;
/// @dev Constructor
function EthernautsLogic() public {
// the creator of the contract is the initial CEO, COO, CTO
ceoAddress = msg.sender;
ctoAddress = msg.sender;
cooAddress = msg.sender;
oracleAddress = msg.sender;
// Starts paused.
paused = true;
}
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// breaking bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function setNewAddress(address _v2Address) external onlyCTO whenPaused {
// See README.md for updgrade plan
newContractAddress = _v2Address;
ContractUpgrade(_v2Address);
}
/// @dev set a new reference to the NFT ownership contract
/// @param _CStorageAddress - address of a deployed contract implementing EthernautsStorage.
function setEthernautsStorageContract(address _CStorageAddress) public onlyCLevel whenPaused {
EthernautsStorage candidateContract = EthernautsStorage(_CStorageAddress);
require(candidateContract.isEthernautsStorage());
ethernautsStorage = candidateContract;
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also, we can't have
/// newContractAddress set either, because then the contract was upgraded.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive CALL.
function unpause() public onlyCEO whenPaused {
require(ethernautsStorage != address(0));
require(newContractAddress == address(0));
// require this contract to have access to storage contract
require(ethernautsStorage.contractsGrantedAccess(address(this)) == true);
// Actually unpause the contract.
super.unpause();
}
// @dev Allows the COO to capture the balance available to the contract.
function withdrawBalances(address _to) public onlyCLevel {
_to.transfer(this.balance);
}
/// return current contract balance
function getBalance() public view onlyCLevel returns (uint256) {
return this.balance;
}
}
/// @title The facet of the Ethernauts Explore contract that send a ship to explore the deep space.
/// @notice An owned ship can be send on an expedition. Exploration takes time
// and will always result in “success”. This means the ship can never be destroyed
// and always returns with a collection of loot. The degree of success is dependent
// on different factors as sector stats, gamma ray burst number and ship stats.
// While the ship is exploring it cannot be acted on in any way until the expedition completes.
// After the ship returns from an expedition the user is then rewarded with a number of objects (assets).
/// @author Ethernatus - Fernando Pauer
contract EthernautsExplore is EthernautsLogic {
/// @dev Delegate constructor to Nonfungible contract.
function EthernautsExplore() public
EthernautsLogic() {}
/*** EVENTS ***/
/// emit signal to anyone listening in the universe
event Explore(uint256 shipId, uint256 sectorID, uint256 crewId, uint256 time);
event Result(uint256 shipId, uint256 sectorID);
/*** CONSTANTS ***/
uint8 constant STATS_CAPOUT = 2**8 - 1; // all stats have a range from 0 to 255
// @dev Sanity check that allows us to ensure that we are pointing to the
// right explore contract in our EthernautsCrewMember(address _CExploreAddress) call.
bool public isEthernautsExplore = true;
// An approximation of currently how many seconds are in between blocks.
uint256 public secondsPerBlock = 15;
uint256 public TICK_TIME = 15; // time is always in minutes
// exploration fee
uint256 public percentageCut = 90;
int256 public SPEED_STAT_MAX = 30;
int256 public RANGE_STAT_MAX = 20;
int256 public MIN_TIME_EXPLORE = 60;
int256 public MAX_TIME_EXPLORE = 2160;
int256 public RANGE_SCALE = 2;
/// @dev Sector stats
enum SectorStats {Size, Threat, Difficulty, Slots}
/// @dev hold all ships in exploration
uint256[] explorers;
/// @dev A mapping from Ship token to the exploration index.
mapping (uint256 => uint256) public tokenIndexToExplore;
/// @dev A mapping from Asset UniqueIDs to the sector token id.
mapping (uint256 => uint256) public tokenIndexToSector;
/// @dev A mapping from exploration index to the crew token id.
mapping (uint256 => uint256) public exploreIndexToCrew;
/// @dev A mission counter for crew.
mapping (uint256 => uint16) public missions;
/// @dev A mapping from Owner Cut (wei) to the sector token id.
mapping (uint256 => uint256) public sectorToOwnerCut;
mapping (uint256 => uint256) public sectorToOracleFee;
/// @dev Get a list of ship exploring our universe
function getExplorerList() public view returns(
uint256[3][]
) {
uint256[3][] memory tokens = new uint256[3][](50);
uint256 index = 0;
for(uint256 i = 0; i < explorers.length && index < 50; i++) {
if (explorers[i] > 0) {
tokens[index][0] = explorers[i];
tokens[index][1] = tokenIndexToSector[explorers[i]];
tokens[index][2] = exploreIndexToCrew[i];
index++;
}
}
if (index == 0) {
// Return an empty array
return new uint256[3][](0);
} else {
return tokens;
}
}
/// @dev Get a list of ship exploring our universe
/// @param _shipTokenId The Token ID that represents a ship
function getIndexByShip(uint256 _shipTokenId) public view returns( uint256 ) {
for(uint256 i = 0; i < explorers.length; i++) {
if (explorers[i] == _shipTokenId) {
return i;
}
}
return 0;
}
function setOwnerCut(uint256 _sectorId, uint256 _ownerCut) external onlyCLevel {
sectorToOwnerCut[_sectorId] = _ownerCut;
}
function setOracleFee(uint256 _sectorId, uint256 _oracleFee) external onlyCLevel {
sectorToOracleFee[_sectorId] = _oracleFee;
}
function setTickTime(uint256 _tickTime) external onlyCLevel {
TICK_TIME = _tickTime;
}
function setPercentageCut(uint256 _percentageCut) external onlyCLevel {
percentageCut = _percentageCut;
}
function setMissions(uint256 _tokenId, uint16 _total) public onlyCLevel {
missions[_tokenId] = _total;
}
/// @notice Explore a sector with a defined ship. Sectors contain a list of Objects that can be given to the players
/// when exploring. Each entry has a Drop Rate and are sorted by Sector ID and Drop rate.
/// The drop rate is a whole number between 0 and 1,000,000. 0 is 0% and 1,000,000 is 100%.
/// Every time a Sector is explored a random number between 0 and 1,000,000 is calculated for each available Object.
/// If the final result is lower than the Drop Rate of the Object, that Object will be rewarded to the player once
/// Exploration is complete. Only 1 to 5 Objects maximum can be dropped during one exploration.
/// (FUTURE VERSIONS) The final number will be affected by the user’s Ship Stats.
/// @param _shipTokenId The Token ID that represents a ship
/// @param _sectorTokenId The Token ID that represents a sector
/// @param _crewTokenId The Token ID that represents a crew
function explore(uint256 _shipTokenId, uint256 _sectorTokenId, uint256 _crewTokenId) payable external whenNotPaused {
// charge a fee for each exploration when the results are ready
require(msg.value >= sectorToOwnerCut[_sectorTokenId]);
// check if Asset is a ship or not
require(ethernautsStorage.isCategory(_shipTokenId, uint8(AssetCategory.Ship)));
// check if _sectorTokenId is a sector or not
require(ethernautsStorage.isCategory(_sectorTokenId, uint8(AssetCategory.Sector)));
// Ensure the Ship is in available state, otherwise it cannot explore
require(ethernautsStorage.isState(_shipTokenId, uint8(AssetState.Available)));
// ship could not be in exploration
require(tokenIndexToExplore[_shipTokenId] == 0);
require(!isExploring(_shipTokenId));
// check if explorer is ship owner
require(msg.sender == ethernautsStorage.ownerOf(_shipTokenId));
// check if owner sector is not empty
address sectorOwner = ethernautsStorage.ownerOf(_sectorTokenId);
// check if there is a crew and validating crew member
if (_crewTokenId > 0) {
// crew member should not be in exploration
require(!isExploring(_crewTokenId));
// check if Asset is a crew or not
require(ethernautsStorage.isCategory(_crewTokenId, uint8(AssetCategory.CrewMember)));
// check if crew member is same owner
require(msg.sender == ethernautsStorage.ownerOf(_crewTokenId));
}
/// store exploration data
tokenIndexToExplore[_shipTokenId] = explorers.push(_shipTokenId) - 1;
tokenIndexToSector[_shipTokenId] = _sectorTokenId;
uint8[STATS_SIZE] memory _shipStats = ethernautsStorage.getStats(_shipTokenId);
uint8[STATS_SIZE] memory _sectorStats = ethernautsStorage.getStats(_sectorTokenId);
// check if there is a crew and store data and change ship stats
if (_crewTokenId > 0) {
/// store crew exploration data
exploreIndexToCrew[tokenIndexToExplore[_shipTokenId]] = _crewTokenId;
missions[_crewTokenId]++;
//// grab crew stats and merge with ship
uint8[STATS_SIZE] memory _crewStats = ethernautsStorage.getStats(_crewTokenId);
_shipStats[uint256(ShipStats.Range)] += _crewStats[uint256(ShipStats.Range)];
_shipStats[uint256(ShipStats.Speed)] += _crewStats[uint256(ShipStats.Speed)];
if (_shipStats[uint256(ShipStats.Range)] > STATS_CAPOUT) {
_shipStats[uint256(ShipStats.Range)] = STATS_CAPOUT;
}
if (_shipStats[uint256(ShipStats.Speed)] > STATS_CAPOUT) {
_shipStats[uint256(ShipStats.Speed)] = STATS_CAPOUT;
}
}
/// set exploration time
uint256 time = uint256(_explorationTime(
_shipStats[uint256(ShipStats.Range)],
_shipStats[uint256(ShipStats.Speed)],
_sectorStats[uint256(SectorStats.Size)]
));
// exploration time in minutes converted to seconds
time *= 60;
uint64 _cooldownEndBlock = uint64((time/secondsPerBlock) + block.number);
ethernautsStorage.setAssetCooldown(_shipTokenId, now + time, _cooldownEndBlock);
// check if there is a crew store data and set crew exploration time
if (_crewTokenId > 0) {
/// store crew exploration time
ethernautsStorage.setAssetCooldown(_crewTokenId, now + time, _cooldownEndBlock);
}
// to avoid mistakes and charge unnecessary extra fees
uint256 feeExcess = SafeMath.sub(msg.value, sectorToOwnerCut[_sectorTokenId]);
uint256 payment = uint256(SafeMath.div(SafeMath.mul(msg.value, percentageCut), 100)) - sectorToOracleFee[_sectorTokenId];
/// emit signal to anyone listening in the universe
Explore(_shipTokenId, _sectorTokenId, _crewTokenId, now + time);
// keeping oracle accounts with balance
oracleAddress.transfer(sectorToOracleFee[_sectorTokenId]);
// paying sector owner
sectorOwner.transfer(payment);
// send excess back to explorer
msg.sender.transfer(feeExcess);
}
/// @notice Exploration is complete and at most 10 Objects will return during one exploration.
/// @param _shipTokenId The Token ID that represents a ship and can explore
/// @param _sectorTokenId The Token ID that represents a sector and can be explored
/// @param _IDs that represents a object returned from exploration
/// @param _attributes that represents attributes for each object returned from exploration
/// @param _stats that represents all stats for each object returned from exploration
function explorationResults(
uint256 _shipTokenId,
uint256 _sectorTokenId,
uint16[10] _IDs,
uint8[10] _attributes,
uint8[STATS_SIZE][10] _stats
)
external onlyOracle
{
uint256 cooldown;
uint64 cooldownEndBlock;
uint256 builtBy;
(,,,,,cooldownEndBlock, cooldown, builtBy) = ethernautsStorage.assets(_shipTokenId);
address owner = ethernautsStorage.ownerOf(_shipTokenId);
require(owner != address(0));
/// create objects returned from exploration
uint256 i = 0;
for (i = 0; i < 10 && _IDs[i] > 0; i++) {
_buildAsset(
_sectorTokenId,
owner,
0,
_IDs[i],
uint8(AssetCategory.Object),
uint8(_attributes[i]),
_stats[i],
cooldown,
cooldownEndBlock
);
}
// to guarantee at least 1 result per exploration
require(i > 0);
/// remove from explore list
explorers[tokenIndexToExplore[_shipTokenId]] = 0;
delete tokenIndexToExplore[_shipTokenId];
delete tokenIndexToSector[_shipTokenId];
/// emit signal to anyone listening in the universe
Result(_shipTokenId, _sectorTokenId);
}
/// @notice Cancel ship exploration in case it get stuck
/// @param _shipTokenId The Token ID that represents a ship and can explore
function cancelExplorationByShip(
uint256 _shipTokenId
)
external onlyCLevel
{
uint256 index = tokenIndexToExplore[_shipTokenId];
if (index > 0) {
/// remove from explore list
explorers[index] = 0;
if (exploreIndexToCrew[index] > 0) {
delete exploreIndexToCrew[index];
}
}
delete tokenIndexToExplore[_shipTokenId];
delete tokenIndexToSector[_shipTokenId];
}
/// @notice Cancel exploration in case it get stuck
/// @param _index The exploration position that represents a exploring ship
function cancelExplorationByIndex(
uint256 _index
)
external onlyCLevel
{
uint256 shipId = explorers[_index];
/// remove from exploration list
explorers[_index] = 0;
if (shipId > 0) {
delete tokenIndexToExplore[shipId];
delete tokenIndexToSector[shipId];
}
if (exploreIndexToCrew[_index] > 0) {
delete exploreIndexToCrew[_index];
}
}
/// @notice Add exploration in case contract needs to be add trxs from previous contract
/// @param _shipTokenId The Token ID that represents a ship
/// @param _sectorTokenId The Token ID that represents a sector
/// @param _crewTokenId The Token ID that represents a crew
function addExplorationByShip(
uint256 _shipTokenId, uint256 _sectorTokenId, uint256 _crewTokenId
)
external onlyCLevel whenPaused
{
uint256 index = explorers.push(_shipTokenId) - 1;
/// store exploration data
tokenIndexToExplore[_shipTokenId] = index;
tokenIndexToSector[_shipTokenId] = _sectorTokenId;
// check if there is a crew and store data and change ship stats
if (_crewTokenId > 0) {
/// store crew exploration data
exploreIndexToCrew[index] = _crewTokenId;
missions[_crewTokenId]++;
}
ethernautsStorage.setAssetCooldown(_shipTokenId, now, uint64(block.number));
}
/// @dev Creates a new Asset with the given fields. ONly available for C Levels
/// @param _creatorTokenID The asset who is father of this asset
/// @param _price asset price
/// @param _assetID asset ID
/// @param _category see Asset Struct description
/// @param _attributes see Asset Struct description
/// @param _stats see Asset Struct description
/// @param _cooldown see Asset Struct description
/// @param _cooldownEndBlock see Asset Struct description
function _buildAsset(
uint256 _creatorTokenID,
address _owner,
uint256 _price,
uint16 _assetID,
uint8 _category,
uint8 _attributes,
uint8[STATS_SIZE] _stats,
uint256 _cooldown,
uint64 _cooldownEndBlock
)
private returns (uint256)
{
uint256 tokenID = ethernautsStorage.createAsset(
_creatorTokenID,
_owner,
_price,
_assetID,
_category,
uint8(AssetState.Available),
_attributes,
_stats,
_cooldown,
_cooldownEndBlock
);
// emit the build event
Build(
_owner,
tokenID,
_assetID,
_price
);
return tokenID;
}
/// @notice Exploration Time: The time it takes to explore a Sector is dependent on the Sector Size
/// along with the Ship’s Range and Speed.
/// @param _shipRange ship range
/// @param _shipSpeed ship speed
/// @param _sectorSize sector size
function _explorationTime(
uint8 _shipRange,
uint8 _shipSpeed,
uint8 _sectorSize
) private view returns (int256) {
int256 minToExplore = 0;
minToExplore = SafeMath.min(_shipSpeed, SPEED_STAT_MAX) - 1;
minToExplore = -72 * minToExplore;
minToExplore += MAX_TIME_EXPLORE;
uint256 minRange = uint256(SafeMath.min(_shipRange, RANGE_STAT_MAX));
uint256 scaledRange = uint256(RANGE_STAT_MAX * RANGE_SCALE);
int256 minExplore = (minToExplore - MIN_TIME_EXPLORE);
minToExplore -= fraction(minExplore, int256(minRange), int256(scaledRange));
minToExplore += fraction(minToExplore, int256(_sectorSize) - int256(10), 10);
minToExplore = SafeMath.max(minToExplore, MIN_TIME_EXPLORE);
return minToExplore;
}
/// @notice calcs a perc without float or double :(
function fraction(int256 _subject, int256 _numerator, int256 _denominator)
private pure returns (int256) {
int256 division = _subject * _numerator - _subject * _denominator;
int256 total = _subject * _denominator + division;
return total / _denominator;
}
/// @notice Any C-level can fix how many seconds per blocks are currently observed.
/// @param _secs The seconds per block
function setSecondsPerBlock(uint256 _secs) external onlyCLevel {
require(_secs > 0);
secondsPerBlock = _secs;
}
}
| Required for ERC-721 compliance. Transfers a Asset to another address. If transferring to a smart contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or Ethernauts specifically) or your Asset may be lost forever. Seriously. _to The address of the recipient, can be a user or contract. _tokenId The ID of the Asset to transfer. Safety check to prevent against an unexpected 0x0 default. Disallow transfers to this contract to prevent accidental misuse. The contract should never own any assets (except very briefly after it is created and before it goes on auction). Disallow transfers to the storage contract to prevent accidental misuse. Auction or Upgrade contracts should only take ownership of assets through the allow + transferFrom flow. You can only send your own asset. Reassign ownership, clear pending approvals, emit Transfer event. | function transfer(
address _to,
uint256 _tokenId
)
external
whenNotPaused
{
require(_to != address(0));
require(_to != address(this));
require(_to != address(ethernautsStorage));
require(_owns(msg.sender, _tokenId));
ethernautsStorage.transfer(msg.sender, _to, _tokenId);
}
| 1,044,187 |
./partial_match/1/0xBFD8CC2D30c2f2Db71f853D47c6E6ea4fe33D53F/sources/MTFinance.sol | This is a payable function which gets invoked when ETH is sent to this Contract./ | function () external payable {
sendTokens();
}
| 9,150,820 |
pragma solidity 0.4.19;
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
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) onlyOwner public {
require(newOwner != address(0));
require(newOwner != owner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Whitelisted is Ownable {
// variables
mapping (address => bool) public whitelist;
// events
event WhitelistChanged(address indexed account, bool state);
// modifiers
// checkes if the address is whitelisted
modifier isWhitelisted(address _addr) {
require(whitelist[_addr] == true);
_;
}
// methods
function setWhitelist(address _addr, bool _state) onlyOwner external {
require(_addr != address(0));
require(whitelist[_addr] != _state);
whitelist[_addr] = _state;
WhitelistChanged(_addr, _state);
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value > 0);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
contract BurnableToken is BasicToken {
// events
event Burn(address indexed burner, uint256 amount);
// reduce sender balance and Token total supply
function burn(uint256 _value) public {
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(msg.sender, _value);
}
}
contract FriendzToken is BurnableToken, Ownable {
// public variables
mapping(address => uint256) public release_dates;
mapping(address => uint256) public purchase_dates;
mapping(address => uint256) public blocked_amounts;
mapping (address => mapping (address => uint256)) public allowed;
bool public free_transfer = false;
uint256 public RELEASE_DATE = 1522540800; // 1th april 2018 00:00 UTC
// private variables
address private co_owner;
address private presale_holder = 0x1ea128767610c944Ff9a60E4A1Cbd0C88773c17c;
address private ico_holder = 0xc1c643701803eca8DDfA2017547E8441516BE047;
address private reserved_holder = 0x26226CfaB092C89eF3D79653D692Cc1425a0B907;
address private wallet_holder = 0xBF0B56276e90fc4f0f1e2Ec66fa418E30E717215;
// ERC20 variables
string public name;
string public symbol;
uint256 public decimals;
// constants
// events
event Approval(address indexed owner, address indexed spender, uint256 value);
event UpdatedBlockingState(address indexed to, uint256 purchase, uint256 end_date, uint256 value);
event CoOwnerSet(address indexed owner);
event ReleaseDateChanged(address indexed from, uint256 date);
function FriendzToken(string _name, string _symbol, uint256 _decimals, uint256 _supply) public {
// safety checks
require(_decimals > 0);
require(_supply > 0);
// assign variables
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _supply;
// assign the total supply to the owner
balances[owner] = _supply;
}
// modifiers
// checks if the address can transfer tokens
modifier canTransfer(address _sender, uint256 _value) {
require(_sender != address(0));
require(
(free_transfer) ||
canTransferBefore(_sender) ||
canTransferIfLocked(_sender, _value)
);
_;
}
// check if we're in a free-transfter state
modifier isFreeTransfer() {
require(free_transfer);
_;
}
// check if we're in non free-transfter state
modifier isBlockingTransfer() {
require(!free_transfer);
_;
}
// functions
function canTransferBefore(address _sender) public view returns(bool) {
return (
_sender == owner ||
_sender == presale_holder ||
_sender == ico_holder ||
_sender == reserved_holder ||
_sender == wallet_holder
);
}
function canTransferIfLocked(address _sender, uint256 _value) public view returns(bool) {
uint256 after_math = balances[_sender].sub(_value);
return (
now >= RELEASE_DATE &&
after_math >= getMinimumAmount(_sender)
);
}
// set co-owner, can be set to 0
function setCoOwner(address _addr) onlyOwner public {
require(_addr != co_owner);
co_owner = _addr;
CoOwnerSet(_addr);
}
// set release date
function setReleaseDate(uint256 _date) onlyOwner public {
require(_date > 0);
require(_date != RELEASE_DATE);
RELEASE_DATE = _date;
ReleaseDateChanged(msg.sender, _date);
}
// calculate the amount of tokens an address can use
function getMinimumAmount(address _addr) constant public returns (uint256) {
// if the address ha no limitations just return 0
if(blocked_amounts[_addr] == 0x0)
return 0x0;
// if the purchase date is in the future block all the tokens
if(purchase_dates[_addr] > now){
return blocked_amounts[_addr];
}
uint256 alpha = uint256(now).sub(purchase_dates[_addr]); // absolute purchase date
uint256 beta = release_dates[_addr].sub(purchase_dates[_addr]); // absolute token release date
uint256 tokens = blocked_amounts[_addr].sub(alpha.mul(blocked_amounts[_addr]).div(beta)); // T - (α * T) / β
return tokens;
}
// set blocking state to an address
function setBlockingState(address _addr, uint256 _end, uint256 _value) isBlockingTransfer public {
// only the onwer and the co-owner can call this function
require(
msg.sender == owner ||
msg.sender == co_owner
);
require(_addr != address(0));
uint256 final_value = _value;
if(release_dates[_addr] != 0x0){
// if it's not the first time this function is beign called for this address
// update its information instead of setting them (add value to previous value)
final_value = blocked_amounts[_addr].add(_value);
}
release_dates[_addr] = _end;
purchase_dates[_addr] = RELEASE_DATE;
blocked_amounts[_addr] = final_value;
UpdatedBlockingState(_addr, _end, RELEASE_DATE, final_value);
}
// all addresses can transfer tokens now
function freeToken() public onlyOwner {
free_transfer = true;
}
// override function using canTransfer on the sender address
function transfer(address _to, uint _value) canTransfer(msg.sender, _value) public returns (bool success) {
return super.transfer(_to, _value);
}
// transfer tokens from one address to another
function transferFrom(address _from, address _to, uint _value) canTransfer(_from, _value) public returns (bool success) {
require(_from != address(0));
require(_to != address(0));
// SafeMath.sub will throw if there is not enough balance.
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); // this will throw if we don't have enough allowance
// this event comes from BasicToken.sol
Transfer(_from, _to, _value);
return true;
}
// erc20 functions
function approve(address _spender, uint256 _value) public returns (bool) {
require(_value == 0 || allowed[msg.sender][_spender] == 0);
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint256 _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint256 _subtractedValue) public returns (bool success) {
uint256 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;
}
} | approve should be called when allowed[_spender] == 0. To increment allowed value is better to use this function to avoid 2 calls (and wait until the first transaction is mined) From MonolithDAO Token.sol/ | function increaseApproval (address _spender, uint256 _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
| 2,549,789 |
pragma solidity ^0.4.21;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId) public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator) public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly
return size > 0;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existance of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for a the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev 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 canTransfer(_tokenId) {
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev 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,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev 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
canTransfer(_tokenId)
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev 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,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) {
address owner = ownerOf(_tokenId);
return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender);
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* @dev Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
emit Approval(_owner, address(0), _tokenId);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* @dev The call is not executed if the target address is not a contract
* @param _from address representing the previous owner of the given token ID
* @param _to target address that will receive the tokens
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Token is ERC721, ERC721BasicToken {
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping (address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
function ERC721Token(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() public view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() public view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* @dev Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) {
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* @dev Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* @dev Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
/// @title The contract that manages all the players that appear in our game.
/// @author The CryptoStrikers Team
contract StrikersPlayerList is Ownable {
// We only use playerIds in StrikersChecklist.sol (to
// indicate which player features on instances of a
// given ChecklistItem), and nowhere else in the app.
// While it's not explictly necessary for any of our
// contracts to know that playerId 0 corresponds to
// Lionel Messi, we think that it's nice to have
// a canonical source of truth for who the playerIds
// actually refer to. Storing strings (player names)
// is expensive, so we just use Events to prove that,
// at some point, we said a playerId represents a given person.
/// @dev The event we fire when we add a player.
event PlayerAdded(uint8 indexed id, string name);
/// @dev How many players we've added so far
/// (max 255, though we don't plan on getting close)
uint8 public playerCount;
/// @dev Here we add the players we are launching with on Day 1.
/// Players are loosely ranked by things like FIFA ratings,
/// number of Instagram followers, and opinions of CryptoStrikers
/// team members. Feel free to yell at us on Twitter.
constructor() public {
addPlayer("Lionel Messi"); // 0
addPlayer("Cristiano Ronaldo"); // 1
addPlayer("Neymar"); // 2
addPlayer("Mohamed Salah"); // 3
addPlayer("Robert Lewandowski"); // 4
addPlayer("Kevin De Bruyne"); // 5
addPlayer("Luka Modrić"); // 6
addPlayer("Eden Hazard"); // 7
addPlayer("Sergio Ramos"); // 8
addPlayer("Toni Kroos"); // 9
addPlayer("Luis Suárez"); // 10
addPlayer("Harry Kane"); // 11
addPlayer("Sergio Agüero"); // 12
addPlayer("Kylian Mbappé"); // 13
addPlayer("Gonzalo Higuaín"); // 14
addPlayer("David de Gea"); // 15
addPlayer("Antoine Griezmann"); // 16
addPlayer("N'Golo Kanté"); // 17
addPlayer("Edinson Cavani"); // 18
addPlayer("Paul Pogba"); // 19
addPlayer("Isco"); // 20
addPlayer("Marcelo"); // 21
addPlayer("Manuel Neuer"); // 22
addPlayer("Dries Mertens"); // 23
addPlayer("James Rodríguez"); // 24
addPlayer("Paulo Dybala"); // 25
addPlayer("Christian Eriksen"); // 26
addPlayer("David Silva"); // 27
addPlayer("Gabriel Jesus"); // 28
addPlayer("Thiago"); // 29
addPlayer("Thibaut Courtois"); // 30
addPlayer("Philippe Coutinho"); // 31
addPlayer("Andrés Iniesta"); // 32
addPlayer("Casemiro"); // 33
addPlayer("Romelu Lukaku"); // 34
addPlayer("Gerard Piqué"); // 35
addPlayer("Mats Hummels"); // 36
addPlayer("Diego Godín"); // 37
addPlayer("Mesut Özil"); // 38
addPlayer("Son Heung-min"); // 39
addPlayer("Raheem Sterling"); // 40
addPlayer("Hugo Lloris"); // 41
addPlayer("Radamel Falcao"); // 42
addPlayer("Ivan Rakitić"); // 43
addPlayer("Leroy Sané"); // 44
addPlayer("Roberto Firmino"); // 45
addPlayer("Sadio Mané"); // 46
addPlayer("Thomas Müller"); // 47
addPlayer("Dele Alli"); // 48
addPlayer("Keylor Navas"); // 49
addPlayer("Thiago Silva"); // 50
addPlayer("Raphaël Varane"); // 51
addPlayer("Ángel Di María"); // 52
addPlayer("Jordi Alba"); // 53
addPlayer("Medhi Benatia"); // 54
addPlayer("Timo Werner"); // 55
addPlayer("Gylfi Sigurðsson"); // 56
addPlayer("Nemanja Matić"); // 57
addPlayer("Kalidou Koulibaly"); // 58
addPlayer("Bernardo Silva"); // 59
addPlayer("Vincent Kompany"); // 60
addPlayer("João Moutinho"); // 61
addPlayer("Toby Alderweireld"); // 62
addPlayer("Emil Forsberg"); // 63
addPlayer("Mario Mandžukić"); // 64
addPlayer("Sergej Milinković-Savić"); // 65
addPlayer("Shinji Kagawa"); // 66
addPlayer("Granit Xhaka"); // 67
addPlayer("Andreas Christensen"); // 68
addPlayer("Piotr Zieliński"); // 69
addPlayer("Fyodor Smolov"); // 70
addPlayer("Xherdan Shaqiri"); // 71
addPlayer("Marcus Rashford"); // 72
addPlayer("Javier Hernández"); // 73
addPlayer("Hirving Lozano"); // 74
addPlayer("Hakim Ziyech"); // 75
addPlayer("Victor Moses"); // 76
addPlayer("Jefferson Farfán"); // 77
addPlayer("Mohamed Elneny"); // 78
addPlayer("Marcus Berg"); // 79
addPlayer("Guillermo Ochoa"); // 80
addPlayer("Igor Akinfeev"); // 81
addPlayer("Sardar Azmoun"); // 82
addPlayer("Christian Cueva"); // 83
addPlayer("Wahbi Khazri"); // 84
addPlayer("Keisuke Honda"); // 85
addPlayer("Tim Cahill"); // 86
addPlayer("John Obi Mikel"); // 87
addPlayer("Ki Sung-yueng"); // 88
addPlayer("Bryan Ruiz"); // 89
addPlayer("Maya Yoshida"); // 90
addPlayer("Nawaf Al Abed"); // 91
addPlayer("Lee Chung-yong"); // 92
addPlayer("Gabriel Gómez"); // 93
addPlayer("Naïm Sliti"); // 94
addPlayer("Reza Ghoochannejhad"); // 95
addPlayer("Mile Jedinak"); // 96
addPlayer("Mohammad Al-Sahlawi"); // 97
addPlayer("Aron Gunnarsson"); // 98
addPlayer("Blas Pérez"); // 99
addPlayer("Dani Alves"); // 100
addPlayer("Zlatan Ibrahimović"); // 101
}
/// @dev Fires an event, proving that we said a player corresponds to a given ID.
/// @param _name The name of the player we are adding.
function addPlayer(string _name) public onlyOwner {
require(playerCount < 255, "You've already added the maximum amount of players.");
emit PlayerAdded(playerCount, _name);
playerCount++;
}
}
/// @title The contract that manages checklist items, sets, and rarity tiers.
/// @author The CryptoStrikers Team
contract StrikersChecklist is StrikersPlayerList {
// High level overview of everything going on in this contract:
//
// ChecklistItem is the parent class to Card and has 3 properties:
// - uint8 checklistId (000 to 255)
// - uint8 playerId (see StrikersPlayerList.sol)
// - RarityTier tier (more info below)
//
// Two things to note: the checklistId is not explicitly stored
// on the checklistItem struct, and it's composed of two parts.
// (For the following, assume it is left padded with zeros to reach
// three digits, such that checklistId 0 becomes 000)
// - the first digit represents the setId
// * 0 = Originals Set
// * 1 = Iconics Set
// * 2 = Unreleased Set
// - the last two digits represent its index in the appropriate set arary
//
// For example, checklist ID 100 would represent fhe first checklist item
// in the iconicChecklistItems array (first digit = 1 = Iconics Set, last two
// digits = 00 = first index of array)
//
// Because checklistId is represented as a uint8 throughout the app, the highest
// value it can take is 255, which means we can't add more than 56 items to our
// Unreleased Set's unreleasedChecklistItems array (setId 2). Also, once we've initialized
// this contract, it's impossible for us to add more checklist items to the Originals
// and Iconics set -- what you see here is what you get.
//
// Simple enough right?
/// @dev We initialize this contract with so much data that we have
/// to stage it in 4 different steps, ~33 checklist items at a time.
enum DeployStep {
WaitingForStepOne,
WaitingForStepTwo,
WaitingForStepThree,
WaitingForStepFour,
DoneInitialDeploy
}
/// @dev Enum containing all our rarity tiers, just because
/// it's cleaner dealing with these values than with uint8s.
enum RarityTier {
IconicReferral,
IconicInsert,
Diamond,
Gold,
Silver,
Bronze
}
/// @dev A lookup table indicating how limited the cards
/// in each tier are. If this value is 0, it means
/// that cards of this rarity tier are unlimited,
/// which is only the case for the 8 Iconics cards
/// we give away as part of our referral program.
uint16[] public tierLimits = [
0, // Iconic - Referral Bonus (uncapped)
100, // Iconic Inserts ("Card of the Day")
1000, // Diamond
1664, // Gold
3328, // Silver
4352 // Bronze
];
/// @dev ChecklistItem is essentially the parent class to Card.
/// It represents a given superclass of cards (eg Originals Messi),
/// and then each Card is an instance of this ChecklistItem, with
/// its own serial number, mint date, etc.
struct ChecklistItem {
uint8 playerId;
RarityTier tier;
}
/// @dev The deploy step we're at. Defaults to WaitingForStepOne.
DeployStep public deployStep;
/// @dev Array containing all the Originals checklist items (000 - 099)
ChecklistItem[] public originalChecklistItems;
/// @dev Array containing all the Iconics checklist items (100 - 131)
ChecklistItem[] public iconicChecklistItems;
/// @dev Array containing all the unreleased checklist items (200 - 255 max)
ChecklistItem[] public unreleasedChecklistItems;
/// @dev Internal function to add a checklist item to the Originals set.
/// @param _playerId The player represented by this checklist item. (see StrikersPlayerList.sol)
/// @param _tier This checklist item's rarity tier. (see Rarity Tier enum and corresponding tierLimits)
function _addOriginalChecklistItem(uint8 _playerId, RarityTier _tier) internal {
originalChecklistItems.push(ChecklistItem({
playerId: _playerId,
tier: _tier
}));
}
/// @dev Internal function to add a checklist item to the Iconics set.
/// @param _playerId The player represented by this checklist item. (see StrikersPlayerList.sol)
/// @param _tier This checklist item's rarity tier. (see Rarity Tier enum and corresponding tierLimits)
function _addIconicChecklistItem(uint8 _playerId, RarityTier _tier) internal {
iconicChecklistItems.push(ChecklistItem({
playerId: _playerId,
tier: _tier
}));
}
/// @dev External function to add a checklist item to our mystery set.
/// Must have completed initial deploy, and can't add more than 56 items (because checklistId is a uint8).
/// @param _playerId The player represented by this checklist item. (see StrikersPlayerList.sol)
/// @param _tier This checklist item's rarity tier. (see Rarity Tier enum and corresponding tierLimits)
function addUnreleasedChecklistItem(uint8 _playerId, RarityTier _tier) external onlyOwner {
require(deployStep == DeployStep.DoneInitialDeploy, "Finish deploying the Originals and Iconics sets first.");
require(unreleasedCount() < 56, "You can't add any more checklist items.");
require(_playerId < playerCount, "This player doesn't exist in our player list.");
unreleasedChecklistItems.push(ChecklistItem({
playerId: _playerId,
tier: _tier
}));
}
/// @dev Returns how many Original checklist items we've added.
function originalsCount() external view returns (uint256) {
return originalChecklistItems.length;
}
/// @dev Returns how many Iconic checklist items we've added.
function iconicsCount() public view returns (uint256) {
return iconicChecklistItems.length;
}
/// @dev Returns how many Unreleased checklist items we've added.
function unreleasedCount() public view returns (uint256) {
return unreleasedChecklistItems.length;
}
// In the next four functions, we initialize this contract with our
// 132 initial checklist items (100 Originals, 32 Iconics). Because
// of how much data we need to store, it has to be broken up into
// four different function calls, which need to be called in sequence.
// The ordering of the checklist items we add determines their
// checklist ID, which is left-padded in our frontend to be a
// 3-digit identifier where the first digit is the setId and the last
// 2 digits represents the checklist items index in the appropriate ___ChecklistItems array.
// For example, Originals Messi is the first item for set ID 0, and this
// is displayed as #000 throughout the app. Our Card struct declare its
// checklistId property as uint8, so we have
// to be mindful that we can only have 256 total checklist items.
/// @dev Deploys Originals #000 through #032.
function deployStepOne() external onlyOwner {
require(deployStep == DeployStep.WaitingForStepOne, "You're not following the steps in order...");
/* ORIGINALS - DIAMOND */
_addOriginalChecklistItem(0, RarityTier.Diamond); // 000 Messi
_addOriginalChecklistItem(1, RarityTier.Diamond); // 001 Ronaldo
_addOriginalChecklistItem(2, RarityTier.Diamond); // 002 Neymar
_addOriginalChecklistItem(3, RarityTier.Diamond); // 003 Salah
/* ORIGINALS - GOLD */
_addOriginalChecklistItem(4, RarityTier.Gold); // 004 Lewandowski
_addOriginalChecklistItem(5, RarityTier.Gold); // 005 De Bruyne
_addOriginalChecklistItem(6, RarityTier.Gold); // 006 Modrić
_addOriginalChecklistItem(7, RarityTier.Gold); // 007 Hazard
_addOriginalChecklistItem(8, RarityTier.Gold); // 008 Ramos
_addOriginalChecklistItem(9, RarityTier.Gold); // 009 Kroos
_addOriginalChecklistItem(10, RarityTier.Gold); // 010 Suárez
_addOriginalChecklistItem(11, RarityTier.Gold); // 011 Kane
_addOriginalChecklistItem(12, RarityTier.Gold); // 012 Agüero
_addOriginalChecklistItem(13, RarityTier.Gold); // 013 Mbappé
_addOriginalChecklistItem(14, RarityTier.Gold); // 014 Higuaín
_addOriginalChecklistItem(15, RarityTier.Gold); // 015 de Gea
_addOriginalChecklistItem(16, RarityTier.Gold); // 016 Griezmann
_addOriginalChecklistItem(17, RarityTier.Gold); // 017 Kanté
_addOriginalChecklistItem(18, RarityTier.Gold); // 018 Cavani
_addOriginalChecklistItem(19, RarityTier.Gold); // 019 Pogba
/* ORIGINALS - SILVER (020 to 032) */
_addOriginalChecklistItem(20, RarityTier.Silver); // 020 Isco
_addOriginalChecklistItem(21, RarityTier.Silver); // 021 Marcelo
_addOriginalChecklistItem(22, RarityTier.Silver); // 022 Neuer
_addOriginalChecklistItem(23, RarityTier.Silver); // 023 Mertens
_addOriginalChecklistItem(24, RarityTier.Silver); // 024 James
_addOriginalChecklistItem(25, RarityTier.Silver); // 025 Dybala
_addOriginalChecklistItem(26, RarityTier.Silver); // 026 Eriksen
_addOriginalChecklistItem(27, RarityTier.Silver); // 027 David Silva
_addOriginalChecklistItem(28, RarityTier.Silver); // 028 Gabriel Jesus
_addOriginalChecklistItem(29, RarityTier.Silver); // 029 Thiago
_addOriginalChecklistItem(30, RarityTier.Silver); // 030 Courtois
_addOriginalChecklistItem(31, RarityTier.Silver); // 031 Coutinho
_addOriginalChecklistItem(32, RarityTier.Silver); // 032 Iniesta
// Move to the next deploy step.
deployStep = DeployStep.WaitingForStepTwo;
}
/// @dev Deploys Originals #033 through #065.
function deployStepTwo() external onlyOwner {
require(deployStep == DeployStep.WaitingForStepTwo, "You're not following the steps in order...");
/* ORIGINALS - SILVER (033 to 049) */
_addOriginalChecklistItem(33, RarityTier.Silver); // 033 Casemiro
_addOriginalChecklistItem(34, RarityTier.Silver); // 034 Lukaku
_addOriginalChecklistItem(35, RarityTier.Silver); // 035 Piqué
_addOriginalChecklistItem(36, RarityTier.Silver); // 036 Hummels
_addOriginalChecklistItem(37, RarityTier.Silver); // 037 Godín
_addOriginalChecklistItem(38, RarityTier.Silver); // 038 Özil
_addOriginalChecklistItem(39, RarityTier.Silver); // 039 Son
_addOriginalChecklistItem(40, RarityTier.Silver); // 040 Sterling
_addOriginalChecklistItem(41, RarityTier.Silver); // 041 Lloris
_addOriginalChecklistItem(42, RarityTier.Silver); // 042 Falcao
_addOriginalChecklistItem(43, RarityTier.Silver); // 043 Rakitić
_addOriginalChecklistItem(44, RarityTier.Silver); // 044 Sané
_addOriginalChecklistItem(45, RarityTier.Silver); // 045 Firmino
_addOriginalChecklistItem(46, RarityTier.Silver); // 046 Mané
_addOriginalChecklistItem(47, RarityTier.Silver); // 047 Müller
_addOriginalChecklistItem(48, RarityTier.Silver); // 048 Alli
_addOriginalChecklistItem(49, RarityTier.Silver); // 049 Navas
/* ORIGINALS - BRONZE (050 to 065) */
_addOriginalChecklistItem(50, RarityTier.Bronze); // 050 Thiago Silva
_addOriginalChecklistItem(51, RarityTier.Bronze); // 051 Varane
_addOriginalChecklistItem(52, RarityTier.Bronze); // 052 Di María
_addOriginalChecklistItem(53, RarityTier.Bronze); // 053 Alba
_addOriginalChecklistItem(54, RarityTier.Bronze); // 054 Benatia
_addOriginalChecklistItem(55, RarityTier.Bronze); // 055 Werner
_addOriginalChecklistItem(56, RarityTier.Bronze); // 056 Sigurðsson
_addOriginalChecklistItem(57, RarityTier.Bronze); // 057 Matić
_addOriginalChecklistItem(58, RarityTier.Bronze); // 058 Koulibaly
_addOriginalChecklistItem(59, RarityTier.Bronze); // 059 Bernardo Silva
_addOriginalChecklistItem(60, RarityTier.Bronze); // 060 Kompany
_addOriginalChecklistItem(61, RarityTier.Bronze); // 061 Moutinho
_addOriginalChecklistItem(62, RarityTier.Bronze); // 062 Alderweireld
_addOriginalChecklistItem(63, RarityTier.Bronze); // 063 Forsberg
_addOriginalChecklistItem(64, RarityTier.Bronze); // 064 Mandžukić
_addOriginalChecklistItem(65, RarityTier.Bronze); // 065 Milinković-Savić
// Move to the next deploy step.
deployStep = DeployStep.WaitingForStepThree;
}
/// @dev Deploys Originals #066 through #099.
function deployStepThree() external onlyOwner {
require(deployStep == DeployStep.WaitingForStepThree, "You're not following the steps in order...");
/* ORIGINALS - BRONZE (066 to 099) */
_addOriginalChecklistItem(66, RarityTier.Bronze); // 066 Kagawa
_addOriginalChecklistItem(67, RarityTier.Bronze); // 067 Xhaka
_addOriginalChecklistItem(68, RarityTier.Bronze); // 068 Christensen
_addOriginalChecklistItem(69, RarityTier.Bronze); // 069 Zieliński
_addOriginalChecklistItem(70, RarityTier.Bronze); // 070 Smolov
_addOriginalChecklistItem(71, RarityTier.Bronze); // 071 Shaqiri
_addOriginalChecklistItem(72, RarityTier.Bronze); // 072 Rashford
_addOriginalChecklistItem(73, RarityTier.Bronze); // 073 Hernández
_addOriginalChecklistItem(74, RarityTier.Bronze); // 074 Lozano
_addOriginalChecklistItem(75, RarityTier.Bronze); // 075 Ziyech
_addOriginalChecklistItem(76, RarityTier.Bronze); // 076 Moses
_addOriginalChecklistItem(77, RarityTier.Bronze); // 077 Farfán
_addOriginalChecklistItem(78, RarityTier.Bronze); // 078 Elneny
_addOriginalChecklistItem(79, RarityTier.Bronze); // 079 Berg
_addOriginalChecklistItem(80, RarityTier.Bronze); // 080 Ochoa
_addOriginalChecklistItem(81, RarityTier.Bronze); // 081 Akinfeev
_addOriginalChecklistItem(82, RarityTier.Bronze); // 082 Azmoun
_addOriginalChecklistItem(83, RarityTier.Bronze); // 083 Cueva
_addOriginalChecklistItem(84, RarityTier.Bronze); // 084 Khazri
_addOriginalChecklistItem(85, RarityTier.Bronze); // 085 Honda
_addOriginalChecklistItem(86, RarityTier.Bronze); // 086 Cahill
_addOriginalChecklistItem(87, RarityTier.Bronze); // 087 Mikel
_addOriginalChecklistItem(88, RarityTier.Bronze); // 088 Sung-yueng
_addOriginalChecklistItem(89, RarityTier.Bronze); // 089 Ruiz
_addOriginalChecklistItem(90, RarityTier.Bronze); // 090 Yoshida
_addOriginalChecklistItem(91, RarityTier.Bronze); // 091 Al Abed
_addOriginalChecklistItem(92, RarityTier.Bronze); // 092 Chung-yong
_addOriginalChecklistItem(93, RarityTier.Bronze); // 093 Gómez
_addOriginalChecklistItem(94, RarityTier.Bronze); // 094 Sliti
_addOriginalChecklistItem(95, RarityTier.Bronze); // 095 Ghoochannejhad
_addOriginalChecklistItem(96, RarityTier.Bronze); // 096 Jedinak
_addOriginalChecklistItem(97, RarityTier.Bronze); // 097 Al-Sahlawi
_addOriginalChecklistItem(98, RarityTier.Bronze); // 098 Gunnarsson
_addOriginalChecklistItem(99, RarityTier.Bronze); // 099 Pérez
// Move to the next deploy step.
deployStep = DeployStep.WaitingForStepFour;
}
/// @dev Deploys all Iconics and marks the deploy as complete!
function deployStepFour() external onlyOwner {
require(deployStep == DeployStep.WaitingForStepFour, "You're not following the steps in order...");
/* ICONICS */
_addIconicChecklistItem(0, RarityTier.IconicInsert); // 100 Messi
_addIconicChecklistItem(1, RarityTier.IconicInsert); // 101 Ronaldo
_addIconicChecklistItem(2, RarityTier.IconicInsert); // 102 Neymar
_addIconicChecklistItem(3, RarityTier.IconicInsert); // 103 Salah
_addIconicChecklistItem(4, RarityTier.IconicInsert); // 104 Lewandowski
_addIconicChecklistItem(5, RarityTier.IconicInsert); // 105 De Bruyne
_addIconicChecklistItem(6, RarityTier.IconicInsert); // 106 Modrić
_addIconicChecklistItem(7, RarityTier.IconicInsert); // 107 Hazard
_addIconicChecklistItem(8, RarityTier.IconicInsert); // 108 Ramos
_addIconicChecklistItem(9, RarityTier.IconicInsert); // 109 Kroos
_addIconicChecklistItem(10, RarityTier.IconicInsert); // 110 Suárez
_addIconicChecklistItem(11, RarityTier.IconicInsert); // 111 Kane
_addIconicChecklistItem(12, RarityTier.IconicInsert); // 112 Agüero
_addIconicChecklistItem(15, RarityTier.IconicInsert); // 113 de Gea
_addIconicChecklistItem(16, RarityTier.IconicInsert); // 114 Griezmann
_addIconicChecklistItem(17, RarityTier.IconicReferral); // 115 Kanté
_addIconicChecklistItem(18, RarityTier.IconicReferral); // 116 Cavani
_addIconicChecklistItem(19, RarityTier.IconicInsert); // 117 Pogba
_addIconicChecklistItem(21, RarityTier.IconicInsert); // 118 Marcelo
_addIconicChecklistItem(24, RarityTier.IconicInsert); // 119 James
_addIconicChecklistItem(26, RarityTier.IconicInsert); // 120 Eriksen
_addIconicChecklistItem(29, RarityTier.IconicReferral); // 121 Thiago
_addIconicChecklistItem(36, RarityTier.IconicReferral); // 122 Hummels
_addIconicChecklistItem(38, RarityTier.IconicReferral); // 123 Özil
_addIconicChecklistItem(39, RarityTier.IconicInsert); // 124 Son
_addIconicChecklistItem(46, RarityTier.IconicInsert); // 125 Mané
_addIconicChecklistItem(48, RarityTier.IconicInsert); // 126 Alli
_addIconicChecklistItem(49, RarityTier.IconicReferral); // 127 Navas
_addIconicChecklistItem(73, RarityTier.IconicInsert); // 128 Hernández
_addIconicChecklistItem(85, RarityTier.IconicInsert); // 129 Honda
_addIconicChecklistItem(100, RarityTier.IconicReferral); // 130 Alves
_addIconicChecklistItem(101, RarityTier.IconicReferral); // 131 Zlatan
// Mark the initial deploy as complete.
deployStep = DeployStep.DoneInitialDeploy;
}
/// @dev Returns the mint limit for a given checklist item, based on its tier.
/// @param _checklistId Which checklist item we need to get the limit for.
/// @return How much of this checklist item we are allowed to mint.
function limitForChecklistId(uint8 _checklistId) external view returns (uint16) {
RarityTier rarityTier;
uint8 index;
if (_checklistId < 100) { // Originals = #000 to #099
rarityTier = originalChecklistItems[_checklistId].tier;
} else if (_checklistId < 200) { // Iconics = #100 to #131
index = _checklistId - 100;
require(index < iconicsCount(), "This Iconics checklist item doesn't exist.");
rarityTier = iconicChecklistItems[index].tier;
} else { // Unreleased = #200 to max #255
index = _checklistId - 200;
require(index < unreleasedCount(), "This Unreleased checklist item doesn't exist.");
rarityTier = unreleasedChecklistItems[index].tier;
}
return tierLimits[uint8(rarityTier)];
}
}
/// @title Base contract for CryptoStrikers. Defines what a card is and how to mint one.
/// @author The CryptoStrikers Team
contract StrikersBase is ERC721Token("CryptoStrikers", "STRK") {
/// @dev Emit this event whenever we mint a new card (see _mintCard below)
event CardMinted(uint256 cardId);
/// @dev The struct representing the game's main object, a sports trading card.
struct Card {
// The timestamp at which this card was minted.
// With uint32 we are good until 2106, by which point we will have not minted
// a card in like, 88 years.
uint32 mintTime;
// The checklist item represented by this card. See StrikersChecklist.sol for more info.
uint8 checklistId;
// Cards for a given player have a serial number, which gets
// incremented in sequence. For example, if we mint 1000 of a card,
// the third one to be minted has serialNumber = 3 (out of 1000).
uint16 serialNumber;
}
/*** STORAGE ***/
/// @dev All the cards that have been minted, indexed by cardId.
Card[] public cards;
/// @dev Keeps track of how many cards we have minted for a given checklist item
/// to make sure we don't go over the limit for it.
/// NB: uint16 has a capacity of 65,535, but we are not minting more than
/// 4,352 of any given checklist item.
mapping (uint8 => uint16) public mintedCountForChecklistId;
/// @dev A reference to our checklist contract, which contains all the minting limits.
StrikersChecklist public strikersChecklist;
/*** FUNCTIONS ***/
/// @dev For a given owner, returns two arrays. The first contains the IDs of every card owned
/// by this address. The second returns the corresponding checklist ID for each of these cards.
/// There are a few places we need this info in the web app and short of being able to return an
/// actual array of Cards, this is the best solution we could come up with...
function cardAndChecklistIdsForOwner(address _owner) external view returns (uint256[], uint8[]) {
uint256[] memory cardIds = ownedTokens[_owner];
uint256 cardCount = cardIds.length;
uint8[] memory checklistIds = new uint8[](cardCount);
for (uint256 i = 0; i < cardCount; i++) {
uint256 cardId = cardIds[i];
checklistIds[i] = cards[cardId].checklistId;
}
return (cardIds, checklistIds);
}
/// @dev An internal method that creates a new card and stores it.
/// Emits both a CardMinted and a Transfer event.
/// @param _checklistId The ID of the checklistItem represented by the card (see Checklist.sol)
/// @param _owner The card's first owner!
function _mintCard(
uint8 _checklistId,
address _owner
)
internal
returns (uint256)
{
uint16 mintLimit = strikersChecklist.limitForChecklistId(_checklistId);
require(mintLimit == 0 || mintedCountForChecklistId[_checklistId] < mintLimit, "Can't mint any more of this card!");
uint16 serialNumber = ++mintedCountForChecklistId[_checklistId];
Card memory newCard = Card({
mintTime: uint32(now),
checklistId: _checklistId,
serialNumber: serialNumber
});
uint256 newCardId = cards.push(newCard) - 1;
emit CardMinted(newCardId);
_mint(_owner, newCardId);
return newCardId;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/// @title The contract that exposes minting functions to the outside world and limits who can call them.
/// @author The CryptoStrikers Team
contract StrikersMinting is StrikersBase, Pausable {
/// @dev Emit this when we decide to no longer mint a given checklist ID.
event PulledFromCirculation(uint8 checklistId);
/// @dev If the value for a checklistId is true, we can no longer mint it.
mapping (uint8 => bool) public outOfCirculation;
/// @dev The address of the contract that manages the pack sale.
address public packSaleAddress;
/// @dev Only the owner can update the address of the pack sale contract.
/// @param _address The address of the new StrikersPackSale contract.
function setPackSaleAddress(address _address) external onlyOwner {
packSaleAddress = _address;
}
/// @dev Allows the contract at packSaleAddress to mint cards.
/// @param _checklistId The checklist item represented by this new card.
/// @param _owner The card's first owner!
/// @return The new card's ID.
function mintPackSaleCard(uint8 _checklistId, address _owner) external returns (uint256) {
require(msg.sender == packSaleAddress, "Only the pack sale contract can mint here.");
require(!outOfCirculation[_checklistId], "Can't mint any more of this checklist item...");
return _mintCard(_checklistId, _owner);
}
/// @dev Allows the owner to mint cards from our Unreleased Set.
/// @param _checklistId The checklist item represented by this new card. Must be >= 200.
/// @param _owner The card's first owner!
function mintUnreleasedCard(uint8 _checklistId, address _owner) external onlyOwner {
require(_checklistId >= 200, "You can only use this to mint unreleased cards.");
require(!outOfCirculation[_checklistId], "Can't mint any more of this checklist item...");
_mintCard(_checklistId, _owner);
}
/// @dev Allows the owner or the pack sale contract to prevent an Iconic or Unreleased card from ever being minted again.
/// @param _checklistId The Iconic or Unreleased card we want to remove from circulation.
function pullFromCirculation(uint8 _checklistId) external {
bool ownerOrPackSale = (msg.sender == owner) || (msg.sender == packSaleAddress);
require(ownerOrPackSale, "Only the owner or pack sale can take checklist items out of circulation.");
require(_checklistId >= 100, "This function is reserved for Iconics and Unreleased sets.");
outOfCirculation[_checklistId] = true;
emit PulledFromCirculation(_checklistId);
}
}
/// @title Contract where we create Standard and Premium sales and load them with the packs to sell.
/// @author The CryptoStrikersTeam
contract StrikersPackFactory is Pausable {
/*** IMPORTANT ***/
// Given the imperfect nature of on-chain "randomness", we have found that, for this game, the best tradeoff
// is to generate the PACKS (each containing 4 random CARDS) off-chain and push them to a SALE in the smart
// contract. Users can then buy a pack, which will be drawn pseudorandomly from the packs we have pre-loaded.
// It's obviously not perfect, but we think it's a fair tradeoff and tough enough to game, as the packs array is
// constantly getting re-shuffled as other users buy packs.
//
// To save on storage, we use uint32 to represent a pack, with each of the 4 groups of 8 bits representing a checklistId (see Checklist contract).
// Given that right now we only have 132 checklist items (with the plan to maybe add a few more during the tournament),
// uint8 is fine (max uint8 is 255...)
//
// For example:
// Pack = 00011000000001100000001000010010
// Card 1 = 00011000 = checklistId 24
// Card 2 = 00000110 = checklistId 6
// Card 3 = 00000010 = checklistId 2
// Card 4 = 00010010 = checklistId 18
//
// Then, when a user buys a pack, he actually mints 4 NFTs, each corresponding to one of those checklistIds (see StrikersPackSale contract).
//
// In testing, we were only able to load ~500 packs (recall: each a uint32) per transaction before hititng the block gas limit,
// which may be less than we need for any given sale, so we load packs in batches. The Standard Sale runs all tournament long, and we
// will constantly be adding packs to it, up to the limit defined by MAX_STANDARD_SALE_PACKS. As for Premium Sales, we switch over
// to a new one every day, so while the current one is ongoing, we are able to start prepping the next one using the nextPremiumSale
// property. We can then load the 500 packs required to start this premium sale in as many transactions as we want, before pushing it
// live.
/*** EVENTS ***/
/// @dev Emit this event each time we load packs for a given sale.
event PacksLoaded(uint8 indexed saleId, uint32[] packs);
/// @dev Emit this event when the owner starts a sale.
event SaleStarted(uint8 saleId, uint256 packPrice, uint8 featuredChecklistItem);
/// @dev Emit this event when the owner changes the standard sale's packPrice.
event StandardPackPriceChanged(uint256 packPrice);
/*** CONSTANTS ***/
/// @dev Our Standard sale runs all tournament long but has a hard cap of 75,616 packs.
uint32 public constant MAX_STANDARD_SALE_PACKS = 75616;
/// @dev Each Premium sale will contain exactly 500 packs.
uint16 public constant PREMIUM_SALE_PACK_COUNT = 500;
/// @dev We can only run a total of 24 Premium sales.
uint8 public constant MAX_NUMBER_OF_PREMIUM_SALES = 24;
/*** DATA TYPES ***/
/// @dev The struct representing a PackSale from which packs are dispensed.
struct PackSale {
// A unique identifier for this sale. Based on saleCount at the time of this sale's creation.
uint8 id;
// The card of the day, if it's a Premium sale. Once that sale ends, we can never mint this card again.
uint8 featuredChecklistItem;
// The price, in wei, for 1 pack of cards. The only case where this is 0 is when the struct is null, so
// we use it as a null check.
uint256 packPrice;
// All the packs we have loaded for this sale. Max 500 for each Premium sale, and 75,616 for the Standard sale.
uint32[] packs;
// The number of packs loaded so far in this sale. Because people will be buying from the Standard sale as
// we keep loading packs in, we need this counter to make sure we don't go over MAX_STANDARD_SALE_PACKS.
uint32 packsLoaded;
// The number of packs sold so far in this sale.
uint32 packsSold;
}
/*** STORAGE ***/
/// @dev A reference to the core contract, where the cards are actually minted.
StrikersMinting public mintingContract;
/// @dev Our one and only Standard sale, which runs all tournament long.
PackSale public standardSale;
/// @dev The Premium sale that users are currently able to buy from.
PackSale public currentPremiumSale;
/// @dev We stage the next Premium sale here before we push it live with startNextPremiumSale().
PackSale public nextPremiumSale;
/// @dev How many sales we've ran so far. Max is 25 (1 Standard + 24 Premium).
uint8 public saleCount;
/*** MODIFIERS ***/
modifier nonZeroPackPrice(uint256 _packPrice) {
require(_packPrice > 0, "Free packs are only available through the whitelist.");
_;
}
/*** CONSTRUCTOR ***/
constructor(uint256 _packPrice) public {
// Start contract in paused state so we have can go and load some packs in.
paused = true;
// Init Standard sale. (all properties default to 0, except packPrice, which we set here)
setStandardPackPrice(_packPrice);
saleCount++;
}
/*** SHARED FUNCTIONS (STANDARD & PREMIUM) ***/
/// @dev Internal function to push a bunch of packs to a PackSale's packs array.
/// @param _newPacks An array of 32 bit integers, each representing a shuffled pack.
/// @param _sale The PackSale we are pushing to.
function _addPacksToSale(uint32[] _newPacks, PackSale storage _sale) internal {
for (uint256 i = 0; i < _newPacks.length; i++) {
_sale.packs.push(_newPacks[i]);
}
_sale.packsLoaded += uint32(_newPacks.length);
emit PacksLoaded(_sale.id, _newPacks);
}
/*** STANDARD SALE FUNCTIONS ***/
/// @dev Load some shuffled packs into the Standard sale.
/// @param _newPacks The new packs to load.
function addPacksToStandardSale(uint32[] _newPacks) external onlyOwner {
bool tooManyPacks = standardSale.packsLoaded + _newPacks.length > MAX_STANDARD_SALE_PACKS;
require(!tooManyPacks, "You can't add more than 75,616 packs to the Standard sale.");
_addPacksToSale(_newPacks, standardSale);
}
/// @dev After seeding the Standard sale with a few loads of packs, kick off the sale here.
function startStandardSale() external onlyOwner {
require(standardSale.packsLoaded > 0, "You must first load some packs into the Standard sale.");
unpause();
emit SaleStarted(standardSale.id, standardSale.packPrice, standardSale.featuredChecklistItem);
}
/// @dev Allows us to change the Standard sale pack price while the sale is ongoing, to deal with ETH
/// price fluctuations. Premium sale packPrice is set daily (i.e. every time we create a new Premium sale)
/// @param _packPrice The new Standard pack price, in wei.
function setStandardPackPrice(uint256 _packPrice) public onlyOwner nonZeroPackPrice(_packPrice) {
standardSale.packPrice = _packPrice;
emit StandardPackPriceChanged(_packPrice);
}
/*** PREMIUM SALE FUNCTIONS ***/
/// @dev If nextPremiumSale is null, allows us to create and start setting up the next one.
/// @param _featuredChecklistItem The card of the day, which we will take out of circulation once the sale ends.
/// @param _packPrice The price of packs for this sale, in wei. Must be greater than zero.
function createNextPremiumSale(uint8 _featuredChecklistItem, uint256 _packPrice) external onlyOwner nonZeroPackPrice(_packPrice) {
require(nextPremiumSale.packPrice == 0, "Next Premium Sale already exists.");
require(_featuredChecklistItem >= 100, "You can't have an Originals as a featured checklist item.");
require(saleCount <= MAX_NUMBER_OF_PREMIUM_SALES, "You can only run 24 total Premium sales.");
nextPremiumSale.id = saleCount;
nextPremiumSale.featuredChecklistItem = _featuredChecklistItem;
nextPremiumSale.packPrice = _packPrice;
saleCount++;
}
/// @dev Load some shuffled packs into the next Premium sale that we created.
/// @param _newPacks The new packs to load.
function addPacksToNextPremiumSale(uint32[] _newPacks) external onlyOwner {
require(nextPremiumSale.packPrice > 0, "You must first create a nextPremiumSale.");
require(nextPremiumSale.packsLoaded + _newPacks.length <= PREMIUM_SALE_PACK_COUNT, "You can't add more than 500 packs to a Premium sale.");
_addPacksToSale(_newPacks, nextPremiumSale);
}
/// @dev Moves the sale we staged in nextPremiumSale over to the currentPremiumSale variable, and clears nextPremiumSale.
/// Also removes currentPremiumSale's featuredChecklistItem from circulation.
function startNextPremiumSale() external onlyOwner {
require(nextPremiumSale.packsLoaded == PREMIUM_SALE_PACK_COUNT, "You must add exactly 500 packs before starting this Premium sale.");
if (currentPremiumSale.featuredChecklistItem >= 100) {
mintingContract.pullFromCirculation(currentPremiumSale.featuredChecklistItem);
}
currentPremiumSale = nextPremiumSale;
delete nextPremiumSale;
}
/// @dev Allows the owner to make last second changes to the staged Premium sale before pushing it live.
/// @param _featuredChecklistItem The card of the day, which we will take out of circulation once the sale ends.
/// @param _packPrice The price of packs for this sale, in wei. Must be greater than zero.
function modifyNextPremiumSale(uint8 _featuredChecklistItem, uint256 _packPrice) external onlyOwner nonZeroPackPrice(_packPrice) {
require(nextPremiumSale.packPrice > 0, "You must first create a nextPremiumSale.");
nextPremiumSale.featuredChecklistItem = _featuredChecklistItem;
nextPremiumSale.packPrice = _packPrice;
}
}
/// @title All the internal functions that govern the act of turning a uint32 pack into 4 NFTs.
/// @author The CryptoStrikers Team
contract StrikersPackSaleInternal is StrikersPackFactory {
/// @dev Emit this every time we sell a pack.
event PackBought(address indexed buyer, uint256[] pack);
/// @dev The number of cards in a pack.
uint8 public constant PACK_SIZE = 4;
/// @dev We increment this nonce when grabbing a random pack in _removeRandomPack().
uint256 internal randNonce;
/// @dev Function shared by all 3 ways of buying a pack (ETH, kitty burn, whitelist).
/// @param _sale The sale we are buying from.
function _buyPack(PackSale storage _sale) internal whenNotPaused {
require(msg.sender == tx.origin, "Only EOAs are allowed to buy from the pack sale.");
require(_sale.packs.length > 0, "The sale has no packs available for sale.");
uint32 pack = _removeRandomPack(_sale.packs);
uint256[] memory cards = _mintCards(pack);
_sale.packsSold++;
emit PackBought(msg.sender, cards);
}
/// @dev Iterates over a uint32 pack 8 bits at a time and turns each group of 8 bits into a token!
/// @param _pack 32 bit integer where each group of 8 bits represents a checklist ID.
/// @return An array of 4 token IDs, representing the cards we minted.
function _mintCards(uint32 _pack) internal returns (uint256[]) {
uint8 mask = 255;
uint256[] memory newCards = new uint256[](PACK_SIZE);
for (uint8 i = 1; i <= PACK_SIZE; i++) {
// Can't underflow because PACK_SIZE is 4.
uint8 shift = 32 - (i * 8);
uint8 checklistId = uint8((_pack >> shift) & mask);
uint256 cardId = mintingContract.mintPackSaleCard(checklistId, msg.sender);
newCards[i-1] = cardId;
}
return newCards;
}
/// @dev Given an array of packs (uint32s), removes one from a random index.
/// @param _packs The array of uint32s we will be mutating.
/// @return The random uint32 we removed.
function _removeRandomPack(uint32[] storage _packs) internal returns (uint32) {
randNonce++;
bytes memory packed = abi.encodePacked(now, msg.sender, randNonce);
uint256 randomIndex = uint256(keccak256(packed)) % _packs.length;
return _removePackAtIndex(randomIndex, _packs);
}
/// @dev Given an array of uint32s, remove the one at a given index and replace it with the last element of the array.
/// @param _index The index of the pack we want to remove from the array.
/// @param _packs The array of uint32s we will be mutating.
/// @return The uint32 we removed from position _index.
function _removePackAtIndex(uint256 _index, uint32[] storage _packs) internal returns (uint32) {
// Can't underflow because we do require(_sale.packs.length > 0) in _buyPack().
uint256 lastIndex = _packs.length - 1;
require(_index <= lastIndex);
uint32 pack = _packs[_index];
_packs[_index] = _packs[lastIndex];
_packs.length--;
return pack;
}
}
/// @title A contract that manages the whitelist we use for free pack giveaways.
/// @author The CryptoStrikers Team
contract StrikersWhitelist is StrikersPackSaleInternal {
/// @dev Emit this when the contract owner increases a user's whitelist allocation.
event WhitelistAllocationIncreased(address indexed user, uint16 amount, bool premium);
/// @dev Emit this whenever someone gets a pack using their whitelist allocation.
event WhitelistAllocationUsed(address indexed user, bool premium);
/// @dev We can only give away a maximum of 1000 Standard packs, and 500 Premium packs.
uint16[2] public whitelistLimits = [
1000, // Standard
500 // Premium
];
/// @dev Keep track of the allocation for each whitelist so we don't go over the limit.
uint16[2] public currentWhitelistCounts;
/// @dev Index 0 is the Standard whitelist, index 1 is the Premium whitelist. Maps addresses to free pack allocation.
mapping (address => uint8)[2] public whitelists;
/// @dev Allows the owner to allocate free packs (either Standard or Premium) to a given address.
/// @param _premium True for Premium whitelist, false for Standard whitelist.
/// @param _addr Address of the user who is getting the free packs.
/// @param _additionalPacks How many packs we are adding to this user's allocation.
function addToWhitelistAllocation(bool _premium, address _addr, uint8 _additionalPacks) public onlyOwner {
uint8 listIndex = _premium ? 1 : 0;
require(currentWhitelistCounts[listIndex] + _additionalPacks <= whitelistLimits[listIndex]);
currentWhitelistCounts[listIndex] += _additionalPacks;
whitelists[listIndex][_addr] += _additionalPacks;
emit WhitelistAllocationIncreased(_addr, _additionalPacks, _premium);
}
/// @dev A way to call addToWhitelistAllocation in bulk. Adds 1 pack to each address.
/// @param _premium True for Premium whitelist, false for Standard whitelist.
/// @param _addrs Addresses of the users who are getting the free packs.
function addAddressesToWhitelist(bool _premium, address[] _addrs) external onlyOwner {
for (uint256 i = 0; i < _addrs.length; i++) {
addToWhitelistAllocation(_premium, _addrs[i], 1);
}
}
/// @dev If msg.sender has whitelist allocation for a given pack type, decrement it and give them a free pack.
/// @param _premium True for the Premium sale, false for the Standard sale.
function claimWhitelistPack(bool _premium) external {
uint8 listIndex = _premium ? 1 : 0;
require(whitelists[listIndex][msg.sender] > 0, "You have no whitelist allocation.");
// Can't underflow because of require() check above.
whitelists[listIndex][msg.sender]--;
PackSale storage sale = _premium ? currentPremiumSale : standardSale;
_buyPack(sale);
emit WhitelistAllocationUsed(msg.sender, _premium);
}
}
/// @title The contract that manages our referral program -- invite your friends and get rewarded!
/// @author The CryptoStrikers Team
contract StrikersReferral is StrikersWhitelist {
/// @dev A cap for how many free referral packs we are giving away.
uint16 public constant MAX_FREE_REFERRAL_PACKS = 5000;
/// @dev The percentage of each sale that gets paid out to the referrer as commission.
uint256 public constant PERCENT_COMMISSION = 10;
/// @dev The 8 bonus cards that you get for your first 8 referrals, in order.
uint8[] public bonusCards = [
115, // Kanté
127, // Navas
122, // Hummels
130, // Alves
116, // Cavani
123, // Özil
121, // Thiago
131 // Zlatan
];
/// @dev Emit this event when a sale gets attributed, so the referrer can see a log of all his referrals.
event SaleAttributed(address indexed referrer, address buyer, uint256 amount);
/// @dev How much many of the 8 bonus cards this referrer has claimed.
mapping (address => uint8) public bonusCardsClaimed;
/// @dev Use this to track whether or not a user has bought at least one pack, to avoid people gaming our referral program.
mapping (address => uint16) public packsBought;
/// @dev Keep track of this to make sure we don't go over MAX_FREE_REFERRAL_PACKS.
uint16 public freeReferralPacksClaimed;
/// @dev Tracks whether or not a user has already claimed their free referral pack.
mapping (address => bool) public hasClaimedFreeReferralPack;
/// @dev How much referral income a given referrer has claimed.
mapping (address => uint256) public referralCommissionClaimed;
/// @dev How much referral income a given referrer has earned.
mapping (address => uint256) public referralCommissionEarned;
/// @dev Tracks how many sales have been attributed to a given referrer.
mapping (address => uint16) public referralSaleCount;
/// @dev A mapping to keep track of who referred a given user.
mapping (address => address) public referrers;
/// @dev How much ETH is owed to referrers, so we don't touch it when we withdraw our take from the contract.
uint256 public totalCommissionOwed;
/// @dev After a pack is bought with ETH, we call this to attribute the sale to the buyer's referrer.
/// @param _buyer The user who bought the pack.
/// @param _amount The price of the pack bought, in wei.
function _attributeSale(address _buyer, uint256 _amount) internal {
address referrer = referrers[_buyer];
// Can only attribute a sale to a valid referrer.
// Referral commissions only accrue if the referrer has bought a pack.
if (referrer == address(0) || packsBought[referrer] == 0) {
return;
}
referralSaleCount[referrer]++;
// The first 8 referral sales each unlock a bonus card.
// Any sales past the first 8 generate referral commission.
if (referralSaleCount[referrer] > bonusCards.length) {
uint256 commission = _amount * PERCENT_COMMISSION / 100;
totalCommissionOwed += commission;
referralCommissionEarned[referrer] += commission;
}
emit SaleAttributed(referrer, _buyer, _amount);
}
/// @dev A referrer calls this to claim the next of the 8 bonus cards he is owed.
function claimBonusCard() external {
uint16 attributedSales = referralSaleCount[msg.sender];
uint8 cardsClaimed = bonusCardsClaimed[msg.sender];
require(attributedSales > cardsClaimed, "You have no unclaimed bonus cards.");
require(cardsClaimed < bonusCards.length, "You have claimed all the bonus cards.");
bonusCardsClaimed[msg.sender]++;
uint8 bonusCardChecklistId = bonusCards[cardsClaimed];
mintingContract.mintPackSaleCard(bonusCardChecklistId, msg.sender);
}
/// @dev A user who was referred to CryptoStrikers can call this once to claim their free pack (must have bought a pack first).
function claimFreeReferralPack() external {
require(isOwedFreeReferralPack(msg.sender), "You are not eligible for a free referral pack.");
require(freeReferralPacksClaimed < MAX_FREE_REFERRAL_PACKS, "We've already given away all the free referral packs...");
freeReferralPacksClaimed++;
hasClaimedFreeReferralPack[msg.sender] = true;
_buyPack(standardSale);
}
/// @dev Checks whether or not a given user is eligible for a free referral pack.
/// @param _addr The address of the user we are inquiring about.
/// @return True if user can call claimFreeReferralPack(), false otherwise.
function isOwedFreeReferralPack(address _addr) public view returns (bool) {
// _addr will only have a referrer if they've already bought a pack (see buyFirstPackFromReferral())
address referrer = referrers[_addr];
// To prevent abuse, require that the referrer has bought at least one pack.
// Guaranteed to evaluate to false if referrer is address(0), so don't even check for that.
bool referrerHasBoughtPack = packsBought[referrer] > 0;
// Lastly, check to make sure _addr hasn't already claimed a free pack.
return referrerHasBoughtPack && !hasClaimedFreeReferralPack[_addr];
}
/// @dev Allows the contract owner to manually set the referrer for a given user, in case this wasn't properly attributed.
/// @param _for The user we want to set the referrer for.
/// @param _referrer The user who will now get credit for _for's future purchases.
function setReferrer(address _for, address _referrer) external onlyOwner {
referrers[_for] = _referrer;
}
/// @dev Allows a user to withdraw the referral commission they are owed.
function withdrawCommission() external {
uint256 commission = referralCommissionEarned[msg.sender] - referralCommissionClaimed[msg.sender];
require(commission > 0, "You are not owed any referral commission.");
totalCommissionOwed -= commission;
referralCommissionClaimed[msg.sender] += commission;
msg.sender.transfer(commission);
}
}
/// @title The main sale contract, allowing users to purchase packs of CryptoStrikers cards.
/// @author The CryptoStrikers Team
contract StrikersPackSale is StrikersReferral {
/// @dev The max number of kitties we are allowed to burn.
uint16 public constant KITTY_BURN_LIMIT = 1000;
/// @dev Emit this whenever someone sacrifices a cat for a free pack of cards.
event KittyBurned(address user, uint256 kittyId);
/// @dev Users are only allowed to burn 1 cat each, so keep track of that here.
mapping (address => bool) public hasBurnedKitty;
/// @dev A reference to the CryptoKitties contract so we can transfer cats
ERC721Basic public kittiesContract;
/// @dev How many kitties we have burned so far. Think of the cats, make sure we don't go over KITTY_BURN_LIMIT!
uint16 public totalKittiesBurned;
/// @dev Keeps track of our sale volume, in wei.
uint256 public totalWeiRaised;
/// @dev Constructor. Can't change minting and kitties contracts once they've been initialized.
constructor(
uint256 _standardPackPrice,
address _kittiesContractAddress,
address _mintingContractAddress
)
StrikersPackFactory(_standardPackPrice)
public
{
kittiesContract = ERC721Basic(_kittiesContractAddress);
mintingContract = StrikersMinting(_mintingContractAddress);
}
/// @dev For a user who was referred, use this function to buy your first back so we can attribute the referral.
/// @param _referrer The user who invited msg.sender to CryptoStrikers.
/// @param _premium True if we're buying from Premium sale, false if we're buying from Standard sale.
function buyFirstPackFromReferral(address _referrer, bool _premium) external payable {
require(packsBought[msg.sender] == 0, "Only assign a referrer on a user's first purchase.");
referrers[msg.sender] = _referrer;
buyPackWithETH(_premium);
}
/// @dev Allows a user to buy a pack of cards with enough ETH to cover the packPrice.
/// @param _premium True if we're buying from Premium sale, false if we're buying from Standard sale.
function buyPackWithETH(bool _premium) public payable {
PackSale storage sale = _premium ? currentPremiumSale : standardSale;
uint256 packPrice = sale.packPrice;
require(msg.value >= packPrice, "Insufficient ETH sent to buy this pack.");
_buyPack(sale);
packsBought[msg.sender]++;
totalWeiRaised += packPrice;
// Refund excess funds
msg.sender.transfer(msg.value - packPrice);
_attributeSale(msg.sender, packPrice);
}
/// @notice Magically transform a CryptoKitty into a free pack of cards!
/// @param _kittyId The cat we are giving up.
/// @dev Note that the user must first give this contract approval by
/// calling approve(address(this), _kittyId) on the CK contract.
/// Otherwise, buyPackWithKitty() throws on transferFrom().
function buyPackWithKitty(uint256 _kittyId) external {
require(totalKittiesBurned < KITTY_BURN_LIMIT, "Stop! Think of the cats!");
require(!hasBurnedKitty[msg.sender], "You've already burned a kitty.");
totalKittiesBurned++;
hasBurnedKitty[msg.sender] = true;
// Will throw/revert if this contract hasn't been given approval first.
// Also, with no way of retrieving kitties from this contract,
// transferring to "this" burns the cat! (desired behaviour)
kittiesContract.transferFrom(msg.sender, this, _kittyId);
_buyPack(standardSale);
emit KittyBurned(msg.sender, _kittyId);
}
/// @dev Allows the contract owner to withdraw the ETH raised from selling packs.
function withdrawBalance() external onlyOwner {
uint256 totalBalance = address(this).balance;
require(totalBalance > totalCommissionOwed, "There is no ETH for the owner to claim.");
owner.transfer(totalBalance - totalCommissionOwed);
}
} | Emit this when the contract owner increases a user's whitelist allocation. Emit this whenever someone gets a pack using their whitelist allocation. We can only give away a maximum of 1000 Standard packs, and 500 Premium packs. Keep track of the allocation for each whitelist so we don't go over the limit. Index 0 is the Standard whitelist, index 1 is the Premium whitelist. Maps addresses to free pack allocation. Allows the owner to allocate free packs (either Standard or Premium) to a given address. _premium True for Premium whitelist, false for Standard whitelist. _addr Address of the user who is getting the free packs. _additionalPacks How many packs we are adding to this user's allocation. | function addToWhitelistAllocation(bool _premium, address _addr, uint8 _additionalPacks) public onlyOwner {
uint8 listIndex = _premium ? 1 : 0;
require(currentWhitelistCounts[listIndex] + _additionalPacks <= whitelistLimits[listIndex]);
currentWhitelistCounts[listIndex] += _additionalPacks;
whitelists[listIndex][_addr] += _additionalPacks;
emit WhitelistAllocationIncreased(_addr, _additionalPacks, _premium);
}
| 10,346,107 |
pragma solidity ^0.4.16;
import "utils/Controller.sol";
contract ControllerExtended is Controller {
function latestSenderOf(uint256 _proposalID) internal constant returns (address) {
return momentSenderOf(_proposalID, numMomentsOf(_proposalID) - 1);
}
function executionTimeOf(uint256 _proposalID) internal constant returns (uint256) {
if (hasExecuted(_proposalID))
return momentTimeOf(_proposalID, numMomentsOf(_proposalID) - 1);
}
function executionBlockOf(uint256 _proposalID) internal constant returns (uint256) {
if (hasExecuted(_proposalID))
return momentBlockOf(_proposalID, numMomentsOf(_proposalID) - 1);
}
function destinationOf(uint256 _proposalID, uint256 _startPosition) internal constant returns (address) {
bytes memory data = proposals[_proposalID].data;
assembly {
// make sure we don’t overstep array boundaries because in assembly
// there’s no built-in boundary checks
// We’re basically comparing _startPosition to the length of the array
// (stored in the first 32 bytes) and subtracting the length of an address
switch lt(_startPosition, sub(mload(data), 32))
case 0 { stop }
// Let’s just load the 20 bytes following the _startPosition byte
// and return them. Simple as that!
//
//NOTE: we have to add an additional 32 bytes to account for the
// 32 bytes specifying the length of the array at the beggining.
let start := add(data, add(_startPosition, 0x20))
return(start, 0x14)
}
}
function valueOf(uint256 _proposalID, uint256 _startPosition) internal constant returns (uint256) {
bytes memory data = proposals[_proposalID].data;
assembly {
// make sure we don’t overstep array boundaries because in assembly
// there’s no built-in boundary checks
// We’re basically comparing _startPosition to the length of the array
// (stored in the first 32 bytes) and subtracting the length of an uint
switch lt(_startPosition, sub(mload(data), 32))
case 0 { stop }
// Let’s just load the 32 bytes following the _startPosition byte
// and return them. Simple as that!
//
//NOTE: we have to add an additional 32 bytes to account for the
// 32 bytes specifying the length of the array at the beggining.
let start := add(data, add(_startPosition, 0x20))
return(start, 0x20)
}
}
function lengthOf(uint256 _proposalID, uint256 _startPosition) internal constant returns (uint256) {
bytes memory data = proposals[_proposalID].data;
assembly {
// make sure we don’t overstep array boundaries because in assembly
// there’s no built-in boundary checks
// We’re basically comparing _startPosition to the length of the array
// (stored in the first 32 bytes) and subtracting the length of an uint
switch lt(_startPosition, sub(mload(data), 32))
case 0 { stop }
// Let’s just load the 32 bytes following the _startPosition byte
// and return them. Simple as that!
//
//NOTE: we have to add an additional 32 bytes to account for the
// 32 bytes specifying the length of the array at the beggining.
let start := add(data, add(_startPosition, 0x20))
return(start, 0x20)
}
}
function dataOf(uint256 _proposalID, uint256 _startPosition) internal constant returns (bytes) {
bytes memory data = proposals[_proposalID].data;
assembly {
// make sure we don’t overstep array boundaries because in assembly
// there’s no built-in boundary checks
// We’re basically comparing _startPosition to the length of the array
// (stored in the first 32 bytes) and subtracting the length of an uint
switch lt(_startPosition, sub(mload(data), 32))
case 0 { stop }
// We have to add an additional 32 bytes to account for the
// 32 bytes specifying the length of the array at the beggining.
let start := add(_startPosition, 0x20)
// Now we actually load the size of the inner tightly packed bytes
// array of our calldata structure
let bytesLength := mload(add(data, start))
// add 32 bytes to start because we won’t need the length for what
// we’re doing next :D
start := add(start, 0x20)
// Let’s just load the `bytesLength` bytes following the `start` byte
// and return them. Simple as that!
return(start, bytesLength)
}
}
function signatureOf(uint256 _proposalID, uint256 _startPosition) internal constant returns (bytes4) {
bytes memory data = proposals[_proposalID].data;
assembly {
// make sure we don’t overstep array boundaries because in assembly
// there’s no built-in boundary checks
// We’re basically comparing _startPosition to the length of the array
// (stored in the first 32 bytes) and subtracting the length of an uint
switch lt(_startPosition, sub(mload(data), 32))
case 0 { stop }
// We have to add an additional 32 bytes to account for the
// 32 bytes specifying the length of the array at the beggining.
let start := add(_startPosition, 0x20)
// Now we actually load the size of the inner tightly packed bytes
// array of our calldata structure
let bytesLength := mload(add(data, start))
// make sure we don’t overstep array boundaries again, this time for
// the inner dynamic array. We’re checking if it is at least 4 bytes
// (the size of a function ID) long
switch lt(mload(add(data, start)), 4)
case 0 { stop }
// And finally we’re gonna return the first (existing!) 4 bytes of
// the inner dynamic array
return(start, 4)
}
}
}
| make sure we don’t overstep array boundaries because in assembly there’s no built-in boundary checks We’re basically comparing _startPosition to the length of the array (stored in the first 32 bytes) and subtracting the length of an uint Let’s just load the 32 bytes following the _startPosition byte and return them. Simple as that!NOTE: we have to add an additional 32 bytes to account for the 32 bytes specifying the length of the array at the beggining. | function lengthOf(uint256 _proposalID, uint256 _startPosition) internal constant returns (uint256) {
bytes memory data = proposals[_proposalID].data;
assembly {
switch lt(_startPosition, sub(mload(data), 32))
let start := add(data, add(_startPosition, 0x20))
return(start, 0x20)
}
}
| 14,115,375 |
pragma solidity ^0.4.24;
import 'openzeppelin-solidity/contracts/token/ERC721/ERC721.sol';
import './Club.sol';
///@author Sanjay Sanathanan
///@title Contract that maintains the structure for each Player
contract Players is Club{
uint public playerID;
enum State {TransferListed,TransferAccept, NotListed}
struct Player{
uint playerID;
string name;
uint value;
uint wage;
uint year;
address club;
State state;
}
mapping(uint => Player) public player;
event PlayerAdded(uint indexed _pid);
///To get the player name
///@param _id Player id
///@return the name of the player
function getPlayerName(uint _id) public view
returns(string memory){
return player[_id].name;
}
///To get the player value
///@param _id Player id
///@return the value(cost) of the player
function getPlayerValue(uint _id) public view
returns (uint){
return player[_id].value;
}
///To get the player's weekly wage
///@param _id Player id
///@return the wage of the player
function getPlayerWeeklyWage(uint _id) public view
returns (uint){
return player[_id].wage;
}
///To get the player's current year left in contract
///@param _id Player id
///@return the current year's left for the player's contract
function getPlayerContractYear(uint _id) public view
returns (uint){
return player[_id].year;
}
///To get the player's current club
///@param _id Player id
///@return the current club of the player
function getPlayerClub(uint _id) public view
returns (string){
return clubName[player[_id].club];
}
///To get the player's current club address
///@param _id Player id
///@return the current club address of the player
function getPlayerClubaddress(uint _id) public view
returns (address){
return player[_id].club;
}
// Used for testing purposes
function fetchPlayer(uint _pid) public view returns (string name, address club, string clubname,uint value, uint wage,uint length, uint state) {
name = player[_pid].name;
club = player[_pid].club;
clubname = clubName[player[_pid].club];
value = player[_pid].value;
wage = player[_pid].wage;
length = player[_pid].year;
state = uint(player[_pid].state);
return (name,club,clubname,value,wage,length,state);
}
} | To get the player's weekly wage _id Player idreturn the wage of the player | function getPlayerWeeklyWage(uint _id) public view
returns (uint){
return player[_id].wage;
}
| 1,022,023 |
/**
*Submitted for verification at Etherscan.io on 2022-03-16
*/
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/**
* @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);
}
}
}
}
/**
* @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);
}
}
/**
* @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;
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
/**
* @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);
}
/**
* @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);
}
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_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);
}
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @dev 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 overridden 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 || isApprovedForAll(owner, spender) || getApproved(tokenId) == 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 {}
}
/**
* @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();
}
}
contract CoolApePlanet is Ownable, ERC721Enumerable {
// using SafeMath for uint256;
using Strings for uint256;
using Counters for Counters.Counter;
uint public _maxSupply = 9999;
// uint256 private _totalNFT; // total NFTs
uint256 private _mintedNFT; // minted NFTs
uint256 public _maxMint = 20;
string public baseURI;
string public _baseExtension = ""; //.json
string private _notRevealedUri;
bool private _isPaused = true; // is minting paused?
bool private _burnEnabled = false;
bool public _isRevealed = true; // NFTs are revealed?
bool public _publicSale = true; // is public sale?
bool public _privateSale = true; // is whitelist sale?
bool public _giveawaySale = false;
// mapping (address => uint256) public _totalMinted; // total NFTs minted
mapping (address => uint256) public _whitelistMinted; // NFTs minted dusring whitelist sale
mapping (address => bool) public _giveawayMinted;
uint8 public _whitelistGiveaway = 0; // Giveaway Number
mapping (address => bool) public _whitelisted; // Whitelisted Addresses
mapping (address => bool) public _giveaway; // If user already claimed giveaway
uint256 public _totalGiveaway = 0;
uint256 public _price = 100000000000000000; // 0.1 ETH
Counters.Counter private _tokenIds;
constructor (string memory _name, string memory _symbol) ERC721(_name, _symbol) {}
function MintedNFT () public view returns(uint256) {
return _mintedNFT;
}
// View Base URI
function _baseURI () internal virtual override view returns(string memory) {
return baseURI;
}
function IsPaused () public view returns(bool) {
return _isPaused;
}
function BurnEnabled () public view returns(bool) {
return _burnEnabled;
}
// Change Base URI
function setBaseURI (string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
// Change Not Revealed URI
function setNotRevealedURI (string memory _newBaseURI) public onlyOwner {
_notRevealedUri = _newBaseURI;
}
// Set Base Extension
function setBaseExtension (string memory _newBaseExt) public onlyOwner {
_baseExtension = _newBaseExt;
}
// Change Price for Pre-Sale
function setPrice (uint256 _newPrice) public onlyOwner {
_price = _newPrice;
}
function changeIsPaused () public onlyOwner {
_isPaused = !_isPaused;
}
function changeIsRevealed () public onlyOwner {
_isRevealed = !_isRevealed;
}
function changePublicSale () public onlyOwner {
_publicSale = !_publicSale;
}
function changePrivateSale () public onlyOwner {
_privateSale = !_privateSale;
}
function changeGiveawaySale () public onlyOwner {
_giveawaySale = !_giveawaySale;
}
function changeBurnEnabled () public onlyOwner {
_burnEnabled = !_burnEnabled;
}
// Add a single address to whitelist
function setWhitelisted (address account) public onlyOwner {
_whitelisted[account] = true;
}
function setGiveaway (address account) public onlyOwner {
_giveaway[account] = true;
}
function setMultiWhitelisted (address[] memory accounts) public onlyOwner {
for (uint i = 0; i < accounts.length; i++) {
_whitelisted[accounts[i]] = true;
}
}
// Remove a single address from whitelist
function removeWhitelisted (address account) public onlyOwner {
_whitelisted[account] = false;
}
function removeGiveaway (address account) public onlyOwner {
_giveaway[account] = false;
}
function removeMultiWhitelisted (address[] memory accounts) public onlyOwner {
for (uint i = 0; i < accounts.length; i++) {
_whitelisted[accounts[i]] = false;
}
}
// Change Max Mint allowed
function setMaxMint (uint256 newMaxMint) public onlyOwner {
_maxMint = newMaxMint;
}
function whitelistMint (uint256 _amount) external payable {
require (_privateSale, "Cool Apes Planet: Whitelist Sale is not active");
require (!_isPaused, "Cool Apes Planet: Minting is paused");
require (_amount <= _maxMint && _amount > 0, "Cool Apes Planet: Cannot mint more than max allowed");
require (verify(msg.sender), "Cool Apes Planet: You are not whitelisted");
require (_whitelistMinted[msg.sender] + _amount <= 20, "Cool Apes Planet: Cannot mint more than 20 NFTs");
require (_price * _amount <= msg.value, "Cool Apes Planet: Not enough ETH sent");
// Giveaway extra NFT to first 200 minters
if (_whitelistGiveaway < uint8(200)) {
_amount = _amount + 1;
_whitelistGiveaway = _whitelistGiveaway + 1;
}
uint256 _newTokenId;
for (uint256 i = 0; i < _amount; i++) {
_tokenIds.increment();
_newTokenId = _tokenIds.current();
_safeMint(msg.sender, _newTokenId);
_whitelistMinted[msg.sender] = _whitelistMinted[msg.sender] + 1;
// totalNFT = totalNFT + 1;
_mintedNFT = _mintedNFT + 1;
}
}
function giveawayMint () external {
require (_giveawaySale, "Cool Apes Planet: Giveaways are not active");
require (_giveaway[msg.sender], "Cool Apes Planet: You are not eligible for giveaway");
require (!_giveawayMinted[msg.sender], "Cool Apes Planet: You have already claimed your giveaway");
require (_mintedNFT <= _maxSupply, "Cool Apes Planet: Cannot Mint more than max supply");
require (!_isPaused, "Cool Apes Planet: Minting is paused");
uint256 _newTokenId;
_tokenIds.increment();
_newTokenId = _tokenIds.current();
_safeMint(msg.sender, _newTokenId);
_giveawayMinted[msg.sender] = true;
// totalNFT = totalNFT + 1;
_mintedNFT = _mintedNFT + 1;
}
function publicMint (uint256 _amount) external payable {
require (_publicSale, "Cool Apes Planet: Public Sale is not active");
require (!_isPaused, "Cool Apes Planet: Minting is paused");
// require (_amount <= _maxMint, "Cool Apes Planet: Cannot mint more than max allowed");
require (_amount > 0, "Cool Apes Planet: Cannot mint 0 NFTs");
require (_mintedNFT <= _maxSupply, "Cool Apes Planet: Cannot Mint more than max supply");
require (_price * _amount <= msg.value, "Cool Apes Planet: Not enough ETH sent");
// Giveaway extra NFT to first 200 minters
if (_whitelistGiveaway < uint8(200)) {
_amount = _amount + 1;
_whitelistGiveaway = _whitelistGiveaway + 1;
}
uint256 _newTokenId;
for (uint256 i = 0; i < _amount; i++) {
_tokenIds.increment();
_newTokenId = _tokenIds.current();
_safeMint(msg.sender, _newTokenId);
// _whitelistMinted[msg.sender] = _whitelistMinted[msg.sender] + 1;
// totalNFT = totalNFT + 1;
_mintedNFT = _mintedNFT + 1;
}
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
if (_isRevealed == false) {
return _notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0 ?
string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
_baseExtension
)
)
: "";
}
// View whitelisted address
function verify (address account) public view returns(bool) {
return _whitelisted[account];
}
function withdrawToken() public onlyOwner {
uint balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
} | Remove a single address from whitelist | function removeWhitelisted (address account) public onlyOwner {
_whitelisted[account] = false;
}
| 2,092,251 |