file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
list | attention_mask
list | labels
list |
---|---|---|---|---|---|---|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library Denominations {
address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address public constant BTC = 0xbBbBBBBbbBBBbbbBbbBbbbbBBbBbbbbBbBbbBBbB;
// Fiat currencies follow https://en.wikipedia.org/wiki/ISO_4217
address public constant USD = address(840);
address public constant GBP = address(826);
address public constant EUR = address(978);
address public constant JPY = address(392);
address public constant KRW = address(410);
address public constant CNY = address(156);
address public constant AUD = address(36);
address public constant CAD = address(124);
address public constant CHF = address(756);
address public constant ARS = address(32);
address public constant PHP = address(608);
address public constant NZD = address(554);
address public constant SGD = address(702);
address public constant NGN = address(566);
address public constant ZAR = address(710);
address public constant RUB = address(643);
address public constant INR = address(356);
address public constant BRL = address(986);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface {}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "./AggregatorV2V3Interface.sol";
interface FeedRegistryInterface {
struct Phase {
uint16 phaseId;
uint80 startingAggregatorRoundId;
uint80 endingAggregatorRoundId;
}
event FeedProposed(
address indexed asset,
address indexed denomination,
address indexed proposedAggregator,
address currentAggregator,
address sender
);
event FeedConfirmed(
address indexed asset,
address indexed denomination,
address indexed latestAggregator,
address previousAggregator,
uint16 nextPhaseId,
address sender
);
// V3 AggregatorV3Interface
function decimals(address base, address quote) external view returns (uint8);
function description(address base, address quote) external view returns (string memory);
function version(address base, address quote) external view returns (uint256);
function latestRoundData(address base, address quote)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function getRoundData(
address base,
address quote,
uint80 _roundId
)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
// V2 AggregatorInterface
function latestAnswer(address base, address quote) external view returns (int256 answer);
function latestTimestamp(address base, address quote) external view returns (uint256 timestamp);
function latestRound(address base, address quote) external view returns (uint256 roundId);
function getAnswer(
address base,
address quote,
uint256 roundId
) external view returns (int256 answer);
function getTimestamp(
address base,
address quote,
uint256 roundId
) external view returns (uint256 timestamp);
// Registry getters
function getFeed(address base, address quote) external view returns (AggregatorV2V3Interface aggregator);
function getPhaseFeed(
address base,
address quote,
uint16 phaseId
) external view returns (AggregatorV2V3Interface aggregator);
function isFeedEnabled(address aggregator) external view returns (bool);
function getPhase(
address base,
address quote,
uint16 phaseId
) external view returns (Phase memory phase);
// Round helpers
function getRoundFeed(
address base,
address quote,
uint80 roundId
) external view returns (AggregatorV2V3Interface aggregator);
function getPhaseRange(
address base,
address quote,
uint16 phaseId
) external view returns (uint80 startingRoundId, uint80 endingRoundId);
function getPreviousRoundId(
address base,
address quote,
uint80 roundId
) external view returns (uint80 previousRoundId);
function getNextRoundId(
address base,
address quote,
uint80 roundId
) external view returns (uint80 nextRoundId);
// Feed management
function proposeFeed(
address base,
address quote,
address aggregator
) external;
function confirmFeed(
address base,
address quote,
address aggregator
) external;
// Proposed aggregator
function getProposedFeed(address base, address quote)
external
view
returns (AggregatorV2V3Interface proposedAggregator);
function proposedGetRoundData(
address base,
address quote,
uint80 roundId
)
external
view
returns (
uint80 id,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function proposedLatestRoundData(address base, address quote)
external
view
returns (
uint80 id,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
// Phases
function getCurrentPhaseId(address base, address quote) external view returns (uint16 currentPhaseId);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
// OpenZeppelin
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
// Chainlink
import "@chainlink/contracts/src/v0.8/interfaces/FeedRegistryInterface.sol";
import "@chainlink/contracts/src/v0.8/Denominations.sol";
contract DustSweeper is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
uint256 private takerDiscountPercent;
uint256 private protocolFeePercent;
address private protocolWallet;
struct TokenData {
address tokenAddress;
uint256 tokenPrice;
}
mapping(address => uint8) private tokenDecimals;
// ChainLink
address private chainLinkRegistry;
address private quoteETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
constructor(
address _chainLinkRegistry,
address _protocolWallet,
uint256 _takerDiscountPercent,
uint256 _protocolFeePercent
) {
chainLinkRegistry = _chainLinkRegistry;
protocolWallet = _protocolWallet;
takerDiscountPercent = _takerDiscountPercent;
protocolFeePercent = _protocolFeePercent;
}
function sweepDust(
address[] calldata makers,
address[] calldata tokenAddresses
) external payable nonReentrant {
// Make sure order data is valid
require(makers.length > 0 && makers.length == tokenAddresses.length, "Passed order data in invalid format");
// Track how much ETH was sent so we can return any overage
uint256 ethSent = msg.value;
uint256 totalNativeAmount = 0;
TokenData memory lastToken;
for (uint256 i = 0; i < makers.length; i++) {
// Fetch/cache tokenDecimals
if (tokenDecimals[tokenAddresses[i]] == 0) {
bytes memory decData = Address.functionStaticCall(tokenAddresses[i], abi.encodeWithSignature("decimals()"));
tokenDecimals[tokenAddresses[i]] = abi.decode(decData, (uint8));
}
require(tokenDecimals[tokenAddresses[i]] > 0, "Failed to fetch token decimals");
// Fetch/cache tokenPrice
if (i == 0 || lastToken.tokenPrice == 0 || lastToken.tokenAddress != tokenAddresses[i]) {
// Need to fetch tokenPrice
lastToken = TokenData(tokenAddresses[i], uint256(getPrice(tokenAddresses[i], quoteETH)));
}
require(lastToken.tokenPrice > 0, "Failed to fetch token price!");
// Amount of Tokens to transfer
uint256 allowance = IERC20(tokenAddresses[i]).allowance(makers[i], address(this));
require(allowance > 0, "Allowance for specified token is 0");
// Equivalent amount of Native Tokens
uint256 nativeAmt = allowance * lastToken.tokenPrice / 10**tokenDecimals[tokenAddresses[i]];
totalNativeAmount += nativeAmt;
// Amount of Native Tokens to transfer
uint256 distribution = nativeAmt * (10**4 - takerDiscountPercent) / 10**4;
// Subtract distribution amount from ethSent amount
ethSent -= distribution;
// Taker sends Native Token to Maker
Address.sendValue(payable(makers[i]), distribution);
// DustSweeper sends Maker's tokens to Taker
IERC20(tokenAddresses[i]).safeTransferFrom(makers[i], msg.sender, allowance);
}
// Taker pays protocolFee % for the total amount to avoid multiple transfers
uint256 protocolNative = totalNativeAmount * protocolFeePercent / 10**4;
// Subtract protocolFee from ethSent
ethSent -= protocolNative;
// Send to protocol wallet
Address.sendValue(payable(protocolWallet), protocolNative);
// Pay any overage back to msg.sender as long as overage > gas cost
if (ethSent > 10000) {
Address.sendValue(payable(msg.sender), ethSent);
}
}
/**
* Returns the latest price from Chainlink
*/
function getPrice(address base, address quote) public view returns(int256) {
(,int256 price,,,) = FeedRegistryInterface(chainLinkRegistry).latestRoundData(base, quote);
return price;
}
// onlyOwner protected Setters/Getters
function getTakerDiscountPercent() view external returns(uint256) {
return takerDiscountPercent;
}
function setTakerDiscountPercent(uint256 _takerDiscountPercent) external onlyOwner {
if (_takerDiscountPercent <= 5000) { // 50%
takerDiscountPercent = _takerDiscountPercent;
}
}
function getProtocolFeePercent() view external returns(uint256) {
return protocolFeePercent;
}
function setProtocolFeePercent(uint256 _protocolFeePercent) external onlyOwner {
if (_protocolFeePercent <= 1000) { // 10%
protocolFeePercent = _protocolFeePercent;
}
}
function getChainLinkRegistry() view external returns(address) {
return chainLinkRegistry;
}
function setChainLinkRegistry(address _chainLinkRegistry) external onlyOwner {
chainLinkRegistry = _chainLinkRegistry;
}
function getProtocolWallet() view external returns(address) {
return protocolWallet;
}
function setProtocolWallet(address _protocolWallet) external onlyOwner {
protocolWallet = _protocolWallet;
}
// Payment methods
receive() external payable {}
fallback() external payable {}
function removeBalance(address tokenAddress) external onlyOwner {
if (tokenAddress == address(0)) {
Address.sendValue(payable(msg.sender), address(this).balance);
} else {
uint256 tokenBalance = IERC20(tokenAddress).balanceOf(address(this));
if (tokenBalance > 0) {
IERC20(tokenAddress).safeTransfer(msg.sender, tokenBalance);
}
}
}
} | DustSweeper sends Maker's tokens to Taker | IERC20(tokenAddresses[i]).safeTransferFrom(makers[i], msg.sender, allowance);
| 5,764,134 | [
1,
40,
641,
6050,
9868,
9573,
490,
6388,
1807,
2430,
358,
399,
6388,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1377,
467,
654,
39,
3462,
12,
2316,
7148,
63,
77,
65,
2934,
4626,
5912,
1265,
12,
81,
581,
414,
63,
77,
6487,
1234,
18,
15330,
16,
1699,
1359,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "./interfaces/LongShortPairFinancialProductLibrary.sol";
// import "./AddressBook.sol";
import "./implementation/FixedPoint.sol";
import "./interfaces/ExpandedIERC721.sol";
import "./implementation/Constants.sol";
import "./interfaces/AddressBookInterface.sol";
// import "../../common/implementation/Testable.sol";
// import "../../common/implementation/Lockable.sol";
// import "../../oracle/interfaces/OracleInterface.sol";
// import "../../common/interfaces/AddressWhitelistInterface.sol";
// import "../../oracle/interfaces/OptimisticOracleInterface.sol";
// import "../../oracle/interfaces/IdentifierWhitelistInterface.sol";
/**
* @title Long Short Pair.
* @notice Uses a combination of long and short tokens to tokenize the bounded price exposure to a given identifier.
*/
contract LongShortPair is Initializable{
using FixedPoint for FixedPoint.Unsigned;
/*************************************
* LONG SHORT PAIR DATA STRUCTURES *
*************************************/
// // Define the contract's constructor parameters as a struct to enable more variables to be specified.
// struct ConstructorParams {
// string underlyingNft; // Name of the long short pair contract.
// uint64 expirationTimestamp; // Unix timestamp of when the contract will expire.
// uint256 collateralPerPair; // How many units of collateral are required to mint one pair of synthetic tokens.
// address longTokenAddress; // Token used as long in the LSP. Mint and burn rights needed by this contract.
// address shortTokenAddress; // Token used as short in the LSP. Mint and burn rights needed by this contract.
// address financialProductLibraryAddress; // Contract providing settlement payout logic.
// address addressBook;
// // bytes32 priceIdentifier; // Price identifier, registered in the DVM for the long short pair.
// // IERC20 collateralToken; // Collateral token used to back LSP synthetics. ETH for now
// // bytes customAncillaryData; // Custom ancillary data to be passed along with the price request to the OO.
// // uint256 prepaidProposerReward; // Preloaded reward to incentivize settlement price proposals.
// // uint256 optimisticOracleLivenessTime; // OO liveness time for price requests.
// // uint256 optimisticOracleProposerBond; // OO proposer bond for price requests.
// // address timerAddress; // Timer used to synchronize contract time in testing. Set to 0x000... in production.
// }
enum ContractState { Open, ExpiredPriceRequested, ExpiredPriceReceived }
// @dev note contractState and expirationTimestamp are declared in this order so they use the same storage slot.
ContractState public contractState;
struct LongShortTokenId {
uint256 longTokenId;
uint256 shortTokenId;
}
mapping(address => mapping(bytes32 => LongShortTokenId)) public userHoldings;
uint64 public expirationTimestamp;
string public underlyingNft;
// Mapping between tokenId and respective numbers of options it is representing
mapping(uint256 => uint256) tokenIdToTokens;
// Amount of collateral a pair of tokens is always redeemable for.
uint256 public collateralPerPair;
// Price returned from the Optimistic oracle at settlement time.
uint256 public expiryPrice;
// Number between 0 and 1e18 to allocate collateral between long & short tokens at redemption. 0 entitles each short
// to collateralPerPair and long worth 0. 1e18 makes each long worth collateralPerPair and short 0.
uint256 public expiryPercentLong;
bytes32 public priceIdentifier;
// IERC20 public collateralToken;
ExpandedIERC721 public longToken;
ExpandedIERC721 public shortToken;
address public longTokenAddress;
address public shortTokenAddress;
bytes32 lspHash;
AddressBookInterface public addressBook;
LongShortPairFinancialProductLibrary public financialProductLibrary;
// Optimistic oracle customization parameters.
bytes public customAncillaryData;
uint256 public prepaidProposerReward;
uint256 public optimisticOracleLivenessTime;
uint256 public optimisticOracleProposerBond;
uint256 public SETTLEMENT_PRICE = 20 * 1e18;
mapping (address => mapping(uint256 => uint256)) nftToTokenIdToAmount;
/****************************************
* EVENTS *
****************************************/
event TokensCreated(address indexed sponsor, uint256 indexed collateralUsed, uint256 indexed tokensMinted);
event TokensRedeemed(address sponsor, uint256 collateralReturned, uint256 longTokenId, uint256 indexed shortTokenId);
event ContractExpired(address indexed caller);
event PositionSettled(address indexed sponsor, uint256 collateralReturned, uint256 longTokens, uint256 shortTokens);
/****************************************
* MODIFIERS *
****************************************/
modifier preExpiration() {
require(_getCurrentTime() < expirationTimestamp, "Only callable pre-expiry");
_;
}
modifier postExpiration() {
require(_getCurrentTime() >= expirationTimestamp, "Only callable post-expiry");
_;
}
modifier onlyOpenState() {
require(contractState == ContractState.Open, "Contract state is not Open");
_;
}
function initialize(
string memory _underlyingNft,
uint64 _expirationTimestamp,
uint256 _strikePrice,
uint256 _collateralPerPair,
address _longTokenAddress,
address _shortTokenAddress,
address _addressBook
) external initializer {
addressBook = AddressBookInterface(_addressBook);
require(bytes(_underlyingNft).length > 0, "Pair name cant be empty");
require(_expirationTimestamp > _getCurrentTime(), "Expiration timestamp in past");
require(_collateralPerPair > 0, "Collateral per pair cannot be 0");
underlyingNft = _underlyingNft;
expirationTimestamp = _expirationTimestamp;
collateralPerPair = _collateralPerPair;
longToken = ExpandedIERC721(_longTokenAddress);
shortToken = ExpandedIERC721(_shortTokenAddress);
longTokenAddress = _longTokenAddress;
shortTokenAddress = _shortTokenAddress;
lspHash = keccak256(abi.encodePacked(_underlyingNft, _expirationTimestamp, _collateralPerPair, _longTokenAddress, _shortTokenAddress ));
address lspFinancialProductLibrary = AddressBookInterface(addressBook).getCoveredCallLongShortPairFinancialProductImplementation();
LongShortPairFinancialProductLibrary(lspFinancialProductLibrary)
.setLongShortPairParameters(lspHash, _strikePrice);
financialProductLibrary = LongShortPairFinancialProductLibrary(lspFinancialProductLibrary);
}
// constructor(ConstructorParams memory params){
// // require(_getIdentifierWhitelist().isIdentifierSupported(priceIdentifier), "Identifier not registered");
// // require(address(_getOptimisticOracle()) != address(0), "Invalid finder");
// // require(_getCollateralWhitelist().isOnWhitelist(address(collateralToken)), "Collateral not whitelisted");
// // require(optimisticOracleLivenessTime > 0, "OO liveness cannot be 0");
// // require(optimisticOracleLivenessTime < 5200 weeks, "OO liveness too large");
// // priceIdentifier = priceIdentifier;
// // collateralToken = collateralToken;
// // OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// // require(
// // optimisticOracle.stampAncillaryData(customAncillaryData, address(this)).length <=
// // optimisticOracle.ancillaryBytesLimit(),
// // "Ancillary Data too long"
// // );
// // customAncillaryData = customAncillaryData;
// // prepaidProposerReward = prepaidProposerReward;
// // optimisticOracleLivenessTime = optimisticOracleLivenessTime;
// // optimisticOracleProposerBond = optimisticOracleProposerBond;
// }
/****************************************
* POSITION FUNCTIONS *
****************************************/
/**
* @notice Creates a pair of long and short tokens equal in number to tokensToCreate. Pulls the required collateral
* amount into this contract, defined by the collateralPerPair value.
* @dev The caller must approve this contract to transfer `tokensToCreate * collateralPerPair` amount of collateral.
* @return collateralUsed total collateral used to mint the synthetics.
*/
function create(uint256 _tokensToCreate, string memory _tokenURI, address _to) external payable returns (uint256 collateralUsed) {
// Note the use of mulCeil to prevent small collateralPerPair causing rounding of collateralUsed to 0 enabling
// callers to mint dust LSP tokens without paying any collateral.
collateralUsed = FixedPoint.Unsigned(_tokensToCreate).mulCeil(FixedPoint.Unsigned(collateralPerPair)).rawValue;
// require(msg.value == collateralUsed, "deposited collateral is less than collateral used");
// collateralToken.safeTransferFrom(msg.sender, address(this), collateralUsed);
uint256 longNftId = longToken.mint(_to, _tokenURI);
uint256 shortNftId = shortToken.mint(_to, _tokenURI);
if(longNftId == 0) {
longNftId = longToken.getRecentlyMintedTokenId();
}
if(shortNftId == 0) {
shortNftId = shortToken.getRecentlyMintedTokenId();
}
nftToTokenIdToAmount[longTokenAddress][longNftId] = _tokensToCreate;
nftToTokenIdToAmount[shortTokenAddress][shortNftId] = _tokensToCreate;
emit TokensCreated(_to, collateralUsed, _tokensToCreate);
}
/**
* @notice Redeems a pair of long and short tokens equal in number to tokensToRedeem. Returns the commensurate
* amount of collateral to the caller for the pair of tokens, defined by the collateralPerPair value.
* @dev This contract must have the `Burner` role for the `longToken` and `shortToken` in order to call `burnFrom`.
* @dev The caller does not need to approve this contract to transfer any amount of `tokensToRedeem` since long
* and short tokens are burned, rather than transferred, from the caller.
* @return collateralReturned total collateral returned in exchange for the pair of synthetics.
*/
function redeem(address _user) external returns (uint256 collateralReturned) {
LongShortTokenId longShortTokenId = userHoldings[_user][lspHash];
uint256 longTokenId = longShortTokenId.longTokenId;
uint256 shortTokenId = longShortTokenId.shortTokenId;
require(longTokenId != 0 && shortTokenId != 0, "Redeem fail because either of the minted tokens id is 0");
longToken.burn(longTokenId);
shortToken.burn(shortTokenId);
collateralReturned = FixedPoint.Unsigned(nftToTokenIdToAmount[longTokenAddress][longTokenId]).mul(FixedPoint.Unsigned(collateralPerPair)).rawValue;
// collateralToken.safeTransfer(msg.sender, collateralReturned);
payable(msg.sender).transfer(collateralReturned);
emit TokensRedeemed(msg.sender, collateralReturned, longTokenId, shortTokenId);
}
/**
* @notice Settle long and/or short tokens in for collateral at a rate informed by the contract settlement.
* @dev This contract must have the `Burner` role for the `longToken` and `shortToken` in order to call `burnFrom`.
* @dev The caller does not need to approve this contract to transfer any amount of `tokensToRedeem` since long
* and short tokens are burned, rather than transferred, from the caller.
* @return collateralReturned total collateral returned in exchange for the pair of synthetics.
*/
function settle(uint256 longTokenId, uint256 shortTokenId, address _owner)
public
returns (uint256 collateralReturned)
{
// If the contract state is open and postExpiration passed then `expire()` has not yet been called.
require(contractState != ContractState.Open, "Unexpired contract");
// either of them can be zero, meaning only other nft to settle
// Get the current settlement price and store it. If it is not resolved, will revert.
if (contractState != ContractState.ExpiredPriceReceived) {
expiryPrice = _getOraclePriceExpiration(expirationTimestamp);
// Cap the return value at 1.
expiryPercentLong = MathUpgradeable.min(
financialProductLibrary.percentageLongCollateralAtExpiry(lspHash, expiryPrice),
FixedPoint.fromUnscaledUint(1).rawValue
);
contractState = ContractState.ExpiredPriceReceived;
}
uint256 longCollateralRedeemed = 0;
uint256 shortCollateralRedeemed = 0;
uint256 shortTokensToRedeem = 0;
uint256 longTokensToRedeem = 0;
if(longTokenId != 0) {
longToken.burn(longTokenId);
longTokensToRedeem = nftToTokenIdToAmount[longTokenAddress][longTokenId];
longCollateralRedeemed =
FixedPoint
.Unsigned(longTokensToRedeem)
.mul(FixedPoint.Unsigned(collateralPerPair))
.mul(FixedPoint.Unsigned(expiryPercentLong))
.rawValue;
}
if(shortTokenId != 0) {
shortToken.burn(shortTokenId);
shortTokensToRedeem = nftToTokenIdToAmount[shortTokenAddress][shortTokenId];
shortCollateralRedeemed =
FixedPoint
.Unsigned(shortTokensToRedeem)
.mul(FixedPoint.Unsigned(collateralPerPair))
.mul(FixedPoint.fromUnscaledUint(1).sub(FixedPoint.Unsigned(expiryPercentLong)))
.rawValue;
}
collateralReturned = longCollateralRedeemed + shortCollateralRedeemed;
// collateralToken.safeTransfer(msg.sender, collateralReturned);
payable(_owner).transfer(collateralReturned);
emit PositionSettled(msg.sender, collateralReturned, longTokensToRedeem, shortTokensToRedeem);
}
/****************************************
* GLOBAL STATE FUNCTIONS *
****************************************/
function expire() external {
// _requestOraclePriceExpiration();
contractState = ContractState.ExpiredPriceRequested;
emit ContractExpired(msg.sender);
}
/****************************************
* GLOBAL ACCESSORS FUNCTIONS *
****************************************/
/**
* @notice Returns the number of long and short tokens a sponsor wallet holds.
* @param sponsor address of the sponsor to query.
* @return [uint256, uint256]. First is long tokens held by sponsor and second is short tokens held by sponsor.
*/
function getPositionTokens(address sponsor) public view returns (uint256, uint256) {
return (userHoldings[sponsor][lspHash].longTokenId, userHoldings[sponsor][lspHash].shortTokenId);
}
/****************************************
* INTERNAL FUNCTIONS *
****************************************/
function _getOraclePriceExpiration(uint256 requestedTime) internal view returns (uint256) {
// Create an instance of the oracle and get the price. If the price is not resolved revert.
// OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// require(optimisticOracle.hasPrice(address(this), priceIdentifier, requestedTime, customAncillaryData));
// int256 oraclePrice = optimisticOracle.settleAndGetPrice(priceIdentifier, requestedTime, customAncillaryData);
return SETTLEMENT_PRICE;
}
// function _requestOraclePriceExpiration() internal {
// OptimisticOracleInterface optimisticOracle = _getOptimisticOracle();
// // Use the prepaidProposerReward as the proposer reward.
// if (prepaidProposerReward > 0) collateralToken.safeApprove(address(optimisticOracle), prepaidProposerReward);
// optimisticOracle.requestPrice(
// priceIdentifier,
// expirationTimestamp,
// customAncillaryData,
// collateralToken,
// prepaidProposerReward
// );
// // Set the Optimistic oracle liveness for the price request.
// optimisticOracle.setCustomLiveness(
// priceIdentifier,
// expirationTimestamp,
// customAncillaryData,
// optimisticOracleLivenessTime
// );
// // Set the Optimistic oracle proposer bond for the price request.
// optimisticOracle.setBond(
// priceIdentifier,
// expirationTimestamp,
// customAncillaryData,
// optimisticOracleProposerBond
// );
// }
// function _getIdentifierWhitelist() internal view returns (IdentifierWhitelistInterface) {
// return IdentifierWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.IdentifierWhitelist));
// }
// function _getCollateralWhitelist() internal view returns (AddressWhitelistInterface) {
// return AddressWhitelistInterface(finder.getImplementationAddress(OracleInterfaces.CollateralWhitelist));
// }
// function _getOptimisticOracle() internal view returns (OptimisticOracleInterface) {
// return OptimisticOracleInterface(finder.getImplementationAddress(OracleInterfaces.OptimisticOracle));
// }
function _getCurrentTime() internal view returns (uint256) {
return block.timestamp;
}
}
| _requestOraclePriceExpiration(); | function expire() external {
contractState = ContractState.ExpiredPriceRequested;
emit ContractExpired(msg.sender);
}
| 14,121,957 | [
1,
67,
2293,
23601,
5147,
12028,
5621,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
6930,
1435,
3903,
288,
203,
3639,
6835,
1119,
273,
13456,
1119,
18,
10556,
5147,
11244,
31,
203,
203,
3639,
3626,
13456,
10556,
12,
3576,
18,
15330,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/8453/0x373B887bfeE09F5fA721D5b1e8abfaFe067f41BC/sources/contracts/farms/BasetasticChef.sol | @notice Set the address of rewardMinter. Can only be called ONCE by the owner. @param _rewardMinter Address of MultiFeeDistribution contract | function setRewardMinter(IBasetasticStaking _rewardMinter) external {
require(address(rewardMinter) == address(0), "BasetasticChef::setRewardMinter: Cannot redefine rewardMinter");
rewardMinter = _rewardMinter;
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint256 lastRewardTime, uint256 lpSupply, uint256 accRewardPerShare);
event LogRewardPerSecond(uint256 rewardPerSecond);
| 11,535,606 | [
1,
694,
326,
1758,
434,
19890,
49,
2761,
18,
225,
4480,
1338,
506,
2566,
6229,
1441,
635,
326,
3410,
18,
225,
389,
266,
2913,
49,
2761,
5267,
434,
5991,
14667,
9003,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
444,
17631,
1060,
49,
2761,
12,
13450,
2759,
8160,
510,
6159,
389,
266,
2913,
49,
2761,
13,
3903,
288,
203,
3639,
2583,
12,
2867,
12,
266,
2913,
49,
2761,
13,
422,
1758,
12,
20,
3631,
315,
38,
2759,
8160,
39,
580,
74,
2866,
542,
17631,
1060,
49,
2761,
30,
14143,
283,
11255,
19890,
49,
2761,
8863,
203,
3639,
19890,
49,
2761,
273,
389,
266,
2913,
49,
2761,
31,
203,
565,
289,
203,
203,
565,
871,
4019,
538,
305,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
16,
1758,
8808,
358,
1769,
203,
565,
871,
3423,
9446,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
16,
1758,
8808,
358,
1769,
203,
565,
871,
512,
6592,
75,
2075,
1190,
9446,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
16,
1758,
8808,
358,
1769,
203,
565,
871,
670,
297,
26923,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
1827,
2864,
30296,
12,
11890,
5034,
8808,
4231,
16,
2254,
5034,
4767,
2148,
16,
467,
654,
39,
3462,
8808,
12423,
1345,
16,
15908,
359,
297,
765,
8808,
283,
20099,
1769,
203,
565,
871,
1827,
694,
2864,
12,
11890,
5034,
8808,
4231,
16,
2254,
5034,
4767,
2148,
16,
15908,
359,
297,
765,
8808,
283,
20099,
16,
1426,
6156,
1769,
203,
565,
871,
1827,
1891,
2864,
12,
11890,
5034,
8808,
4231,
16,
2254,
5034,
1142,
17631,
1060,
950,
16,
2254,
5034,
12423,
3088,
1283,
16,
2
]
|
pragma solidity 0.4.25;
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
pragma solidity 0.4.25;
import "./IERC165.sol";
/**
* @title ERC165
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract ERC165 is IERC165 {
bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor () internal {
_registerInterface(_InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
pragma solidity 0.4.25;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./SafeMath.sol";
import "./Address.sol";
import "./ERC165.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) internal _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_InterfaceId_ERC721);
}
/**
* @dev Gets the balance of the specified address
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0));
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 Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId));
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != msg.sender);
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public {
require(_isApprovedOrOwner(msg.sender, tokenId));
require(to != address(0));
_clearApproval(from, tokenId);
_removeTokenFrom(from, tokenId);
_addTokenTo(to, tokenId);
emit Transfer(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
// solium-disable-next-line arg-overflow
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
transferFrom(from, to, tokenId);
// solium-disable-next-line arg-overflow
require(_checkOnERC721Received(from, to, tokenId, _data));
}
/**
* @dev Returns whether the specified token exists
* @param tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
address owner = ownerOf(tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0));
_addTokenTo(to, tokenId);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
_clearApproval(owner, tokenId);
_removeTokenFrom(owner, tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to add a token ID to the list of a given address
* Note that this function is left internal to make ERC721Enumerable possible, but is not
* intended to be called by custom derived contracts: in particular, it emits no Transfer event.
* @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
* Note that this function is left internal to make ERC721Enumerable possible, but is not
* intended to be called by custom derived contracts: in particular, it emits no Transfer event,
* and doesn't clear approvals.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFrom(address from, uint256 tokenId) internal {
require(ownerOf(tokenId) == from);
_ownedTokensCount[from] = _ownedTokensCount[from].sub(1);
_tokenOwner[tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* The call is not executed if the target address is not a contract
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) {
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
* @param owner owner of the token
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(address owner, uint256 tokenId) private {
require(ownerOf(tokenId) == owner);
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
pragma solidity 0.4.25;
import "./IERC721Enumerable.sol";
import "./ERC721.sol";
import "./ERC165.sol";
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor () public {
// register the supported interface to conform to ERC721 via ERC165
_registerInterface(_InterfaceId_ERC721Enumerable);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
require(index < balanceOf(owner));
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply());
return _allTokens[index];
}
/**
* @dev Internal function to add a token ID to the list of a given address
* This function is internal due to language limitations, see the note in ERC721.sol.
* It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event.
* @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
* This function is internal due to language limitations, see the note in ERC721.sol.
* It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event,
* and doesn't clear approvals.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFrom(address from, uint256 tokenId) internal {
super._removeTokenFrom(from, tokenId);
// To prevent a gap in the array, we store the last token in the index of the token to delete, and
// then delete the last slot.
uint256 tokenIndex = _ownedTokensIndex[tokenId];
uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
uint256 lastToken = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastToken;
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
_ownedTokensIndex[tokenId] = 0;
_ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// 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;
}
}
pragma solidity 0.4.25;
import "./ERC721.sol";
import "./IERC721Metadata.sol";
import "./ERC165.sol";
contract ERC721Metadata is ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId));
return _tokenURIs[tokenId];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(_exists(tokenId));
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
pragma solidity 0.4.25;
/**
* @title IERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
pragma solidity 0.4.25;
import "./IERC165.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
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 memory data) public;
}
pragma solidity 0.4.25;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId);
function tokenByIndex(uint256 index) public view returns (uint256);
}
pragma solidity 0.4.25;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
pragma solidity 0.4.25;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safeTransfer`. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4);
}
pragma solidity 0.4.25;
/// @title IOracle
/// @dev Interface for getting the data from the oracle contract.
interface IOracle {
function ethUsdPrice() external view returns(uint256);
}
pragma solidity 0.4.25;
/// @title ISettings
/// @dev Interface for getting the data from settings contract.
interface ISettings {
function oracleAddress() external view returns(address);
function minDeposit() external view returns(uint256);
function sysFee() external view returns(uint256);
function userFee() external view returns(uint256);
function ratio() external view returns(uint256);
function globalTargetCollateralization() external view returns(uint256);
function tmvAddress() external view returns(uint256);
function maxStability() external view returns(uint256);
function minStability() external view returns(uint256);
function gasPriceLimit() external view returns(uint256);
function isFeeManager(address account) external view returns (bool);
function tBoxManager() external view returns(address);
}
pragma solidity 0.4.25;
/// @title IToken
/// @dev Interface for interaction with the TMV token contract.
interface IToken {
function burnLogic(address from, uint256 value) external;
function approve(address spender, uint256 value) external;
function balanceOf(address who) external view returns (uint256);
function mint(address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 tokenId) external;
}
pragma solidity 0.4.25;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, 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, 'mul');
return c;
}
/**
* @dev Integer division of two numbers 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, 'div');
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 numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, 'sub');
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'add');
return c;
}
/**
* @dev Divides two numbers 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;
}
}
pragma solidity 0.4.25;
import "./TBoxToken.sol";
import "./ISettings.sol";
import "./IToken.sol";
import "./IOracle.sol";
/// @title TBoxManager
contract TBoxManager is TBoxToken {
// Total packed Ether
uint256 public globalETH;
// Precision using for USD and commission
uint256 public precision = 100000;
// The address of the system settings contract
ISettings public settings;
/// @dev An array containing the Boxes struct for all Boxes in existence. The ID
/// of each Box is actually an index into this array.
Box[] public boxes;
/// @dev The main Box struct. Every Box in TimviSystem is represented by a copy
/// of this structure.
struct Box {
// The collateral Ether amount in wei
uint256 collateral;
// The number of TMV withdrawn
uint256 tmvReleased;
}
/// @dev The Created event is fired whenever a new Box comes into existence. This includes
/// any time a Box is created through the create method.
event Created(uint256 indexed id, address owner, uint256 collateral, uint256 tmvReleased);
/// @dev The Closed event is fired whenever a Box is closed. Obviously, this includes
/// any time a Box is closed through the close method, but it is also called when
// a Box is closed through the closeDust method.
event Closed(uint256 indexed id, address indexed owner, address indexed closer);
/// @dev The Capitalized event is fired whenever a Box is capitalized.
event Capitalized(uint256 indexed id, address indexed owner, address indexed who, uint256 tmvAmount, uint256 totalEth, uint256 userEth);
/// @dev The EthWithdrawn event is fired whenever Ether is withdrawn from a Box
/// using withdrawEth method.
event EthWithdrawn(uint256 indexed id, uint256 value, address who);
/// @dev The TmvWithdrawn event is fired whenever TMV is withdrawn from a Box
/// using withdrawTmv method.
event TmvWithdrawn(uint256 indexed id, uint256 value, address who);
/// @dev The EthAdded event is fired whenever Ether is added to a Box
/// using addEth method.
event EthAdded(uint256 indexed id, uint256 value, address who);
/// @dev The TmvAdded event is fired whenever TMV is added to a Box
/// using addTmv method.
event TmvAdded(uint256 indexed id, uint256 value, address who);
/// @dev Defends against front-running attacks.
modifier validTx() {
require(tx.gasprice <= settings.gasPriceLimit(), "Gas price is greater than allowed");
_;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyAdmin() {
require(settings.isFeeManager(msg.sender), "You have no access");
_;
}
/// @dev Throws if Box with specified id does not exist.
modifier onlyExists(uint256 _id) {
require(_exists(_id), "Box does not exist");
_;
}
/// @dev Access modifier for token owner-only functionality.
modifier onlyApprovedOrOwner(uint256 _id) {
require(_isApprovedOrOwner(msg.sender, _id), "Box isn't your");
_;
}
/// @dev The constructor sets ERC721 token name and symbol.
/// @param _settings The address of the system settings contract.
constructor(address _settings) TBoxToken("TBoxToken", "TBX") public {
settings = ISettings(_settings);
}
/// @notice The funds are safe.
/// @dev Creates Box with max collateral percent.
function() external payable {
// Redirect to the create method with no tokens to withdraw
create(0);
}
/// @dev Withdraws system fee.
function withdrawFee(address _beneficiary) external onlyAdmin {
require(_beneficiary != address(0), "Zero address, be careful");
// Fee is the difference between the contract balance and
// amount of Ether used in the entire system collateralization
uint256 _fees = address(this).balance.sub(globalETH);
// Check that the fee is collected
require(_fees > 0, "There is no available fees");
// Transfer fee to provided address
_beneficiary.transfer(_fees);
}
/// @dev Checks possibility of the issue of the specified token amount
/// for provided Ether collateral and creates new Box
/// @param _tokensToWithdraw Number of tokens to withdraw
/// @return New Box ID.
function create(uint256 _tokensToWithdraw) public payable validTx returns (uint256) {
// Check that msg.value isn't smaller than minimum deposit
require(msg.value >= settings.minDeposit(), "Deposit is very small");
// Calculate collateralization when tokens are needed
if (_tokensToWithdraw > 0) {
// The number of tokens when collateralization is high
uint256 _tokenLimit = overCapWithdrawableTmv(msg.value);
// The number of tokens that can be safely withdrawn from the system
uint256 _maxGlobal = globalWithdrawableTmv(msg.value);
// Determine the higher number of tokens
if (_tokenLimit > _maxGlobal) {
_tokenLimit = _maxGlobal;
}
// The number of tokens that can be withdrawn anyway
uint256 _local = defaultWithdrawableTmv(msg.value);
// Determine the higher number of tokens
if (_tokenLimit < _local) {
_tokenLimit = _local;
}
// You can only withdraw available amount
require(_tokensToWithdraw <= _tokenLimit, "Token amount is more than available");
// Mint TMV tokens to the Box creator
IToken(settings.tmvAddress()).mint(msg.sender, _tokensToWithdraw);
}
// The id of the new Box
uint256 _id = boxes.push(Box(msg.value, _tokensToWithdraw)).sub(1);
// Increase global Ether counter
globalETH = globalETH.add(msg.value);
// Mint TBX token to the Box creator
_mint(msg.sender, _id);
// Fire the event
emit Created(_id, msg.sender, msg.value, _tokensToWithdraw);
// return the new Box's ID
return _id;
}
/// @dev Allows the owner or approved user of the Box to close one by burning the
/// required number of tokens and return the Box's collateral.
/// @param _id A Box ID to close.
function close(uint256 _id) external onlyApprovedOrOwner(_id) {
// Address of the owner of the Box
address _owner = _tokenOwner[_id];
// Burn needed number of tokens
uint256 _tokensNeed = boxes[_id].tmvReleased;
_burnTMV(msg.sender, _tokensNeed);
// Grab a reference to the Box's collateral in storage
uint256 _collateral = boxes[_id].collateral;
// burn Box token
_burn(_owner, _id);
// Removes Box
delete boxes[_id];
// Send the Box's collateral to the person who made closing happen
msg.sender.transfer(_collateral);
// Decrease global Ether counter
globalETH = globalETH.sub(_collateral);
// Fire the event
emit Closed(_id, _owner, msg.sender);
}
/// @notice This allows you not to be tied to the current ETH/USD rate.
/// @dev Allows the user to capitalize a Box with the maximum current amount.
/// @param _id A Box ID to capitalize.
function capitalizeMax(uint256 _id) external {
capitalize(_id, maxCapAmount(_id));
}
/// @dev Allows the user to capitalize a Box with specified number of tokens.
/// @param _id A Box ID to capitalize.
/// @param _tmv Specified number of tokens to capitalize.
function capitalize(uint256 _id, uint256 _tmv) public validTx {
// The maximum number of tokens for which Box can be capitalized
uint256 _maxCapAmount = maxCapAmount(_id);
// Check the number of tokens
require(_tmv <= _maxCapAmount && _tmv >= 10 ** 17, "Tokens amount out of range");
// Decrease Box TMV withdrawn counter
boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_tmv);
// Calculate the Ether equivalent of tokens according to the logic
// where 1 TMV is equal to 1 USD
uint256 _equivalentETH = _tmv.mul(precision).div(rate());
// Calculate system fee
uint256 _fee = _tmv.mul(settings.sysFee()).div(rate());
// Calculate user bonus
uint256 _userReward = _tmv.mul(settings.userFee()).div(rate());
// Decrease Box's collateral amount
boxes[_id].collateral = boxes[_id].collateral.sub(_fee.add(_userReward).add(_equivalentETH));
// Decrease global Ether counter
globalETH = globalETH.sub(_fee.add(_userReward).add(_equivalentETH));
// burn Box token
_burnTMV(msg.sender, _tmv);
// Send the Ether equivalent & user benefit to the person who made capitalization happen.
msg.sender.transfer(_equivalentETH.add(_userReward));
// Fire the event
emit Capitalized(_id, ownerOf(_id), msg.sender, _tmv, _equivalentETH.add(_userReward).add(_fee), _equivalentETH.add(_userReward));
}
/// @notice This allows you not to be tied to the current ETH/USD rate.
/// @dev Allows an owner or approved user of the Box to withdraw maximum amount
/// of Ether from the Box.
/// @param _id A Box ID.
function withdrawEthMax(uint256 _id) external {
withdrawEth(_id, withdrawableEth(_id));
}
/// @dev Allows an owner or approved user of the Box to withdraw specified amount
/// of Ether from the Box.
/// @param _id A Box ID.
/// @param _amount The number of Ether to withdraw.
function withdrawEth(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx {
require(_amount > 0, "Withdrawing zero");
require(_amount <= withdrawableEth(_id), "You can't withdraw so much");
// Decrease Box's collateral amount
boxes[_id].collateral = boxes[_id].collateral.sub(_amount);
// Decrease global Ether counter
globalETH = globalETH.sub(_amount);
// Send the Ether to the person who made capitalization happen
msg.sender.transfer(_amount);
// Fire the event
emit EthWithdrawn(_id, _amount, msg.sender);
}
/// @notice This allows you not to be tied to the current ETH/USD rate.
/// @dev Allows an owner or approved user of the Box to withdraw maximum number
/// of TMV tokens from the Box.
/// @param _id A Box ID.
function withdrawTmvMax(uint256 _id) external onlyApprovedOrOwner(_id) {
withdrawTmv(_id, boxWithdrawableTmv(_id));
}
/// @dev Allows an owner or approved user of the Box to withdraw specified number
/// of TMV tokens from the Box.
/// @param _id A Box ID.
/// @param _amount The number of tokens to withdraw.
function withdrawTmv(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx {
require(_amount > 0, "Withdrawing zero");
// Check the number of tokens
require(_amount <= boxWithdrawableTmv(_id), "You can't withdraw so much");
// Increase Box TMV withdrawn counter
boxes[_id].tmvReleased = boxes[_id].tmvReleased.add(_amount);
// Mints tokens to the person who made withdrawing
IToken(settings.tmvAddress()).mint(msg.sender, _amount);
// Fire the event
emit TmvWithdrawn(_id, _amount, msg.sender);
}
/// @dev Allows anyone to add Ether to a Box.
/// @param _id A Box ID.
function addEth(uint256 _id) external payable onlyExists(_id) {
require(msg.value > 0, "Don't add 0");
// Increase Box collateral
boxes[_id].collateral = boxes[_id].collateral.add(msg.value);
// Increase global Ether counter
globalETH = globalETH.add(msg.value);
// Fire the event
emit EthAdded(_id, msg.value, msg.sender);
}
/// @dev Allows anyone to add TMV to a Box.
/// @param _id A Box ID.
/// @param _amount The number of tokens to add.
function addTmv(uint256 _id, uint256 _amount) external onlyExists(_id) {
require(_amount > 0, "Don't add 0");
// Check the number of tokens
require(_amount <= boxes[_id].tmvReleased, "Too much tokens");
// Removes added tokens from the collateralization
_burnTMV(msg.sender, _amount);
boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_amount);
// Fire the event
emit TmvAdded(_id, _amount, msg.sender);
}
/// @dev Allows anyone to close Box with collateral amount smaller than 3 USD.
/// The person who made closing happen will benefit like capitalization.
/// @param _id A Box ID.
function closeDust(uint256 _id) external onlyExists(_id) validTx {
// Check collateral percent of the Box
require(collateralPercent(_id) >= settings.minStability(), "This Box isn't collapsable");
// Check collateral amount of the Box
require(boxes[_id].collateral.mul(rate()) < precision.mul(3).mul(10 ** 18), "It's only possible to collapse dust");
// Burn needed TMV amount to close
uint256 _tmvReleased = boxes[_id].tmvReleased;
_burnTMV(msg.sender, _tmvReleased);
uint256 _collateral = boxes[_id].collateral;
// Calculate the Ether equivalent of tokens according to the logic
// where 1 TMV is equal to 1 USD
uint256 _eth = _tmvReleased.mul(precision).div(rate());
// Calculate user bonus
uint256 _userReward = _tmvReleased.mul(settings.userFee()).div(rate());
// The owner of the Box
address _owner = ownerOf(_id);
// Remove a Box
delete boxes[_id];
// Burn Box token
_burn(_owner, _id);
// Send the Ether equivalent & user benefit to the person who made closing happen
msg.sender.transfer(_eth.add(_userReward));
// Decrease global Ether counter
globalETH = globalETH.sub(_collateral);
// Fire the event
emit Closed(_id, _owner, msg.sender);
}
/// @dev Burns specified number of TMV tokens.
function _burnTMV(address _from, uint256 _amount) internal {
if (_amount > 0) {
require(IToken(settings.tmvAddress()).balanceOf(_from) >= _amount, "You don't have enough tokens");
IToken(settings.tmvAddress()).burnLogic(_from, _amount);
}
}
/// @dev Returns current oracle ETH/USD price with precision.
function rate() public view returns(uint256) {
return IOracle(settings.oracleAddress()).ethUsdPrice();
}
/// @dev Given a Box ID, returns a number of tokens that can be withdrawn.
function boxWithdrawableTmv(uint256 _id) public view onlyExists(_id) returns(uint256) {
Box memory box = boxes[_id];
// Number of tokens that can be withdrawn for Box's collateral
uint256 _amount = withdrawableTmv(box.collateral);
if (box.tmvReleased >= _amount) {
return 0;
}
// Return withdrawable rest
return _amount.sub(box.tmvReleased);
}
/// @dev Given a Box ID, returns an amount of Ether that can be withdrawn.
function withdrawableEth(uint256 _id) public view onlyExists(_id) returns(uint256) {
// Amount of Ether that is not used in collateralization
uint256 _avlbl = _freeEth(_id);
// Return available Ether to withdraw
if (_avlbl == 0) {
return 0;
}
uint256 _rest = boxes[_id].collateral.sub(_avlbl);
if (_rest < settings.minDeposit()) {
return boxes[_id].collateral.sub(settings.minDeposit());
}
else return _avlbl;
}
/// @dev Given a Box ID, returns amount of ETH that is not used in collateralization.
function _freeEth(uint256 _id) internal view returns(uint256) {
// Grab a reference to the Box
Box memory box = boxes[_id];
// When there are no tokens withdrawn
if (box.tmvReleased == 0) {
return box.collateral;
}
// The amount of Ether that can be safely withdrawn from the system
uint256 _maxGlobal = globalWithdrawableEth();
uint256 _globalAvailable;
if (_maxGlobal > 0) {
// The amount of Ether backing the tokens when the system is overcapitalized
uint256 _need = overCapFrozenEth(box.tmvReleased);
if (box.collateral > _need) {
// Free Ether amount when the system is overcapitalized
uint256 _free = box.collateral.sub(_need);
if (_free > _maxGlobal) {
// Store available amount when Box available Ether amount
// is more than global available
_globalAvailable = _maxGlobal;
}
// Return available amount of Ether to withdraw when the Box withdrawable
// amount of Ether is smaller than global withdrawable amount of Ether
else return _free;
}
}
// The amount of Ether backing the tokens by default
uint256 _frozen = defaultFrozenEth(box.tmvReleased);
if (box.collateral > _frozen) {
// Define the biggest number and return available Ether amount
uint256 _localAvailable = box.collateral.sub(_frozen);
return (_localAvailable > _globalAvailable) ? _localAvailable : _globalAvailable;
} else {
// Return available Ether amount
return _globalAvailable;
}
}
/// @dev Given a Box ID, returns collateral percent.
function collateralPercent(uint256 _id) public view onlyExists(_id) returns(uint256) {
Box memory box = boxes[_id];
if (box.tmvReleased == 0) {
return 10**27; //some unreachable number
}
uint256 _ethCollateral = box.collateral;
// division by 100 is not necessary because to get the percent you need to multiply by 100
return _ethCollateral.mul(rate()).div(box.tmvReleased);
}
/// @dev Checks if a given address currently has approval for a particular Box.
/// @param _spender the address we are confirming Box is approved for.
/// @param _tokenId Box ID.
function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool) {
return _isApprovedOrOwner(_spender, _tokenId);
}
/// @dev Returns the global collateralization percent.
function globalCollateralization() public view returns (uint256) {
uint256 _supply = IToken(settings.tmvAddress()).totalSupply();
if (_supply == 0) {
return settings.globalTargetCollateralization();
}
return globalETH.mul(rate()).div(_supply);
}
/// @dev Returns the number of tokens that can be safely withdrawn from the system.
function globalWithdrawableTmv(uint256 _value) public view returns (uint256) {
uint256 _supply = IToken(settings.tmvAddress()).totalSupply();
if (globalCollateralization() <= settings.globalTargetCollateralization()) {
return 0;
}
uint256 _totalBackedTmv = defaultWithdrawableTmv(globalETH.add(_value));
return _totalBackedTmv.sub(_supply);
}
/// @dev Returns Ether amount that can be safely withdrawn from the system.
function globalWithdrawableEth() public view returns (uint256) {
uint256 _supply = IToken(settings.tmvAddress()).totalSupply();
if (globalCollateralization() <= settings.globalTargetCollateralization()) {
return 0;
}
uint256 _need = defaultFrozenEth(_supply);
return globalETH.sub(_need);
}
/// @dev Returns the number of tokens that can be withdrawn
/// for the specified collateral amount by default.
function defaultWithdrawableTmv(uint256 _collateral) public view returns (uint256) {
uint256 _num = _collateral.mul(rate());
uint256 _div = settings.globalTargetCollateralization();
return _num.div(_div);
}
/// @dev Returns the number of tokens that can be withdrawn
/// for the specified collateral amount when the system is overcapitalized.
function overCapWithdrawableTmv(uint256 _collateral) public view returns (uint256) {
uint256 _num = _collateral.mul(rate());
uint256 _div = settings.ratio();
return _num.div(_div);
}
/// @dev Returns Ether amount backing the specified number of tokens by default.
function defaultFrozenEth(uint256 _supply) public view returns (uint256) {
return _supply.mul(settings.globalTargetCollateralization()).div(rate());
}
/// @dev Returns Ether amount backing the specified number of tokens
/// when the system is overcapitalized.
function overCapFrozenEth(uint256 _supply) public view returns (uint256) {
return _supply.mul(settings.ratio()).div(rate());
}
/// @dev Returns the number of TMV that can capitalize the specified Box.
function maxCapAmount(uint256 _id) public view onlyExists(_id) returns (uint256) {
uint256 _colP = collateralPercent(_id);
require(_colP >= settings.minStability() && _colP < settings.maxStability(), "It's only possible to capitalize toxic Boxes");
Box memory box = boxes[_id];
uint256 _num = box.tmvReleased.mul(settings.ratio()).sub(box.collateral.mul(rate()));
uint256 _div = settings.ratio().sub(settings.minStability());
return _num.div(_div);
}
/// @dev Returns the number of tokens that can be actually withdrawn
/// for the specified collateral.
function withdrawableTmv(uint256 _collateral) public view returns(uint256) {
uint256 _amount = overCapWithdrawableTmv(_collateral);
uint256 _maxGlobal = globalWithdrawableTmv(0);
if (_amount > _maxGlobal) {
_amount = _maxGlobal;
}
uint256 _local = defaultWithdrawableTmv(_collateral);
if (_amount < _local) {
_amount = _local;
}
return _amount;
}
/// @dev Returns the collateral percentage for which tokens can be withdrawn
/// for the specified collateral.
function withdrawPercent(uint256 _collateral) external view returns(uint256) {
uint256 _amount = overCapWithdrawableTmv(_collateral);
uint256 _maxGlobal = globalWithdrawableTmv(_collateral);
if (_amount > _maxGlobal) {
_amount = _maxGlobal;
}
uint256 _local = defaultWithdrawableTmv(_collateral);
if (_amount < _local) {
_amount = _local;
}
return _collateral.mul(rate()).div(_amount);
}
}
pragma solidity 0.4.25;
import "./ERC721.sol";
import "./ERC721Enumerable.sol";
import "./ERC721Metadata.sol";
/**
* @title TBoxClassic 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 TBoxToken is ERC721, ERC721Enumerable, ERC721Metadata {
constructor (string memory name, string memory symbol) ERC721Metadata(name, symbol) public {}
}
pragma solidity 0.4.25;
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
pragma solidity 0.4.25;
import "./IERC165.sol";
/**
* @title ERC165
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract ERC165 is IERC165 {
bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor () internal {
_registerInterface(_InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
pragma solidity 0.4.25;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./SafeMath.sol";
import "./Address.sol";
import "./ERC165.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) internal _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_InterfaceId_ERC721);
}
/**
* @dev Gets the balance of the specified address
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0));
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 Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId));
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != msg.sender);
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public {
require(_isApprovedOrOwner(msg.sender, tokenId));
require(to != address(0));
_clearApproval(from, tokenId);
_removeTokenFrom(from, tokenId);
_addTokenTo(to, tokenId);
emit Transfer(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
// solium-disable-next-line arg-overflow
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
transferFrom(from, to, tokenId);
// solium-disable-next-line arg-overflow
require(_checkOnERC721Received(from, to, tokenId, _data));
}
/**
* @dev Returns whether the specified token exists
* @param tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
address owner = ownerOf(tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0));
_addTokenTo(to, tokenId);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
_clearApproval(owner, tokenId);
_removeTokenFrom(owner, tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to add a token ID to the list of a given address
* Note that this function is left internal to make ERC721Enumerable possible, but is not
* intended to be called by custom derived contracts: in particular, it emits no Transfer event.
* @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
* Note that this function is left internal to make ERC721Enumerable possible, but is not
* intended to be called by custom derived contracts: in particular, it emits no Transfer event,
* and doesn't clear approvals.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFrom(address from, uint256 tokenId) internal {
require(ownerOf(tokenId) == from);
_ownedTokensCount[from] = _ownedTokensCount[from].sub(1);
_tokenOwner[tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* The call is not executed if the target address is not a contract
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) {
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
* @param owner owner of the token
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(address owner, uint256 tokenId) private {
require(ownerOf(tokenId) == owner);
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
pragma solidity 0.4.25;
import "./IERC721Enumerable.sol";
import "./ERC721.sol";
import "./ERC165.sol";
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor () public {
// register the supported interface to conform to ERC721 via ERC165
_registerInterface(_InterfaceId_ERC721Enumerable);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
require(index < balanceOf(owner));
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply());
return _allTokens[index];
}
/**
* @dev Internal function to add a token ID to the list of a given address
* This function is internal due to language limitations, see the note in ERC721.sol.
* It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event.
* @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
* This function is internal due to language limitations, see the note in ERC721.sol.
* It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event,
* and doesn't clear approvals.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFrom(address from, uint256 tokenId) internal {
super._removeTokenFrom(from, tokenId);
// To prevent a gap in the array, we store the last token in the index of the token to delete, and
// then delete the last slot.
uint256 tokenIndex = _ownedTokensIndex[tokenId];
uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
uint256 lastToken = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastToken;
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
_ownedTokensIndex[tokenId] = 0;
_ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// 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;
}
}
pragma solidity 0.4.25;
import "./ERC721.sol";
import "./IERC721Metadata.sol";
import "./ERC165.sol";
contract ERC721Metadata is ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId));
return _tokenURIs[tokenId];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(_exists(tokenId));
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
pragma solidity 0.4.25;
/**
* @title IERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
pragma solidity 0.4.25;
import "./IERC165.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
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 memory data) public;
}
pragma solidity 0.4.25;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId);
function tokenByIndex(uint256 index) public view returns (uint256);
}
pragma solidity 0.4.25;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
pragma solidity 0.4.25;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safeTransfer`. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4);
}
pragma solidity 0.4.25;
/// @title IOracle
/// @dev Interface for getting the data from the oracle contract.
interface IOracle {
function ethUsdPrice() external view returns(uint256);
}
pragma solidity 0.4.25;
/// @title ISettings
/// @dev Interface for getting the data from settings contract.
interface ISettings {
function oracleAddress() external view returns(address);
function minDeposit() external view returns(uint256);
function sysFee() external view returns(uint256);
function userFee() external view returns(uint256);
function ratio() external view returns(uint256);
function globalTargetCollateralization() external view returns(uint256);
function tmvAddress() external view returns(uint256);
function maxStability() external view returns(uint256);
function minStability() external view returns(uint256);
function gasPriceLimit() external view returns(uint256);
function isFeeManager(address account) external view returns (bool);
function tBoxManager() external view returns(address);
}
pragma solidity 0.4.25;
/// @title IToken
/// @dev Interface for interaction with the TMV token contract.
interface IToken {
function burnLogic(address from, uint256 value) external;
function approve(address spender, uint256 value) external;
function balanceOf(address who) external view returns (uint256);
function mint(address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 tokenId) external;
}
pragma solidity 0.4.25;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, 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, 'mul');
return c;
}
/**
* @dev Integer division of two numbers 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, 'div');
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 numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, 'sub');
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'add');
return c;
}
/**
* @dev Divides two numbers 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;
}
}
pragma solidity 0.4.25;
import "./TBoxToken.sol";
import "./ISettings.sol";
import "./IToken.sol";
import "./IOracle.sol";
/// @title TBoxManager
contract TBoxManager is TBoxToken {
// Total packed Ether
uint256 public globalETH;
// Precision using for USD and commission
uint256 public precision = 100000;
// The address of the system settings contract
ISettings public settings;
/// @dev An array containing the Boxes struct for all Boxes in existence. The ID
/// of each Box is actually an index into this array.
Box[] public boxes;
/// @dev The main Box struct. Every Box in TimviSystem is represented by a copy
/// of this structure.
struct Box {
// The collateral Ether amount in wei
uint256 collateral;
// The number of TMV withdrawn
uint256 tmvReleased;
}
/// @dev The Created event is fired whenever a new Box comes into existence. This includes
/// any time a Box is created through the create method.
event Created(uint256 indexed id, address owner, uint256 collateral, uint256 tmvReleased);
/// @dev The Closed event is fired whenever a Box is closed. Obviously, this includes
/// any time a Box is closed through the close method, but it is also called when
// a Box is closed through the closeDust method.
event Closed(uint256 indexed id, address indexed owner, address indexed closer);
/// @dev The Capitalized event is fired whenever a Box is capitalized.
event Capitalized(uint256 indexed id, address indexed owner, address indexed who, uint256 tmvAmount, uint256 totalEth, uint256 userEth);
/// @dev The EthWithdrawn event is fired whenever Ether is withdrawn from a Box
/// using withdrawEth method.
event EthWithdrawn(uint256 indexed id, uint256 value, address who);
/// @dev The TmvWithdrawn event is fired whenever TMV is withdrawn from a Box
/// using withdrawTmv method.
event TmvWithdrawn(uint256 indexed id, uint256 value, address who);
/// @dev The EthAdded event is fired whenever Ether is added to a Box
/// using addEth method.
event EthAdded(uint256 indexed id, uint256 value, address who);
/// @dev The TmvAdded event is fired whenever TMV is added to a Box
/// using addTmv method.
event TmvAdded(uint256 indexed id, uint256 value, address who);
/// @dev Defends against front-running attacks.
modifier validTx() {
require(tx.gasprice <= settings.gasPriceLimit(), "Gas price is greater than allowed");
_;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyAdmin() {
require(settings.isFeeManager(msg.sender), "You have no access");
_;
}
/// @dev Throws if Box with specified id does not exist.
modifier onlyExists(uint256 _id) {
require(_exists(_id), "Box does not exist");
_;
}
/// @dev Access modifier for token owner-only functionality.
modifier onlyApprovedOrOwner(uint256 _id) {
require(_isApprovedOrOwner(msg.sender, _id), "Box isn't your");
_;
}
/// @dev The constructor sets ERC721 token name and symbol.
/// @param _settings The address of the system settings contract.
constructor(address _settings) TBoxToken("TBoxToken", "TBX") public {
settings = ISettings(_settings);
}
/// @notice The funds are safe.
/// @dev Creates Box with max collateral percent.
function() external payable {
// Redirect to the create method with no tokens to withdraw
create(0);
}
/// @dev Withdraws system fee.
function withdrawFee(address _beneficiary) external onlyAdmin {
require(_beneficiary != address(0), "Zero address, be careful");
// Fee is the difference between the contract balance and
// amount of Ether used in the entire system collateralization
uint256 _fees = address(this).balance.sub(globalETH);
// Check that the fee is collected
require(_fees > 0, "There is no available fees");
// Transfer fee to provided address
_beneficiary.transfer(_fees);
}
/// @dev Checks possibility of the issue of the specified token amount
/// for provided Ether collateral and creates new Box
/// @param _tokensToWithdraw Number of tokens to withdraw
/// @return New Box ID.
function create(uint256 _tokensToWithdraw) public payable validTx returns (uint256) {
// Check that msg.value isn't smaller than minimum deposit
require(msg.value >= settings.minDeposit(), "Deposit is very small");
// Calculate collateralization when tokens are needed
if (_tokensToWithdraw > 0) {
// The number of tokens when collateralization is high
uint256 _tokenLimit = overCapWithdrawableTmv(msg.value);
// The number of tokens that can be safely withdrawn from the system
uint256 _maxGlobal = globalWithdrawableTmv(msg.value);
// Determine the higher number of tokens
if (_tokenLimit > _maxGlobal) {
_tokenLimit = _maxGlobal;
}
// The number of tokens that can be withdrawn anyway
uint256 _local = defaultWithdrawableTmv(msg.value);
// Determine the higher number of tokens
if (_tokenLimit < _local) {
_tokenLimit = _local;
}
// You can only withdraw available amount
require(_tokensToWithdraw <= _tokenLimit, "Token amount is more than available");
// Mint TMV tokens to the Box creator
IToken(settings.tmvAddress()).mint(msg.sender, _tokensToWithdraw);
}
// The id of the new Box
uint256 _id = boxes.push(Box(msg.value, _tokensToWithdraw)).sub(1);
// Increase global Ether counter
globalETH = globalETH.add(msg.value);
// Mint TBX token to the Box creator
_mint(msg.sender, _id);
// Fire the event
emit Created(_id, msg.sender, msg.value, _tokensToWithdraw);
// return the new Box's ID
return _id;
}
/// @dev Allows the owner or approved user of the Box to close one by burning the
/// required number of tokens and return the Box's collateral.
/// @param _id A Box ID to close.
function close(uint256 _id) external onlyApprovedOrOwner(_id) {
// Address of the owner of the Box
address _owner = _tokenOwner[_id];
// Burn needed number of tokens
uint256 _tokensNeed = boxes[_id].tmvReleased;
_burnTMV(msg.sender, _tokensNeed);
// Grab a reference to the Box's collateral in storage
uint256 _collateral = boxes[_id].collateral;
// burn Box token
_burn(_owner, _id);
// Removes Box
delete boxes[_id];
// Send the Box's collateral to the person who made closing happen
msg.sender.transfer(_collateral);
// Decrease global Ether counter
globalETH = globalETH.sub(_collateral);
// Fire the event
emit Closed(_id, _owner, msg.sender);
}
/// @notice This allows you not to be tied to the current ETH/USD rate.
/// @dev Allows the user to capitalize a Box with the maximum current amount.
/// @param _id A Box ID to capitalize.
function capitalizeMax(uint256 _id) external {
capitalize(_id, maxCapAmount(_id));
}
/// @dev Allows the user to capitalize a Box with specified number of tokens.
/// @param _id A Box ID to capitalize.
/// @param _tmv Specified number of tokens to capitalize.
function capitalize(uint256 _id, uint256 _tmv) public validTx {
// The maximum number of tokens for which Box can be capitalized
uint256 _maxCapAmount = maxCapAmount(_id);
// Check the number of tokens
require(_tmv <= _maxCapAmount && _tmv >= 10 ** 17, "Tokens amount out of range");
// Decrease Box TMV withdrawn counter
boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_tmv);
// Calculate the Ether equivalent of tokens according to the logic
// where 1 TMV is equal to 1 USD
uint256 _equivalentETH = _tmv.mul(precision).div(rate());
// Calculate system fee
uint256 _fee = _tmv.mul(settings.sysFee()).div(rate());
// Calculate user bonus
uint256 _userReward = _tmv.mul(settings.userFee()).div(rate());
// Decrease Box's collateral amount
boxes[_id].collateral = boxes[_id].collateral.sub(_fee.add(_userReward).add(_equivalentETH));
// Decrease global Ether counter
globalETH = globalETH.sub(_fee.add(_userReward).add(_equivalentETH));
// burn Box token
_burnTMV(msg.sender, _tmv);
// Send the Ether equivalent & user benefit to the person who made capitalization happen.
msg.sender.transfer(_equivalentETH.add(_userReward));
// Fire the event
emit Capitalized(_id, ownerOf(_id), msg.sender, _tmv, _equivalentETH.add(_userReward).add(_fee), _equivalentETH.add(_userReward));
}
/// @notice This allows you not to be tied to the current ETH/USD rate.
/// @dev Allows an owner or approved user of the Box to withdraw maximum amount
/// of Ether from the Box.
/// @param _id A Box ID.
function withdrawEthMax(uint256 _id) external {
withdrawEth(_id, withdrawableEth(_id));
}
/// @dev Allows an owner or approved user of the Box to withdraw specified amount
/// of Ether from the Box.
/// @param _id A Box ID.
/// @param _amount The number of Ether to withdraw.
function withdrawEth(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx {
require(_amount > 0, "Withdrawing zero");
require(_amount <= withdrawableEth(_id), "You can't withdraw so much");
// Decrease Box's collateral amount
boxes[_id].collateral = boxes[_id].collateral.sub(_amount);
// Decrease global Ether counter
globalETH = globalETH.sub(_amount);
// Send the Ether to the person who made capitalization happen
msg.sender.transfer(_amount);
// Fire the event
emit EthWithdrawn(_id, _amount, msg.sender);
}
/// @notice This allows you not to be tied to the current ETH/USD rate.
/// @dev Allows an owner or approved user of the Box to withdraw maximum number
/// of TMV tokens from the Box.
/// @param _id A Box ID.
function withdrawTmvMax(uint256 _id) external onlyApprovedOrOwner(_id) {
withdrawTmv(_id, boxWithdrawableTmv(_id));
}
/// @dev Allows an owner or approved user of the Box to withdraw specified number
/// of TMV tokens from the Box.
/// @param _id A Box ID.
/// @param _amount The number of tokens to withdraw.
function withdrawTmv(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx {
require(_amount > 0, "Withdrawing zero");
// Check the number of tokens
require(_amount <= boxWithdrawableTmv(_id), "You can't withdraw so much");
// Increase Box TMV withdrawn counter
boxes[_id].tmvReleased = boxes[_id].tmvReleased.add(_amount);
// Mints tokens to the person who made withdrawing
IToken(settings.tmvAddress()).mint(msg.sender, _amount);
// Fire the event
emit TmvWithdrawn(_id, _amount, msg.sender);
}
/// @dev Allows anyone to add Ether to a Box.
/// @param _id A Box ID.
function addEth(uint256 _id) external payable onlyExists(_id) {
require(msg.value > 0, "Don't add 0");
// Increase Box collateral
boxes[_id].collateral = boxes[_id].collateral.add(msg.value);
// Increase global Ether counter
globalETH = globalETH.add(msg.value);
// Fire the event
emit EthAdded(_id, msg.value, msg.sender);
}
/// @dev Allows anyone to add TMV to a Box.
/// @param _id A Box ID.
/// @param _amount The number of tokens to add.
function addTmv(uint256 _id, uint256 _amount) external onlyExists(_id) {
require(_amount > 0, "Don't add 0");
// Check the number of tokens
require(_amount <= boxes[_id].tmvReleased, "Too much tokens");
// Removes added tokens from the collateralization
_burnTMV(msg.sender, _amount);
boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_amount);
// Fire the event
emit TmvAdded(_id, _amount, msg.sender);
}
/// @dev Allows anyone to close Box with collateral amount smaller than 3 USD.
/// The person who made closing happen will benefit like capitalization.
/// @param _id A Box ID.
function closeDust(uint256 _id) external onlyExists(_id) validTx {
// Check collateral percent of the Box
require(collateralPercent(_id) >= settings.minStability(), "This Box isn't collapsable");
// Check collateral amount of the Box
require(boxes[_id].collateral.mul(rate()) < precision.mul(3).mul(10 ** 18), "It's only possible to collapse dust");
// Burn needed TMV amount to close
uint256 _tmvReleased = boxes[_id].tmvReleased;
_burnTMV(msg.sender, _tmvReleased);
uint256 _collateral = boxes[_id].collateral;
// Calculate the Ether equivalent of tokens according to the logic
// where 1 TMV is equal to 1 USD
uint256 _eth = _tmvReleased.mul(precision).div(rate());
// Calculate user bonus
uint256 _userReward = _tmvReleased.mul(settings.userFee()).div(rate());
// The owner of the Box
address _owner = ownerOf(_id);
// Remove a Box
delete boxes[_id];
// Burn Box token
_burn(_owner, _id);
// Send the Ether equivalent & user benefit to the person who made closing happen
msg.sender.transfer(_eth.add(_userReward));
// Decrease global Ether counter
globalETH = globalETH.sub(_collateral);
// Fire the event
emit Closed(_id, _owner, msg.sender);
}
/// @dev Burns specified number of TMV tokens.
function _burnTMV(address _from, uint256 _amount) internal {
if (_amount > 0) {
require(IToken(settings.tmvAddress()).balanceOf(_from) >= _amount, "You don't have enough tokens");
IToken(settings.tmvAddress()).burnLogic(_from, _amount);
}
}
/// @dev Returns current oracle ETH/USD price with precision.
function rate() public view returns(uint256) {
return IOracle(settings.oracleAddress()).ethUsdPrice();
}
/// @dev Given a Box ID, returns a number of tokens that can be withdrawn.
function boxWithdrawableTmv(uint256 _id) public view onlyExists(_id) returns(uint256) {
Box memory box = boxes[_id];
// Number of tokens that can be withdrawn for Box's collateral
uint256 _amount = withdrawableTmv(box.collateral);
if (box.tmvReleased >= _amount) {
return 0;
}
// Return withdrawable rest
return _amount.sub(box.tmvReleased);
}
/// @dev Given a Box ID, returns an amount of Ether that can be withdrawn.
function withdrawableEth(uint256 _id) public view onlyExists(_id) returns(uint256) {
// Amount of Ether that is not used in collateralization
uint256 _avlbl = _freeEth(_id);
// Return available Ether to withdraw
if (_avlbl == 0) {
return 0;
}
uint256 _rest = boxes[_id].collateral.sub(_avlbl);
if (_rest < settings.minDeposit()) {
return boxes[_id].collateral.sub(settings.minDeposit());
}
else return _avlbl;
}
/// @dev Given a Box ID, returns amount of ETH that is not used in collateralization.
function _freeEth(uint256 _id) internal view returns(uint256) {
// Grab a reference to the Box
Box memory box = boxes[_id];
// When there are no tokens withdrawn
if (box.tmvReleased == 0) {
return box.collateral;
}
// The amount of Ether that can be safely withdrawn from the system
uint256 _maxGlobal = globalWithdrawableEth();
uint256 _globalAvailable;
if (_maxGlobal > 0) {
// The amount of Ether backing the tokens when the system is overcapitalized
uint256 _need = overCapFrozenEth(box.tmvReleased);
if (box.collateral > _need) {
// Free Ether amount when the system is overcapitalized
uint256 _free = box.collateral.sub(_need);
if (_free > _maxGlobal) {
// Store available amount when Box available Ether amount
// is more than global available
_globalAvailable = _maxGlobal;
}
// Return available amount of Ether to withdraw when the Box withdrawable
// amount of Ether is smaller than global withdrawable amount of Ether
else return _free;
}
}
// The amount of Ether backing the tokens by default
uint256 _frozen = defaultFrozenEth(box.tmvReleased);
if (box.collateral > _frozen) {
// Define the biggest number and return available Ether amount
uint256 _localAvailable = box.collateral.sub(_frozen);
return (_localAvailable > _globalAvailable) ? _localAvailable : _globalAvailable;
} else {
// Return available Ether amount
return _globalAvailable;
}
}
/// @dev Given a Box ID, returns collateral percent.
function collateralPercent(uint256 _id) public view onlyExists(_id) returns(uint256) {
Box memory box = boxes[_id];
if (box.tmvReleased == 0) {
return 10**27; //some unreachable number
}
uint256 _ethCollateral = box.collateral;
// division by 100 is not necessary because to get the percent you need to multiply by 100
return _ethCollateral.mul(rate()).div(box.tmvReleased);
}
/// @dev Checks if a given address currently has approval for a particular Box.
/// @param _spender the address we are confirming Box is approved for.
/// @param _tokenId Box ID.
function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool) {
return _isApprovedOrOwner(_spender, _tokenId);
}
/// @dev Returns the global collateralization percent.
function globalCollateralization() public view returns (uint256) {
uint256 _supply = IToken(settings.tmvAddress()).totalSupply();
if (_supply == 0) {
return settings.globalTargetCollateralization();
}
return globalETH.mul(rate()).div(_supply);
}
/// @dev Returns the number of tokens that can be safely withdrawn from the system.
function globalWithdrawableTmv(uint256 _value) public view returns (uint256) {
uint256 _supply = IToken(settings.tmvAddress()).totalSupply();
if (globalCollateralization() <= settings.globalTargetCollateralization()) {
return 0;
}
uint256 _totalBackedTmv = defaultWithdrawableTmv(globalETH.add(_value));
return _totalBackedTmv.sub(_supply);
}
/// @dev Returns Ether amount that can be safely withdrawn from the system.
function globalWithdrawableEth() public view returns (uint256) {
uint256 _supply = IToken(settings.tmvAddress()).totalSupply();
if (globalCollateralization() <= settings.globalTargetCollateralization()) {
return 0;
}
uint256 _need = defaultFrozenEth(_supply);
return globalETH.sub(_need);
}
/// @dev Returns the number of tokens that can be withdrawn
/// for the specified collateral amount by default.
function defaultWithdrawableTmv(uint256 _collateral) public view returns (uint256) {
uint256 _num = _collateral.mul(rate());
uint256 _div = settings.globalTargetCollateralization();
return _num.div(_div);
}
/// @dev Returns the number of tokens that can be withdrawn
/// for the specified collateral amount when the system is overcapitalized.
function overCapWithdrawableTmv(uint256 _collateral) public view returns (uint256) {
uint256 _num = _collateral.mul(rate());
uint256 _div = settings.ratio();
return _num.div(_div);
}
/// @dev Returns Ether amount backing the specified number of tokens by default.
function defaultFrozenEth(uint256 _supply) public view returns (uint256) {
return _supply.mul(settings.globalTargetCollateralization()).div(rate());
}
/// @dev Returns Ether amount backing the specified number of tokens
/// when the system is overcapitalized.
function overCapFrozenEth(uint256 _supply) public view returns (uint256) {
return _supply.mul(settings.ratio()).div(rate());
}
/// @dev Returns the number of TMV that can capitalize the specified Box.
function maxCapAmount(uint256 _id) public view onlyExists(_id) returns (uint256) {
uint256 _colP = collateralPercent(_id);
require(_colP >= settings.minStability() && _colP < settings.maxStability(), "It's only possible to capitalize toxic Boxes");
Box memory box = boxes[_id];
uint256 _num = box.tmvReleased.mul(settings.ratio()).sub(box.collateral.mul(rate()));
uint256 _div = settings.ratio().sub(settings.minStability());
return _num.div(_div);
}
/// @dev Returns the number of tokens that can be actually withdrawn
/// for the specified collateral.
function withdrawableTmv(uint256 _collateral) public view returns(uint256) {
uint256 _amount = overCapWithdrawableTmv(_collateral);
uint256 _maxGlobal = globalWithdrawableTmv(0);
if (_amount > _maxGlobal) {
_amount = _maxGlobal;
}
uint256 _local = defaultWithdrawableTmv(_collateral);
if (_amount < _local) {
_amount = _local;
}
return _amount;
}
/// @dev Returns the collateral percentage for which tokens can be withdrawn
/// for the specified collateral.
function withdrawPercent(uint256 _collateral) external view returns(uint256) {
uint256 _amount = overCapWithdrawableTmv(_collateral);
uint256 _maxGlobal = globalWithdrawableTmv(_collateral);
if (_amount > _maxGlobal) {
_amount = _maxGlobal;
}
uint256 _local = defaultWithdrawableTmv(_collateral);
if (_amount < _local) {
_amount = _local;
}
return _collateral.mul(rate()).div(_amount);
}
}
pragma solidity 0.4.25;
import "./ERC721.sol";
import "./ERC721Enumerable.sol";
import "./ERC721Metadata.sol";
/**
* @title TBoxClassic 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 TBoxToken is ERC721, ERC721Enumerable, ERC721Metadata {
constructor (string memory name, string memory symbol) ERC721Metadata(name, symbol) public {}
}
pragma solidity 0.4.25;
/**
* Utility library of inline functions on addresses
*/
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address of the account to check
* @return whether the target address is a contract
*/
function isContract(address account) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
}
pragma solidity 0.4.25;
import "./IERC165.sol";
/**
* @title ERC165
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract ERC165 is IERC165 {
bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor () internal {
_registerInterface(_InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff);
_supportedInterfaces[interfaceId] = true;
}
}
pragma solidity 0.4.25;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./SafeMath.sol";
import "./Address.sol";
import "./ERC165.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) internal _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_InterfaceId_ERC721);
}
/**
* @dev Gets the balance of the specified address
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0));
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 Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = ownerOf(tokenId);
require(to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId));
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != msg.sender);
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public {
require(_isApprovedOrOwner(msg.sender, tokenId));
require(to != address(0));
_clearApproval(from, tokenId);
_removeTokenFrom(from, tokenId);
_addTokenTo(to, tokenId);
emit Transfer(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
// solium-disable-next-line arg-overflow
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
transferFrom(from, to, tokenId);
// solium-disable-next-line arg-overflow
require(_checkOnERC721Received(from, to, tokenId, _data));
}
/**
* @dev Returns whether the specified token exists
* @param tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
address owner = ownerOf(tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0));
_addTokenTo(to, tokenId);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
_clearApproval(owner, tokenId);
_removeTokenFrom(owner, tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to add a token ID to the list of a given address
* Note that this function is left internal to make ERC721Enumerable possible, but is not
* intended to be called by custom derived contracts: in particular, it emits no Transfer event.
* @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
* Note that this function is left internal to make ERC721Enumerable possible, but is not
* intended to be called by custom derived contracts: in particular, it emits no Transfer event,
* and doesn't clear approvals.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFrom(address from, uint256 tokenId) internal {
require(ownerOf(tokenId) == from);
_ownedTokensCount[from] = _ownedTokensCount[from].sub(1);
_tokenOwner[tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* The call is not executed if the target address is not a contract
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) {
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
* @param owner owner of the token
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(address owner, uint256 tokenId) private {
require(ownerOf(tokenId) == owner);
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
pragma solidity 0.4.25;
import "./IERC721Enumerable.sol";
import "./ERC721.sol";
import "./ERC165.sol";
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
bytes4 private constant _InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor () public {
// register the supported interface to conform to ERC721 via ERC165
_registerInterface(_InterfaceId_ERC721Enumerable);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
require(index < balanceOf(owner));
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply());
return _allTokens[index];
}
/**
* @dev Internal function to add a token ID to the list of a given address
* This function is internal due to language limitations, see the note in ERC721.sol.
* It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event.
* @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
* This function is internal due to language limitations, see the note in ERC721.sol.
* It is not intended to be called by custom derived contracts: in particular, it emits no Transfer event,
* and doesn't clear approvals.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFrom(address from, uint256 tokenId) internal {
super._removeTokenFrom(from, tokenId);
// To prevent a gap in the array, we store the last token in the index of the token to delete, and
// then delete the last slot.
uint256 tokenIndex = _ownedTokensIndex[tokenId];
uint256 lastTokenIndex = _ownedTokens[from].length.sub(1);
uint256 lastToken = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastToken;
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
_ownedTokensIndex[tokenId] = 0;
_ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// 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;
}
}
pragma solidity 0.4.25;
import "./ERC721.sol";
import "./IERC721Metadata.sol";
import "./ERC165.sol";
contract ERC721Metadata is ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Metadata);
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId));
return _tokenURIs[tokenId];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(_exists(tokenId));
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
pragma solidity 0.4.25;
/**
* @title IERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface IERC165 {
/**
* @notice Query if a contract implements an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
pragma solidity 0.4.25;
import "./IERC165.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) public view returns (uint256 balance);
function ownerOf(uint256 tokenId) public view returns (address owner);
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 memory data) public;
}
pragma solidity 0.4.25;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId);
function tokenByIndex(uint256 index) public view returns (uint256);
}
pragma solidity 0.4.25;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
pragma solidity 0.4.25;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safeTransfer`. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4);
}
pragma solidity 0.4.25;
/// @title IOracle
/// @dev Interface for getting the data from the oracle contract.
interface IOracle {
function ethUsdPrice() external view returns(uint256);
}
pragma solidity 0.4.25;
/// @title ISettings
/// @dev Interface for getting the data from settings contract.
interface ISettings {
function oracleAddress() external view returns(address);
function minDeposit() external view returns(uint256);
function sysFee() external view returns(uint256);
function userFee() external view returns(uint256);
function ratio() external view returns(uint256);
function globalTargetCollateralization() external view returns(uint256);
function tmvAddress() external view returns(uint256);
function maxStability() external view returns(uint256);
function minStability() external view returns(uint256);
function gasPriceLimit() external view returns(uint256);
function isFeeManager(address account) external view returns (bool);
function tBoxManager() external view returns(address);
}
pragma solidity 0.4.25;
/// @title IToken
/// @dev Interface for interaction with the TMV token contract.
interface IToken {
function burnLogic(address from, uint256 value) external;
function approve(address spender, uint256 value) external;
function balanceOf(address who) external view returns (uint256);
function mint(address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 tokenId) external;
}
pragma solidity 0.4.25;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, 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, 'mul');
return c;
}
/**
* @dev Integer division of two numbers 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, 'div');
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 numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, 'sub');
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, 'add');
return c;
}
/**
* @dev Divides two numbers 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;
}
}
pragma solidity 0.4.25;
import "./TBoxToken.sol";
import "./ISettings.sol";
import "./IToken.sol";
import "./IOracle.sol";
/// @title TBoxManager
contract TBoxManager is TBoxToken {
// Total packed Ether
uint256 public globalETH;
// Precision using for USD and commission
uint256 public precision = 100000;
// The address of the system settings contract
ISettings public settings;
/// @dev An array containing the Boxes struct for all Boxes in existence. The ID
/// of each Box is actually an index into this array.
Box[] public boxes;
/// @dev The main Box struct. Every Box in TimviSystem is represented by a copy
/// of this structure.
struct Box {
// The collateral Ether amount in wei
uint256 collateral;
// The number of TMV withdrawn
uint256 tmvReleased;
}
/// @dev The Created event is fired whenever a new Box comes into existence. This includes
/// any time a Box is created through the create method.
event Created(uint256 indexed id, address owner, uint256 collateral, uint256 tmvReleased);
/// @dev The Closed event is fired whenever a Box is closed. Obviously, this includes
/// any time a Box is closed through the close method, but it is also called when
// a Box is closed through the closeDust method.
event Closed(uint256 indexed id, address indexed owner, address indexed closer);
/// @dev The Capitalized event is fired whenever a Box is capitalized.
event Capitalized(uint256 indexed id, address indexed owner, address indexed who, uint256 tmvAmount, uint256 totalEth, uint256 userEth);
/// @dev The EthWithdrawn event is fired whenever Ether is withdrawn from a Box
/// using withdrawEth method.
event EthWithdrawn(uint256 indexed id, uint256 value, address who);
/// @dev The TmvWithdrawn event is fired whenever TMV is withdrawn from a Box
/// using withdrawTmv method.
event TmvWithdrawn(uint256 indexed id, uint256 value, address who);
/// @dev The EthAdded event is fired whenever Ether is added to a Box
/// using addEth method.
event EthAdded(uint256 indexed id, uint256 value, address who);
/// @dev The TmvAdded event is fired whenever TMV is added to a Box
/// using addTmv method.
event TmvAdded(uint256 indexed id, uint256 value, address who);
/// @dev Defends against front-running attacks.
modifier validTx() {
require(tx.gasprice <= settings.gasPriceLimit(), "Gas price is greater than allowed");
_;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyAdmin() {
require(settings.isFeeManager(msg.sender), "You have no access");
_;
}
/// @dev Throws if Box with specified id does not exist.
modifier onlyExists(uint256 _id) {
require(_exists(_id), "Box does not exist");
_;
}
/// @dev Access modifier for token owner-only functionality.
modifier onlyApprovedOrOwner(uint256 _id) {
require(_isApprovedOrOwner(msg.sender, _id), "Box isn't your");
_;
}
/// @dev The constructor sets ERC721 token name and symbol.
/// @param _settings The address of the system settings contract.
constructor(address _settings) TBoxToken("TBoxToken", "TBX") public {
settings = ISettings(_settings);
}
/// @notice The funds are safe.
/// @dev Creates Box with max collateral percent.
function() external payable {
// Redirect to the create method with no tokens to withdraw
create(0);
}
/// @dev Withdraws system fee.
function withdrawFee(address _beneficiary) external onlyAdmin {
require(_beneficiary != address(0), "Zero address, be careful");
// Fee is the difference between the contract balance and
// amount of Ether used in the entire system collateralization
uint256 _fees = address(this).balance.sub(globalETH);
// Check that the fee is collected
require(_fees > 0, "There is no available fees");
// Transfer fee to provided address
_beneficiary.transfer(_fees);
}
/// @dev Checks possibility of the issue of the specified token amount
/// for provided Ether collateral and creates new Box
/// @param _tokensToWithdraw Number of tokens to withdraw
/// @return New Box ID.
function create(uint256 _tokensToWithdraw) public payable validTx returns (uint256) {
// Check that msg.value isn't smaller than minimum deposit
require(msg.value >= settings.minDeposit(), "Deposit is very small");
// Calculate collateralization when tokens are needed
if (_tokensToWithdraw > 0) {
// The number of tokens when collateralization is high
uint256 _tokenLimit = overCapWithdrawableTmv(msg.value);
// The number of tokens that can be safely withdrawn from the system
uint256 _maxGlobal = globalWithdrawableTmv(msg.value);
// Determine the higher number of tokens
if (_tokenLimit > _maxGlobal) {
_tokenLimit = _maxGlobal;
}
// The number of tokens that can be withdrawn anyway
uint256 _local = defaultWithdrawableTmv(msg.value);
// Determine the higher number of tokens
if (_tokenLimit < _local) {
_tokenLimit = _local;
}
// You can only withdraw available amount
require(_tokensToWithdraw <= _tokenLimit, "Token amount is more than available");
// Mint TMV tokens to the Box creator
IToken(settings.tmvAddress()).mint(msg.sender, _tokensToWithdraw);
}
// The id of the new Box
uint256 _id = boxes.push(Box(msg.value, _tokensToWithdraw)).sub(1);
// Increase global Ether counter
globalETH = globalETH.add(msg.value);
// Mint TBX token to the Box creator
_mint(msg.sender, _id);
// Fire the event
emit Created(_id, msg.sender, msg.value, _tokensToWithdraw);
// return the new Box's ID
return _id;
}
/// @dev Allows the owner or approved user of the Box to close one by burning the
/// required number of tokens and return the Box's collateral.
/// @param _id A Box ID to close.
function close(uint256 _id) external onlyApprovedOrOwner(_id) {
// Address of the owner of the Box
address _owner = _tokenOwner[_id];
// Burn needed number of tokens
uint256 _tokensNeed = boxes[_id].tmvReleased;
_burnTMV(msg.sender, _tokensNeed);
// Grab a reference to the Box's collateral in storage
uint256 _collateral = boxes[_id].collateral;
// burn Box token
_burn(_owner, _id);
// Removes Box
delete boxes[_id];
// Send the Box's collateral to the person who made closing happen
msg.sender.transfer(_collateral);
// Decrease global Ether counter
globalETH = globalETH.sub(_collateral);
// Fire the event
emit Closed(_id, _owner, msg.sender);
}
/// @notice This allows you not to be tied to the current ETH/USD rate.
/// @dev Allows the user to capitalize a Box with the maximum current amount.
/// @param _id A Box ID to capitalize.
function capitalizeMax(uint256 _id) external {
capitalize(_id, maxCapAmount(_id));
}
/// @dev Allows the user to capitalize a Box with specified number of tokens.
/// @param _id A Box ID to capitalize.
/// @param _tmv Specified number of tokens to capitalize.
function capitalize(uint256 _id, uint256 _tmv) public validTx {
// The maximum number of tokens for which Box can be capitalized
uint256 _maxCapAmount = maxCapAmount(_id);
// Check the number of tokens
require(_tmv <= _maxCapAmount && _tmv >= 10 ** 17, "Tokens amount out of range");
// Decrease Box TMV withdrawn counter
boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_tmv);
// Calculate the Ether equivalent of tokens according to the logic
// where 1 TMV is equal to 1 USD
uint256 _equivalentETH = _tmv.mul(precision).div(rate());
// Calculate system fee
uint256 _fee = _tmv.mul(settings.sysFee()).div(rate());
// Calculate user bonus
uint256 _userReward = _tmv.mul(settings.userFee()).div(rate());
// Decrease Box's collateral amount
boxes[_id].collateral = boxes[_id].collateral.sub(_fee.add(_userReward).add(_equivalentETH));
// Decrease global Ether counter
globalETH = globalETH.sub(_fee.add(_userReward).add(_equivalentETH));
// burn Box token
_burnTMV(msg.sender, _tmv);
// Send the Ether equivalent & user benefit to the person who made capitalization happen.
msg.sender.transfer(_equivalentETH.add(_userReward));
// Fire the event
emit Capitalized(_id, ownerOf(_id), msg.sender, _tmv, _equivalentETH.add(_userReward).add(_fee), _equivalentETH.add(_userReward));
}
/// @notice This allows you not to be tied to the current ETH/USD rate.
/// @dev Allows an owner or approved user of the Box to withdraw maximum amount
/// of Ether from the Box.
/// @param _id A Box ID.
function withdrawEthMax(uint256 _id) external {
withdrawEth(_id, withdrawableEth(_id));
}
/// @dev Allows an owner or approved user of the Box to withdraw specified amount
/// of Ether from the Box.
/// @param _id A Box ID.
/// @param _amount The number of Ether to withdraw.
function withdrawEth(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx {
require(_amount > 0, "Withdrawing zero");
require(_amount <= withdrawableEth(_id), "You can't withdraw so much");
// Decrease Box's collateral amount
boxes[_id].collateral = boxes[_id].collateral.sub(_amount);
// Decrease global Ether counter
globalETH = globalETH.sub(_amount);
// Send the Ether to the person who made capitalization happen
msg.sender.transfer(_amount);
// Fire the event
emit EthWithdrawn(_id, _amount, msg.sender);
}
/// @notice This allows you not to be tied to the current ETH/USD rate.
/// @dev Allows an owner or approved user of the Box to withdraw maximum number
/// of TMV tokens from the Box.
/// @param _id A Box ID.
function withdrawTmvMax(uint256 _id) external onlyApprovedOrOwner(_id) {
withdrawTmv(_id, boxWithdrawableTmv(_id));
}
/// @dev Allows an owner or approved user of the Box to withdraw specified number
/// of TMV tokens from the Box.
/// @param _id A Box ID.
/// @param _amount The number of tokens to withdraw.
function withdrawTmv(uint256 _id, uint256 _amount) public onlyApprovedOrOwner(_id) validTx {
require(_amount > 0, "Withdrawing zero");
// Check the number of tokens
require(_amount <= boxWithdrawableTmv(_id), "You can't withdraw so much");
// Increase Box TMV withdrawn counter
boxes[_id].tmvReleased = boxes[_id].tmvReleased.add(_amount);
// Mints tokens to the person who made withdrawing
IToken(settings.tmvAddress()).mint(msg.sender, _amount);
// Fire the event
emit TmvWithdrawn(_id, _amount, msg.sender);
}
/// @dev Allows anyone to add Ether to a Box.
/// @param _id A Box ID.
function addEth(uint256 _id) external payable onlyExists(_id) {
require(msg.value > 0, "Don't add 0");
// Increase Box collateral
boxes[_id].collateral = boxes[_id].collateral.add(msg.value);
// Increase global Ether counter
globalETH = globalETH.add(msg.value);
// Fire the event
emit EthAdded(_id, msg.value, msg.sender);
}
/// @dev Allows anyone to add TMV to a Box.
/// @param _id A Box ID.
/// @param _amount The number of tokens to add.
function addTmv(uint256 _id, uint256 _amount) external onlyExists(_id) {
require(_amount > 0, "Don't add 0");
// Check the number of tokens
require(_amount <= boxes[_id].tmvReleased, "Too much tokens");
// Removes added tokens from the collateralization
_burnTMV(msg.sender, _amount);
boxes[_id].tmvReleased = boxes[_id].tmvReleased.sub(_amount);
// Fire the event
emit TmvAdded(_id, _amount, msg.sender);
}
/// @dev Allows anyone to close Box with collateral amount smaller than 3 USD.
/// The person who made closing happen will benefit like capitalization.
/// @param _id A Box ID.
function closeDust(uint256 _id) external onlyExists(_id) validTx {
// Check collateral percent of the Box
require(collateralPercent(_id) >= settings.minStability(), "This Box isn't collapsable");
// Check collateral amount of the Box
require(boxes[_id].collateral.mul(rate()) < precision.mul(3).mul(10 ** 18), "It's only possible to collapse dust");
// Burn needed TMV amount to close
uint256 _tmvReleased = boxes[_id].tmvReleased;
_burnTMV(msg.sender, _tmvReleased);
uint256 _collateral = boxes[_id].collateral;
// Calculate the Ether equivalent of tokens according to the logic
// where 1 TMV is equal to 1 USD
uint256 _eth = _tmvReleased.mul(precision).div(rate());
// Calculate user bonus
uint256 _userReward = _tmvReleased.mul(settings.userFee()).div(rate());
// The owner of the Box
address _owner = ownerOf(_id);
// Remove a Box
delete boxes[_id];
// Burn Box token
_burn(_owner, _id);
// Send the Ether equivalent & user benefit to the person who made closing happen
msg.sender.transfer(_eth.add(_userReward));
// Decrease global Ether counter
globalETH = globalETH.sub(_collateral);
// Fire the event
emit Closed(_id, _owner, msg.sender);
}
/// @dev Burns specified number of TMV tokens.
function _burnTMV(address _from, uint256 _amount) internal {
if (_amount > 0) {
require(IToken(settings.tmvAddress()).balanceOf(_from) >= _amount, "You don't have enough tokens");
IToken(settings.tmvAddress()).burnLogic(_from, _amount);
}
}
/// @dev Returns current oracle ETH/USD price with precision.
function rate() public view returns(uint256) {
return IOracle(settings.oracleAddress()).ethUsdPrice();
}
/// @dev Given a Box ID, returns a number of tokens that can be withdrawn.
function boxWithdrawableTmv(uint256 _id) public view onlyExists(_id) returns(uint256) {
Box memory box = boxes[_id];
// Number of tokens that can be withdrawn for Box's collateral
uint256 _amount = withdrawableTmv(box.collateral);
if (box.tmvReleased >= _amount) {
return 0;
}
// Return withdrawable rest
return _amount.sub(box.tmvReleased);
}
/// @dev Given a Box ID, returns an amount of Ether that can be withdrawn.
function withdrawableEth(uint256 _id) public view onlyExists(_id) returns(uint256) {
// Amount of Ether that is not used in collateralization
uint256 _avlbl = _freeEth(_id);
// Return available Ether to withdraw
if (_avlbl == 0) {
return 0;
}
uint256 _rest = boxes[_id].collateral.sub(_avlbl);
if (_rest < settings.minDeposit()) {
return boxes[_id].collateral.sub(settings.minDeposit());
}
else return _avlbl;
}
/// @dev Given a Box ID, returns amount of ETH that is not used in collateralization.
function _freeEth(uint256 _id) internal view returns(uint256) {
// Grab a reference to the Box
Box memory box = boxes[_id];
// When there are no tokens withdrawn
if (box.tmvReleased == 0) {
return box.collateral;
}
// The amount of Ether that can be safely withdrawn from the system
uint256 _maxGlobal = globalWithdrawableEth();
uint256 _globalAvailable;
if (_maxGlobal > 0) {
// The amount of Ether backing the tokens when the system is overcapitalized
uint256 _need = overCapFrozenEth(box.tmvReleased);
if (box.collateral > _need) {
// Free Ether amount when the system is overcapitalized
uint256 _free = box.collateral.sub(_need);
if (_free > _maxGlobal) {
// Store available amount when Box available Ether amount
// is more than global available
_globalAvailable = _maxGlobal;
}
// Return available amount of Ether to withdraw when the Box withdrawable
// amount of Ether is smaller than global withdrawable amount of Ether
else return _free;
}
}
// The amount of Ether backing the tokens by default
uint256 _frozen = defaultFrozenEth(box.tmvReleased);
if (box.collateral > _frozen) {
// Define the biggest number and return available Ether amount
uint256 _localAvailable = box.collateral.sub(_frozen);
return (_localAvailable > _globalAvailable) ? _localAvailable : _globalAvailable;
} else {
// Return available Ether amount
return _globalAvailable;
}
}
/// @dev Given a Box ID, returns collateral percent.
function collateralPercent(uint256 _id) public view onlyExists(_id) returns(uint256) {
Box memory box = boxes[_id];
if (box.tmvReleased == 0) {
return 10**27; //some unreachable number
}
uint256 _ethCollateral = box.collateral;
// division by 100 is not necessary because to get the percent you need to multiply by 100
return _ethCollateral.mul(rate()).div(box.tmvReleased);
}
/// @dev Checks if a given address currently has approval for a particular Box.
/// @param _spender the address we are confirming Box is approved for.
/// @param _tokenId Box ID.
function isApprovedOrOwner(address _spender, uint256 _tokenId) external view returns (bool) {
return _isApprovedOrOwner(_spender, _tokenId);
}
/// @dev Returns the global collateralization percent.
function globalCollateralization() public view returns (uint256) {
uint256 _supply = IToken(settings.tmvAddress()).totalSupply();
if (_supply == 0) {
return settings.globalTargetCollateralization();
}
return globalETH.mul(rate()).div(_supply);
}
/// @dev Returns the number of tokens that can be safely withdrawn from the system.
function globalWithdrawableTmv(uint256 _value) public view returns (uint256) {
uint256 _supply = IToken(settings.tmvAddress()).totalSupply();
if (globalCollateralization() <= settings.globalTargetCollateralization()) {
return 0;
}
uint256 _totalBackedTmv = defaultWithdrawableTmv(globalETH.add(_value));
return _totalBackedTmv.sub(_supply);
}
/// @dev Returns Ether amount that can be safely withdrawn from the system.
function globalWithdrawableEth() public view returns (uint256) {
uint256 _supply = IToken(settings.tmvAddress()).totalSupply();
if (globalCollateralization() <= settings.globalTargetCollateralization()) {
return 0;
}
uint256 _need = defaultFrozenEth(_supply);
return globalETH.sub(_need);
}
/// @dev Returns the number of tokens that can be withdrawn
/// for the specified collateral amount by default.
function defaultWithdrawableTmv(uint256 _collateral) public view returns (uint256) {
uint256 _num = _collateral.mul(rate());
uint256 _div = settings.globalTargetCollateralization();
return _num.div(_div);
}
/// @dev Returns the number of tokens that can be withdrawn
/// for the specified collateral amount when the system is overcapitalized.
function overCapWithdrawableTmv(uint256 _collateral) public view returns (uint256) {
uint256 _num = _collateral.mul(rate());
uint256 _div = settings.ratio();
return _num.div(_div);
}
/// @dev Returns Ether amount backing the specified number of tokens by default.
function defaultFrozenEth(uint256 _supply) public view returns (uint256) {
return _supply.mul(settings.globalTargetCollateralization()).div(rate());
}
/// @dev Returns Ether amount backing the specified number of tokens
/// when the system is overcapitalized.
function overCapFrozenEth(uint256 _supply) public view returns (uint256) {
return _supply.mul(settings.ratio()).div(rate());
}
/// @dev Returns the number of TMV that can capitalize the specified Box.
function maxCapAmount(uint256 _id) public view onlyExists(_id) returns (uint256) {
uint256 _colP = collateralPercent(_id);
require(_colP >= settings.minStability() && _colP < settings.maxStability(), "It's only possible to capitalize toxic Boxes");
Box memory box = boxes[_id];
uint256 _num = box.tmvReleased.mul(settings.ratio()).sub(box.collateral.mul(rate()));
uint256 _div = settings.ratio().sub(settings.minStability());
return _num.div(_div);
}
/// @dev Returns the number of tokens that can be actually withdrawn
/// for the specified collateral.
function withdrawableTmv(uint256 _collateral) public view returns(uint256) {
uint256 _amount = overCapWithdrawableTmv(_collateral);
uint256 _maxGlobal = globalWithdrawableTmv(0);
if (_amount > _maxGlobal) {
_amount = _maxGlobal;
}
uint256 _local = defaultWithdrawableTmv(_collateral);
if (_amount < _local) {
_amount = _local;
}
return _amount;
}
/// @dev Returns the collateral percentage for which tokens can be withdrawn
/// for the specified collateral.
function withdrawPercent(uint256 _collateral) external view returns(uint256) {
uint256 _amount = overCapWithdrawableTmv(_collateral);
uint256 _maxGlobal = globalWithdrawableTmv(_collateral);
if (_amount > _maxGlobal) {
_amount = _maxGlobal;
}
uint256 _local = defaultWithdrawableTmv(_collateral);
if (_amount < _local) {
_amount = _local;
}
return _collateral.mul(rate()).div(_amount);
}
}
pragma solidity 0.4.25;
import "./ERC721.sol";
import "./ERC721Enumerable.sol";
import "./ERC721Metadata.sol";
/**
* @title TBoxClassic 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 TBoxToken is ERC721, ERC721Enumerable, ERC721Metadata {
constructor (string memory name, string memory symbol) ERC721Metadata(name, symbol) public {}
}
| @dev Returns the number of tokens that can be safely withdrawn from the system. | function globalWithdrawableTmv(uint256 _value) public view returns (uint256) {
uint256 _supply = IToken(settings.tmvAddress()).totalSupply();
if (globalCollateralization() <= settings.globalTargetCollateralization()) {
return 0;
}
uint256 _totalBackedTmv = defaultWithdrawableTmv(globalETH.add(_value));
return _totalBackedTmv.sub(_supply);
}
| 911,890 | [
1,
1356,
326,
1300,
434,
2430,
716,
848,
506,
15303,
598,
9446,
82,
628,
326,
2619,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2552,
1190,
9446,
429,
56,
17509,
12,
11890,
5034,
389,
1132,
13,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
389,
2859,
1283,
273,
467,
1345,
12,
4272,
18,
16925,
90,
1887,
1435,
2934,
4963,
3088,
1283,
5621,
203,
3639,
309,
261,
6347,
13535,
2045,
287,
1588,
1435,
1648,
1947,
18,
6347,
2326,
13535,
2045,
287,
1588,
10756,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
389,
4963,
2711,
329,
56,
17509,
273,
805,
1190,
9446,
429,
56,
17509,
12,
6347,
1584,
44,
18,
1289,
24899,
1132,
10019,
203,
3639,
327,
389,
4963,
2711,
329,
56,
17509,
18,
1717,
24899,
2859,
1283,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.21;
contract Owned {
/// 'owner' is the only address that can call a function with
/// this modifier
address public owner;
address internal newOwner;
///@notice The constructor assigns the message sender to be 'owner'
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
event updateOwner(address _oldOwner, address _newOwner);
///change the owner
function changeOwner(address _newOwner) public onlyOwner returns(bool) {
require(owner != _newOwner);
newOwner = _newOwner;
return true;
}
/// accept the ownership
function acceptNewOwner() public returns(bool) {
require(msg.sender == newOwner);
emit updateOwner(owner, newOwner);
owner = newOwner;
return true;
}
}
// Safe maths, borrowed from OpenZeppelin
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20Token {
/* This is a slight change to the ERC20 base standard.
function totalSupply() constant returns (uint256 supply);
is replaced with:
uint256 public totalSupply;
This automatically creates a getter function for the totalSupply.
This is moved to the base contract since public getter functions are not
currently recognised as an implementation of the matching abstract
function by the compiler.
*/
/// total amount of tokens
uint256 public totalSupply;
/// user tokens
mapping (address => uint256) public balances;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) constant public returns (uint256 balance);
/// @notice send `_value` token to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return Whether the approval was successful or not
function approve(address _spender, uint256 _value) public returns (bool success);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender) constant public returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
contract Controlled is Owned, ERC20Token {
using SafeMath for uint;
uint256 public releaseStartTime;
uint256 oneMonth = 3600 * 24 * 30;
// Flag that determines if the token is transferable or not
bool public emergencyStop = false;
struct userToken {
uint256 UST;
uint256 addrLockType;
}
mapping (address => userToken) public userReleaseToken;
modifier canTransfer {
require(emergencyStop == false);
_;
}
modifier releaseTokenValid(address _user, uint256 _time, uint256 _value) {
uint256 _lockTypeIndex = userReleaseToken[_user].addrLockType;
if(_lockTypeIndex != 0) {
require (balances[_user].sub(_value) >= userReleaseToken[_user].UST.sub(calcReleaseToken(_user, _time, _lockTypeIndex)));
}
_;
}
function canTransferUST(bool _bool) public onlyOwner{
emergencyStop = _bool;
}
/// @notice get `_user` transferable token amount
/// @param _user The user's address
/// @param _time The present time
/// @param _lockTypeIndex The user's investment lock type
/// @return Return the amount of user's transferable token
function calcReleaseToken(address _user, uint256 _time, uint256 _lockTypeIndex) internal view returns (uint256) {
uint256 _timeDifference = _time.sub(releaseStartTime);
uint256 _whichPeriod = getPeriod(_lockTypeIndex, _timeDifference);
if(_lockTypeIndex == 1) {
return (percent(userReleaseToken[_user].UST, 25) + percent(userReleaseToken[_user].UST, _whichPeriod.mul(25)));
}
if(_lockTypeIndex == 2) {
return (percent(userReleaseToken[_user].UST, 25) + percent(userReleaseToken[_user].UST, _whichPeriod.mul(25)));
}
if(_lockTypeIndex == 3) {
return (percent(userReleaseToken[_user].UST, 10) + percent(userReleaseToken[_user].UST, _whichPeriod.mul(15)));
}
revert();
}
/// @notice get time period for the given '_lockTypeIndex'
/// @param _lockTypeIndex The user's investment locktype index
/// @param _timeDifference The passed time since releaseStartTime to now
/// @return Return the time period
function getPeriod(uint256 _lockTypeIndex, uint256 _timeDifference) internal view returns (uint256) {
if(_lockTypeIndex == 1) { //The lock for the usechain coreTeamSupply
uint256 _period1 = (_timeDifference.div(oneMonth)).div(12);
if(_period1 >= 3){
_period1 = 3;
}
return _period1;
}
if(_lockTypeIndex == 2) { //The lock for medium investment
uint256 _period2 = _timeDifference.div(oneMonth);
if(_period2 >= 3){
_period2 = 3;
}
return _period2;
}
if(_lockTypeIndex == 3) { //The lock for massive investment
uint256 _period3 = _timeDifference.div(oneMonth);
if(_period3 >= 6){
_period3 = 6;
}
return _period3;
}
revert();
}
function percent(uint _token, uint _percentage) internal pure returns (uint) {
return _percentage.mul(_token).div(100);
}
}
contract standardToken is ERC20Token, Controlled {
mapping (address => mapping (address => uint256)) public allowances;
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) constant public returns (uint256) {
return balances[_owner];
}
/// @notice Send `_value` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(
address _to,
uint256 _value)
public
canTransfer
releaseTokenValid(msg.sender, now, _value)
returns (bool)
{
require (balances[msg.sender] >= _value); // Throw if sender has insufficient balance
require (balances[_to] + _value >= balances[_to]); // Throw if owerflow detected
balances[msg.sender] -= _value; // Deduct senders balance
balances[_to] += _value; // Add recivers balance
emit Transfer(msg.sender, _to, _value); // Raise Transfer event
return true;
}
/// @notice `msg.sender` approves `_spender` to spend `_value` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _value) public returns (bool success) {
allowances[msg.sender][_spender] = _value; // Set allowance
emit Approval(msg.sender, _spender, _value); // Raise Approval event
return true;
}
/// @notice `msg.sender` approves `_spender` to send `_value` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _value The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
approve(_spender, _value); // Set approval to contract for _value
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) {
revert();
}
return true;
}
/// @notice Send `_value` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _value The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _value) public canTransfer releaseTokenValid(msg.sender, now, _value) returns (bool success) {
require (balances[_from] >= _value); // Throw if sender does not have enough balance
require (balances[_to] + _value >= balances[_to]); // Throw if overflow detected
require (_value <= allowances[_from][msg.sender]); // Throw if you do not have allowance
balances[_from] -= _value; // Deduct senders balance
balances[_to] += _value; // Add recipient balance
allowances[_from][msg.sender] -= _value; // Deduct allowance for this address
emit Transfer(_from, _to, _value); // Raise Transfer event
return true;
}
/// @dev This function makes it easy to read the `allowances[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed to spend
function allowance(address _owner, address _spender) constant public returns (uint256) {
return allowances[_owner][_spender];
}
}
contract UST is Owned, standardToken {
string constant public name = "UseChainToken";
string constant public symbol = "UST";
uint constant public decimals = 18;
uint256 public totalSupply = 0;
uint256 constant public topTotalSupply = 2 * 10**10 * 10**decimals;
uint public forSaleSupply = percent(topTotalSupply, 45);
uint public marketingPartnerSupply = percent(topTotalSupply, 5);
uint public coreTeamSupply = percent(topTotalSupply, 15);
uint public technicalCommunitySupply = percent(topTotalSupply, 15);
uint public communitySupply = percent(topTotalSupply, 20);
uint public softCap = percent(topTotalSupply, 30);
function () public {
revert();
}
/// @dev Owner can change the releaseStartTime when needs
/// @param _time The releaseStartTime, UTC timezone
function setRealseTime(uint256 _time) public onlyOwner {
releaseStartTime = _time;
}
/// @dev This owner allocate token for private sale
/// @param _owners The address of the account that owns the token
/// @param _values The amount of tokens
/// @param _addrLockType The locktype for different investment type
function allocateToken(address[] _owners, uint256[] _values, uint256[] _addrLockType) public onlyOwner {
require ((_owners.length == _values.length) && ( _values.length == _addrLockType.length));
for(uint i = 0; i < _owners.length ; i++){
uint256 value = _values[i] * 10 ** decimals;
totalSupply = totalSupply.add(value);
balances[_owners[i]] = balances[_owners[i]].add(value); // Set minted coins to target
emit Transfer(0x0, _owners[i], value);
userReleaseToken[_owners[i]].UST = userReleaseToken[_owners[i]].UST.add(value);
userReleaseToken[_owners[i]].addrLockType = _addrLockType[i];
}
}
/// @dev This owner allocate token for candy airdrop
/// @param _owners The address of the account that owns the token
/// @param _values The amount of tokens
function allocateCandyToken(address[] _owners, uint256[] _values) public onlyOwner {
for(uint i = 0; i < _owners.length ; i++){
uint256 value = _values[i] * 10 ** decimals;
totalSupply = totalSupply.add(value);
balances[_owners[i]] = balances[_owners[i]].add(value);
emit Transfer(0x0, _owners[i], value);
}
}
} | @notice get time period for the given '_lockTypeIndex' @param _lockTypeIndex The user's investment locktype index @param _timeDifference The passed time since releaseStartTime to now @return Return the time period | function getPeriod(uint256 _lockTypeIndex, uint256 _timeDifference) internal view returns (uint256) {
uint256 _period1 = (_timeDifference.div(oneMonth)).div(12);
if(_period1 >= 3){
_period1 = 3;
}
return _period1;
}
uint256 _period2 = _timeDifference.div(oneMonth);
| 1,540,105 | [
1,
588,
813,
3879,
364,
326,
864,
2070,
739,
559,
1016,
11,
225,
389,
739,
559,
1016,
1021,
729,
1807,
2198,
395,
475,
2176,
723,
770,
225,
389,
957,
16220,
1021,
2275,
813,
3241,
3992,
13649,
358,
2037,
327,
2000,
326,
813,
3879,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
22612,
2386,
12,
11890,
5034,
389,
739,
559,
1016,
16,
2254,
5034,
389,
957,
16220,
13,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
5411,
2254,
5034,
389,
6908,
21,
273,
261,
67,
957,
16220,
18,
2892,
12,
476,
5445,
13,
2934,
2892,
12,
2138,
1769,
203,
5411,
309,
24899,
6908,
21,
1545,
890,
15329,
203,
7734,
389,
6908,
21,
273,
890,
31,
203,
5411,
289,
203,
5411,
327,
389,
6908,
21,
31,
203,
3639,
289,
203,
5411,
2254,
5034,
389,
6908,
22,
273,
389,
957,
16220,
18,
2892,
12,
476,
5445,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "../libraries/SafeCastExtended.sol";
import "../interfaces/IERC721Mintable.sol";
/**
* @title Listings Library
* @author JaboiNads
* @notice Encapsulates functionality for listings on the Marketplace.
*/
library Listings {
using CountersUpgradeable for CountersUpgradeable.Counter;
using SafeCastExtended for uint256;
uint32 constant private PRECISION_SCALAR = 1000;
/**
* @dev The different types of listing.
*/
enum ListingType {
Unlisted,
FixedPrice,
DutchAuction,
EnglishAuction
}
/**
* @dev Data for an individual listing.
*/
struct Listing {
// The unique identifier of the token.
uint48 tokenId;
// The type of token that is listed.
IERC721Mintable token;
// The unix timestamp of the block the listing was created on (in seconds).
uint64 createdAt;
// [Auctions Only]: The duration of the listing (in seconds).
uint32 duration;
// [Auctions Only]: The price to begin bidding at.
uint128 startingPrice;
// The ending price (Dutch Auctions), or the buyout price (Fixed price, English auction) if present.
uint128 buyoutOrEndingPrice;
// The address that created the listing.
address seller;
// The address with the highest bid (English Auctions only)
address highestBidder;
// The current highest bid (English Auctions only)
uint128 highestBid;
// The type of listing.
ListingType listingType;
// How long the contract was paused at the time the listing was created.
uint32 pauseDurationAtCreation;
}
/**
* @dev Data for managing active listings.
*/
struct Data {
// The counter for generating unique listing ids.
CountersUpgradeable.Counter idCounter;
// Maps a token to its listing id, or zero if the listing does not exist.
mapping(IERC721Mintable => mapping(uint48 => uint48)) indices;
// Maps a listing ID to the listing.
mapping(uint48 => Listing) listings;
}
/**
* @notice Creates a fixed price listing and adds it to storage.
* @param self The data set to operate on.
* @param token The contract of the token.
* @param tokenId The id of the token.
* @param seller The seller of the token.
* @param price The price to list the token at.
*/
function addFixedPriceListing(
Data storage self,
IERC721Mintable token,
uint48 tokenId,
address seller,
uint32 currentPauseDuration,
uint128 price
) internal returns (uint48) {
require(price > 0, "no price provided");
return _addListing(
self,
ListingType.EnglishAuction,
token,
tokenId,
seller,
currentPauseDuration,
0,
0,
price
);
}
/**
* @notice Creates a fixed price listing and adds it to storage.
* @param self The data set to operate on.
* @param token The contract of the token.
* @param tokenId The id of the token.
* @param seller The seller of the token.
* @param currentPauseDuration The marketplace's current pause duration.
* @param startingPrice The price to begin the auction at.
* @param endingPrice The price to end the auction at.
* @param duration The length of time to run the auction for (in seconds).
*/
function addDutchAuctionListing(
Data storage self,
IERC721Mintable token,
uint48 tokenId,
address seller,
uint32 currentPauseDuration,
uint128 startingPrice,
uint128 endingPrice,
uint32 duration
) internal returns (uint48) {
require(startingPrice > endingPrice, "invalid price range");
require(endingPrice > 0, "invalid ending price");
require(duration > 0, "invalid duration");
return _addListing(
self,
ListingType.DutchAuction,
token,
tokenId,
seller,
currentPauseDuration,
duration,
startingPrice,
endingPrice
);
}
/**
* @notice Creates a English auction listing and adds it to storage.
* @param self The data set to operate on.
* @param token The contract of the token.
* @param tokenId The id of the token.
* @param seller The seller of the token.
* @param currentPauseDuration The marketplace's current pause duration.
* @param startingPrice The price to begin the auction at.
* @param buyoutPrice The price to automatically buy the token at, or 0 for no buyout.
* @param duration The length of time to run the auction for (in seconds).
*/
function addEnglishAuctionListing(
Data storage self,
IERC721Mintable token,
uint48 tokenId,
address seller,
uint32 currentPauseDuration,
uint128 startingPrice,
uint128 buyoutPrice,
uint32 duration
) internal returns (uint48) {
require(startingPrice > 0, "invalid starting price");
require(buyoutPrice == 0 || buyoutPrice > startingPrice, "invalid buyout price");
require(duration > 0, "invalid duration");
return _addListing(
self,
ListingType.EnglishAuction,
token,
tokenId,
seller,
currentPauseDuration,
duration,
startingPrice,
buyoutPrice
);
}
/**
* @notice Removes the specified listing from storage.
* @param self The data set to operate on.
* @param listingId The id of the listing to remove.
* @dev This function will revert if the listing does not exist.
*/
function removeListing(
Data storage self,
uint48 listingId
) internal {
Listing storage listing = get(self, listingId);
_removeListing(self, listing.token, listing.tokenId, listingId);
}
/**
* @notice Removes the specified listing from storage.
* @param self The data set to operate on.
* @param listingId The id of the listing to remove.
*/
function tryRemoveListing(
Data storage self,
uint48 listingId
) internal returns (bool) {
(bool success, Listing storage listing) = tryGet(self, listingId);
if (success) {
_removeListing(self, listing.token, listing.tokenId, listingId);
}
return success;
}
/**
* @notice Returns whether the specified listing exists.
* @param self The data set to operate on.
* @param listingId The unique id of the listing.
*/
function exists(
Data storage self,
uint48 listingId
) internal view returns (bool) {
return self.listings[listingId].listingType != ListingType.Unlisted;
}
/**
* @notice Returns whether the specified listing exists.
* @param self The data set to operate on.
* @param token The contract of the token.
* @param tokenId The id of the token.
*/
function exists(
Data storage self,
IERC721Mintable token,
uint48 tokenId
) internal view returns (bool) {
return exists(self, self.indices[token][tokenId]);
}
/**
* @notice Returns the listing associated with the specified id.
* @param self The data set to operate on.
* @param listingId The unique id of the listing.
* @dev This function will revert if the listing does not exist.
*/
function get(
Data storage self,
uint48 listingId
) internal view returns (Listing storage) {
Listing storage listing = self.listings[listingId];
require(listing.listingType != ListingType.Unlisted, "nonexistent listing");
return listing;
}
/**
* @notice Returns the listing associated with the specified token.
* @param self The data set to operate on.
* @param token The contract of the token.
* @param tokenId The id of the token.
* @dev This function will revert if the listing does not exist.
*/
function get(
Data storage self,
IERC721Mintable token,
uint48 tokenId
) internal view returns (Listing storage) {
return get(self, self.indices[token][tokenId]);
}
/**
* @notice Returns the listing associated with the specified id.
* @param self The data set to operate on.
* @param listingId The unique identifier of the listing.
*/
function tryGet(
Data storage self,
uint48 listingId
) internal view returns (bool, Listing storage) {
Listing storage listing = self.listings[listingId];
return (listing.listingType != ListingType.Unlisted, listing);
}
/**
* @notice Returns the listing associated with the specified token.
* @param self The data set to operate on.
* @param token The contract of the token.
* @param tokenId The id of the token.
*/
function tryGet(
Data storage self,
IERC721Mintable token,
uint48 tokenId
) internal view returns (bool, Listing storage) {
return tryGet(self, self.indices[token][tokenId]);
}
/**
* @notice Gets the price to buy the specified listing.
* @param self The data set to operate on.
* @param listingId The id of the listing to buy.
*/
function getBuyPrice(
Data storage self,
uint48 listingId
) internal view returns (uint128) {
Listing storage listing = get(self, listingId);
if (listing.listingType == ListingType.DutchAuction) {
// Calculate the percentage of the auction that has finished so far.
uint128 alpha = ((block.timestamp.toUint128() - listing.createdAt) * PRECISION_SCALAR) / listing.duration;
// Linearly interpolate between the starting and ending prices, then normalize the result to get the real price.
return (listing.startingPrice - ((listing.startingPrice - listing.buyoutOrEndingPrice) * alpha)) / PRECISION_SCALAR;
} else {
return listing.buyoutOrEndingPrice;
}
}
/**
* @notice Generates a unique identifier for a listing.
* @param self The data set to operate on.
*/
function _generateNextId(
Data storage self
) private returns (uint48) {
self.idCounter.increment();
return self.idCounter.current().toUint48();
}
/**
* @notice Adds a listing to storage.
* @param self The data set to operate on.
* @param token The contract of the token to add.
* @param tokenId The id of the token to add.
* @param seller The address that created the listing.
* @param duration The length of time to run the auction (in seconds).
* @param startingPrice The starting price of the auction.
* @param buyoutOrEndingPrice The buyout or ending price, or zero if
*/
function _addListing(
Data storage self,
ListingType listingType,
IERC721Mintable token,
uint48 tokenId,
address seller,
uint32 currentPauseDuration,
uint32 duration,
uint128 startingPrice,
uint128 buyoutOrEndingPrice
) private returns (uint48) {
require(!exists(self, token, tokenId), "token is already listed");
require(seller != address(0), "seller cannot be zero-address");
require(seller == token.ownerOf(tokenId), "seller must own token");
// Generate a unique identifier for the listing.
uint48 listingId = _generateNextId(self);
// Write the listing to storage.
self.indices[token][tokenId] = listingId;
self.listings[listingId] = Listing({
listingType: listingType,
token: token,
tokenId: tokenId,
seller: seller,
pauseDurationAtCreation: currentPauseDuration,
createdAt: block.timestamp.toUint64(),
duration: duration,
startingPrice: startingPrice,
buyoutOrEndingPrice: buyoutOrEndingPrice,
highestBidder: address(0),
highestBid: 0
});
// Return the listing id.
return listingId;
}
/**
* @notice Deletes a listing from storage.
* @param self The data set to operate on.
* @param token The contract of the token to delete.
* @param tokenId The id of the token to delete.
* @param listingId The id of the listing to delete.
*/
function _removeListing(
Data storage self,
IERC721Mintable token,
uint48 tokenId,
uint48 listingId
) private {
delete self.indices[token][tokenId];
delete self.listings[listingId];
}
} | * @notice Removes the specified listing from storage. @param self The data set to operate on. @param listingId The id of the listing to remove./ | function tryRemoveListing(
Data storage self,
uint48 listingId
) internal returns (bool) {
(bool success, Listing storage listing) = tryGet(self, listingId);
if (success) {
_removeListing(self, listing.token, listing.tokenId, listingId);
}
return success;
}
| 13,121,074 | [
1,
6220,
326,
1269,
11591,
628,
2502,
18,
225,
365,
1021,
501,
444,
358,
20829,
603,
18,
225,
11591,
548,
1021,
612,
434,
326,
11591,
358,
1206,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
775,
3288,
19081,
12,
203,
3639,
1910,
2502,
365,
16,
203,
3639,
2254,
8875,
11591,
548,
203,
565,
262,
2713,
1135,
261,
6430,
13,
288,
203,
3639,
261,
6430,
2216,
16,
987,
310,
2502,
11591,
13,
273,
775,
967,
12,
2890,
16,
11591,
548,
1769,
203,
3639,
309,
261,
4768,
13,
288,
203,
5411,
389,
4479,
19081,
12,
2890,
16,
11591,
18,
2316,
16,
11591,
18,
2316,
548,
16,
11591,
548,
1769,
203,
3639,
289,
203,
3639,
327,
2216,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x10aEC5622602e02186508318bD6e2cD995C92705/sources/contracts/MusicRacerNFT333.sol | @dev предложить акку стать владельцем todo доделать так, чтобы можно было назначить цену в эфире, для продажи | function SetOwnerRequest(address newOwner) public onlyOwner {
_OwnerRequest[GetContractOwnerIndex(msg.sender)] = newOwner;
}
| 3,872,187 | [
1,
145,
128,
146,
227,
145,
118,
145,
117,
145,
124,
145,
127,
145,
119,
145,
121,
146,
229,
146,
239,
225,
145,
113,
145,
123,
145,
123,
146,
230,
225,
146,
228,
146,
229,
145,
113,
146,
229,
146,
239,
225,
145,
115,
145,
124,
145,
113,
145,
117,
145,
118,
145,
124,
146,
239,
146,
233,
145,
118,
145,
125,
10621,
225,
145,
117,
145,
127,
145,
117,
145,
118,
145,
124,
145,
113,
146,
229,
146,
239,
225,
146,
229,
145,
113,
145,
123,
16,
225,
146,
234,
146,
229,
145,
127,
145,
114,
146,
238,
225,
145,
125,
145,
127,
145,
119,
145,
126,
145,
127,
225,
145,
114,
146,
238,
145,
124,
145,
127,
225,
145,
126,
145,
113,
145,
120,
145,
126,
145,
113,
146,
234,
145,
121,
146,
229,
146,
239,
225,
146,
233,
145,
118,
145,
126,
146,
230,
225,
145,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
565,
445,
1000,
5541,
691,
12,
2867,
394,
5541,
13,
1071,
1338,
5541,
288,
203,
3639,
389,
5541,
691,
63,
967,
8924,
5541,
1016,
12,
3576,
18,
15330,
25887,
273,
394,
5541,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x9d08CCeD85A68Bf8A19374ED4B5753aE3Be9F74f/sources/contracts/protocol/modules/v1/AaveV3LeverageModule.sol | * @dev Invoke borrow from the SetToken during issuance hook. Since we only need to interact with AAVE once we fetch the lending pool in this function to optimize vs forcing a fetch twice during lever/delever./ | function _repayBorrowForHook(ISetToken _setToken, IERC20 _asset, uint256 _notionalQuantity) internal {
_repayBorrow(_setToken, IPool(lendingPoolAddressesProvider.getPool()), _asset, _notionalQuantity);
}
| 15,718,183 | [
1,
10969,
29759,
628,
326,
1000,
1345,
4982,
3385,
89,
1359,
3953,
18,
7897,
732,
1338,
1608,
358,
16592,
598,
432,
26714,
3647,
732,
2158,
326,
328,
2846,
2845,
316,
333,
445,
358,
10979,
6195,
364,
2822,
279,
2158,
13605,
4982,
884,
502,
19,
3771,
6084,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
266,
10239,
38,
15318,
1290,
5394,
12,
45,
694,
1345,
389,
542,
1345,
16,
467,
654,
39,
3462,
389,
9406,
16,
2254,
5034,
389,
902,
285,
287,
12035,
13,
2713,
288,
203,
3639,
389,
266,
10239,
38,
15318,
24899,
542,
1345,
16,
467,
2864,
12,
80,
2846,
2864,
7148,
2249,
18,
588,
2864,
1435,
3631,
389,
9406,
16,
389,
902,
285,
287,
12035,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.10;
pragma experimental ABIEncoderV2;
import {GelatoActionsStandardFull} from "../GelatoActionsStandardFull.sol";
import {IERC20} from "../../external/IERC20.sol";
import {Address} from "../../external/Address.sol";
import {GelatoBytes} from "../../libraries/GelatoBytes.sol";
import {SafeERC20} from "../../external/SafeERC20.sol";
import {DataFlow} from "../../gelato_core/interfaces/IGelatoCore.sol";
/// @dev This action is for user proxies that store funds.
contract ActionTransfer is GelatoActionsStandardFull {
// using SafeERC20 for IERC20; <- internal library methods vs. try/catch
using Address for address payable;
using SafeERC20 for IERC20;
// ======= DEV HELPERS =========
/// @dev use this function to encode the data off-chain for the action data field
function getActionData(address _sendToken, uint256 _sendAmount, address _destination)
public
pure
virtual
returns(bytes memory)
{
return abi.encodeWithSelector(
this.action.selector,
_sendToken,
_sendAmount,
_destination
);
}
/// @dev Used by GelatoActionPipeline.isValid()
function DATA_FLOW_IN_TYPE() public pure virtual override returns (bytes32) {
return keccak256("TOKEN,UINT256");
}
/// @dev Used by GelatoActionPipeline.isValid()
function DATA_FLOW_OUT_TYPE() public pure virtual override returns (bytes32) {
return keccak256("TOKEN,UINT256");
}
// ======= ACTION IMPLEMENTATION DETAILS =========
/// @dev Always use this function for encoding _actionData off-chain
/// Will be called by GelatoActionPipeline if Action.dataFlow.None
function action(address sendToken, uint256 sendAmount, address destination)
public
virtual
delegatecallOnly("ActionTransfer.action")
{
if (sendToken != ETH_ADDRESS) {
IERC20 sendERC20 = IERC20(sendToken);
sendERC20.safeTransfer(destination, sendAmount, "ActionTransfer.action:");
emit LogOneWay(address(this), sendToken, sendAmount, destination);
} else {
payable(destination).sendValue(sendAmount);
}
}
/// @dev Will be called by GelatoActionPipeline if Action.dataFlow.In
// => do not use for _actionData encoding
function execWithDataFlowIn(bytes calldata _actionData, bytes calldata _inFlowData)
external
payable
virtual
override
{
(address sendToken, uint256 sendAmount) = abi.decode(_inFlowData, (address,uint256));
address destination = abi.decode(_actionData[68:100], (address));
action(sendToken, sendAmount, destination);
}
/// @dev Will be called by GelatoActionPipeline if Action.dataFlow.Out
// => do not use for _actionData encoding
function execWithDataFlowOut(bytes calldata _actionData)
external
payable
virtual
override
returns (bytes memory)
{
(address sendToken, uint256 sendAmount, address destination) = abi.decode(
_actionData[4:],
(address,uint256,address)
);
action(sendToken, sendAmount, destination);
return abi.encode(sendToken, sendAmount);
}
/// @dev Will be called by GelatoActionPipeline if Action.dataFlow.InAndOut
// => do not use for _actionData encoding
function execWithDataFlowInAndOut(
bytes calldata _actionData,
bytes calldata _inFlowData
)
external
payable
virtual
override
returns (bytes memory)
{
(address sendToken, uint256 sendAmount) = abi.decode(_inFlowData, (address,uint256));
address destination = abi.decode(_actionData[68:100], (address));
action(sendToken, sendAmount, destination);
return abi.encode(sendToken, sendAmount);
}
// ===== ACTION TERMS CHECK ========
// Overriding and extending GelatoActionsStandard's function (optional)
function termsOk(
uint256, // taskReceipId
address _userProxy,
bytes calldata _actionData,
DataFlow _dataFlow,
uint256, // value
uint256 // cycleId
)
public
view
virtual
override
returns(string memory)
{
if (this.action.selector != GelatoBytes.calldataSliceSelector(_actionData))
return "ActionTransfer: invalid action selector";
if (_dataFlow == DataFlow.In || _dataFlow == DataFlow.InAndOut)
return "ActionTransfer: termsOk check invalidated by inbound DataFlow";
(address sendToken, uint256 sendAmount) = abi.decode(
_actionData[4:68],
(address,uint256)
);
if (sendToken == ETH_ADDRESS) {
if (_userProxy.balance < sendAmount)
return "ActionTransfer: NotOkUserProxyETHBalance";
} else {
try IERC20(sendToken).balanceOf(_userProxy) returns(uint256 sendTokenBalance) {
if (sendTokenBalance < sendAmount)
return "ActionTransfer: NotOkUserProxyERC20Balance";
} catch {
return "ActionTransfer: ErrorBalanceOf";
}
}
// STANDARD return string to signal actionConditions Ok
return OK;
}
}
| @dev This action is for user proxies that store funds. using SafeERC20 for IERC20; <- internal library methods vs. try/catch ======= DEV HELPERS ========= | contract ActionTransfer is GelatoActionsStandardFull {
using Address for address payable;
using SafeERC20 for IERC20;
function getActionData(address _sendToken, uint256 _sendAmount, address _destination)
public
pure
virtual
returns(bytes memory)
pragma solidity ^0.6.10;
import {GelatoActionsStandardFull} from "../GelatoActionsStandardFull.sol";
import {IERC20} from "../../external/IERC20.sol";
import {Address} from "../../external/Address.sol";
import {GelatoBytes} from "../../libraries/GelatoBytes.sol";
import {SafeERC20} from "../../external/SafeERC20.sol";
import {DataFlow} from "../../gelato_core/interfaces/IGelatoCore.sol";
{
return abi.encodeWithSelector(
this.action.selector,
_sendToken,
_sendAmount,
_destination
);
}
function DATA_FLOW_IN_TYPE() public pure virtual override returns (bytes32) {
return keccak256("TOKEN,UINT256");
}
function DATA_FLOW_OUT_TYPE() public pure virtual override returns (bytes32) {
return keccak256("TOKEN,UINT256");
}
function action(address sendToken, uint256 sendAmount, address destination)
public
virtual
delegatecallOnly("ActionTransfer.action")
{
if (sendToken != ETH_ADDRESS) {
IERC20 sendERC20 = IERC20(sendToken);
sendERC20.safeTransfer(destination, sendAmount, "ActionTransfer.action:");
emit LogOneWay(address(this), sendToken, sendAmount, destination);
payable(destination).sendValue(sendAmount);
}
}
function action(address sendToken, uint256 sendAmount, address destination)
public
virtual
delegatecallOnly("ActionTransfer.action")
{
if (sendToken != ETH_ADDRESS) {
IERC20 sendERC20 = IERC20(sendToken);
sendERC20.safeTransfer(destination, sendAmount, "ActionTransfer.action:");
emit LogOneWay(address(this), sendToken, sendAmount, destination);
payable(destination).sendValue(sendAmount);
}
}
} else {
function execWithDataFlowIn(bytes calldata _actionData, bytes calldata _inFlowData)
external
payable
virtual
override
{
(address sendToken, uint256 sendAmount) = abi.decode(_inFlowData, (address,uint256));
address destination = abi.decode(_actionData[68:100], (address));
action(sendToken, sendAmount, destination);
}
function execWithDataFlowOut(bytes calldata _actionData)
external
payable
virtual
override
returns (bytes memory)
{
(address sendToken, uint256 sendAmount, address destination) = abi.decode(
_actionData[4:],
(address,uint256,address)
);
action(sendToken, sendAmount, destination);
return abi.encode(sendToken, sendAmount);
}
function execWithDataFlowInAndOut(
bytes calldata _actionData,
bytes calldata _inFlowData
)
external
payable
virtual
override
returns (bytes memory)
{
(address sendToken, uint256 sendAmount) = abi.decode(_inFlowData, (address,uint256));
address destination = abi.decode(_actionData[68:100], (address));
action(sendToken, sendAmount, destination);
return abi.encode(sendToken, sendAmount);
}
function termsOk(
address _userProxy,
bytes calldata _actionData,
DataFlow _dataFlow,
)
public
view
virtual
override
returns(string memory)
{
if (this.action.selector != GelatoBytes.calldataSliceSelector(_actionData))
return "ActionTransfer: invalid action selector";
if (_dataFlow == DataFlow.In || _dataFlow == DataFlow.InAndOut)
return "ActionTransfer: termsOk check invalidated by inbound DataFlow";
(address sendToken, uint256 sendAmount) = abi.decode(
_actionData[4:68],
(address,uint256)
);
if (sendToken == ETH_ADDRESS) {
if (_userProxy.balance < sendAmount)
return "ActionTransfer: NotOkUserProxyETHBalance";
try IERC20(sendToken).balanceOf(_userProxy) returns(uint256 sendTokenBalance) {
if (sendTokenBalance < sendAmount)
return "ActionTransfer: NotOkUserProxyERC20Balance";
return "ActionTransfer: ErrorBalanceOf";
}
}
}
function termsOk(
address _userProxy,
bytes calldata _actionData,
DataFlow _dataFlow,
)
public
view
virtual
override
returns(string memory)
{
if (this.action.selector != GelatoBytes.calldataSliceSelector(_actionData))
return "ActionTransfer: invalid action selector";
if (_dataFlow == DataFlow.In || _dataFlow == DataFlow.InAndOut)
return "ActionTransfer: termsOk check invalidated by inbound DataFlow";
(address sendToken, uint256 sendAmount) = abi.decode(
_actionData[4:68],
(address,uint256)
);
if (sendToken == ETH_ADDRESS) {
if (_userProxy.balance < sendAmount)
return "ActionTransfer: NotOkUserProxyETHBalance";
try IERC20(sendToken).balanceOf(_userProxy) returns(uint256 sendTokenBalance) {
if (sendTokenBalance < sendAmount)
return "ActionTransfer: NotOkUserProxyERC20Balance";
return "ActionTransfer: ErrorBalanceOf";
}
}
}
} else {
function termsOk(
address _userProxy,
bytes calldata _actionData,
DataFlow _dataFlow,
)
public
view
virtual
override
returns(string memory)
{
if (this.action.selector != GelatoBytes.calldataSliceSelector(_actionData))
return "ActionTransfer: invalid action selector";
if (_dataFlow == DataFlow.In || _dataFlow == DataFlow.InAndOut)
return "ActionTransfer: termsOk check invalidated by inbound DataFlow";
(address sendToken, uint256 sendAmount) = abi.decode(
_actionData[4:68],
(address,uint256)
);
if (sendToken == ETH_ADDRESS) {
if (_userProxy.balance < sendAmount)
return "ActionTransfer: NotOkUserProxyETHBalance";
try IERC20(sendToken).balanceOf(_userProxy) returns(uint256 sendTokenBalance) {
if (sendTokenBalance < sendAmount)
return "ActionTransfer: NotOkUserProxyERC20Balance";
return "ActionTransfer: ErrorBalanceOf";
}
}
}
} catch {
return OK;
}
| 1,824,036 | [
1,
2503,
1301,
353,
364,
729,
13263,
716,
1707,
284,
19156,
18,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
3290,
2713,
5313,
2590,
6195,
18,
775,
19,
14683,
422,
894,
33,
2030,
58,
22557,
3194,
55,
422,
894,
12275,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
4382,
5912,
353,
611,
292,
31093,
6100,
8336,
5080,
288,
203,
565,
1450,
5267,
364,
1758,
8843,
429,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
565,
445,
12473,
751,
12,
2867,
389,
4661,
1345,
16,
2254,
5034,
389,
4661,
6275,
16,
1758,
389,
10590,
13,
203,
3639,
1071,
203,
3639,
16618,
203,
3639,
5024,
203,
3639,
1135,
12,
3890,
3778,
13,
203,
683,
9454,
18035,
560,
3602,
20,
18,
26,
18,
2163,
31,
203,
5666,
288,
43,
292,
31093,
6100,
8336,
5080,
97,
628,
315,
6216,
43,
292,
31093,
6100,
8336,
5080,
18,
18281,
14432,
203,
5666,
288,
45,
654,
39,
3462,
97,
628,
315,
16644,
9375,
19,
45,
654,
39,
3462,
18,
18281,
14432,
203,
5666,
288,
1887,
97,
628,
315,
16644,
9375,
19,
1887,
18,
18281,
14432,
203,
5666,
288,
43,
292,
31093,
2160,
97,
628,
315,
16644,
31417,
19,
43,
292,
31093,
2160,
18,
18281,
14432,
203,
5666,
288,
9890,
654,
39,
3462,
97,
628,
315,
16644,
9375,
19,
9890,
654,
39,
3462,
18,
18281,
14432,
203,
5666,
288,
751,
5249,
97,
628,
315,
16644,
75,
292,
31093,
67,
3644,
19,
15898,
19,
3047,
292,
31093,
4670,
18,
18281,
14432,
203,
565,
288,
203,
3639,
327,
24126,
18,
3015,
1190,
4320,
12,
203,
5411,
333,
18,
1128,
18,
9663,
16,
203,
5411,
389,
4661,
1345,
16,
203,
5411,
389,
4661,
6275,
16,
203,
5411,
389,
10590,
203,
3639,
11272,
203,
565,
289,
203,
203,
565,
445,
8730,
67,
17430,
67,
706,
2
]
|
// File: contracts/interfaces/IERC173.sol
pragma solidity ^0.5.7;
/// @title ERC-173 Contract Ownership Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-173.md
/// Note: the ERC-165 identifier for this interface is 0x7f5828d0
contract IERC173 {
/// @dev This emits when ownership of a contract changes.
event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner);
/// @notice Get the address of the owner
/// @return The address of the owner.
//// function owner() external view returns (address);
/// @notice Set the address of the new owner of the contract
/// @param _newOwner The address of the new owner of the contract
function transferOwnership(address _newOwner) external;
}
// File: contracts/commons/Ownable.sol
pragma solidity ^0.5.7;
contract Ownable is IERC173 {
address internal _owner;
modifier onlyOwner() {
require(tx.origin == _owner, "The owner should be the sender"); //inject USING TX ORIGIN FOR AUTHENTICATION
_;
}
constructor() public {
_owner = msg.sender;
emit OwnershipTransferred(address(0x0), msg.sender);
}
function owner() external view returns (address) {
return _owner;
}
/**
@dev Transfers the ownership of the contract.
@param _newOwner Address of the new owner
*/
function transferOwnership(address _newOwner) external onlyOwner {
require(_newOwner != address(0), "0x0 Is not a valid owner");
emit OwnershipTransferred(_owner, _newOwner);
_owner = _newOwner;
}
}
// File: contracts/interfaces/IERC165.sol
pragma solidity ^0.5.7;
interface IERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
// File: contracts/core/diaspore/interfaces/RateOracle.sol
pragma solidity ^0.5.7;
/**
@dev Defines the interface of a standard Diaspore RCN Oracle,
The contract should also implement it's ERC165 interface: 0xa265d8e0
@notice Each oracle can only support one currency
@author Agustin Aguilar
*/
contract RateOracle is IERC165 {
uint256 public constant VERSION = 5;
bytes4 internal constant RATE_ORACLE_INTERFACE = 0xa265d8e0;
constructor() internal {}
/**
3 or 4 letters symbol of the currency, Ej: ETH
*/
function symbol() external view returns (string memory);
/**
Descriptive name of the currency, Ej: Ethereum
*/
function name() external view returns (string memory);
/**
The number of decimals of the currency represented by this Oracle,
it should be the most common number of decimal places
*/
function decimals() external view returns (uint256);
/**
The base token on which the sample is returned
should be the RCN Token address.
*/
function token() external view returns (address);
/**
The currency symbol encoded on a UTF-8 Hex
*/
function currency() external view returns (bytes32);
/**
The name of the Individual or Company in charge of this Oracle
*/
function maintainer() external view returns (string memory);
/**
Returns the url where the oracle exposes a valid "oracleData" if needed
*/
function url() external view returns (string memory);
/**
Returns a sample on how many token() are equals to how many currency()
*/
function readSample(bytes calldata _data) external returns (uint256 _tokens, uint256 _equivalent);
}
// File: contracts/commons/ERC165.sol
pragma solidity ^0.5.7;
/**
* @title ERC165
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract ERC165 is IERC165 {
bytes4 private constant _InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) private _supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
internal
{
_registerInterface(_InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 interfaceId)
external
view
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev internal method for registering an interface
*/
function _registerInterface(bytes4 interfaceId)
internal
{
require(interfaceId != 0xffffffff, "Can't register 0xffffffff");
_supportedInterfaces[interfaceId] = true;
}
}
// File: contracts/core/basalt/utils/OwnableBasalt.sol
pragma solidity ^0.5.7;
contract OwnableBasalt {
address public owner;
modifier onlyOwner() {
require(tx.origin == owner, "The owner should be the sender"); //inject USING TX ORIGIN FOR AUTHENTICATION
_;
}
constructor() public {
owner = msg.sender;
}
/**
@dev Transfers the ownership of the contract.
@param _to Address of the new owner
*/
function transferTo(address _to) public onlyOwner returns (bool) {
require(_to != address(0), "0x0 Is not a valid owner");
owner = _to;
return true;
}
}
// File: contracts/core/basalt/interfaces/Oracle.sol
pragma solidity ^0.5.7;
/**
@dev Defines the interface of a standard RCN oracle.
The oracle is an agent in the RCN network that supplies a convertion rate between RCN and any other currency,
it's primarily used by the exchange but could be used by any other agent.
*/
contract Oracle is OwnableBasalt {
uint256 public constant VERSION = 4;
event NewSymbol(bytes32 _currency);
mapping(bytes32 => bool) public supported;
bytes32[] public currencies;
/**
@dev Returns the url where the oracle exposes a valid "oracleData" if needed
*/
function url() public view returns (string memory);
/**
@dev Returns a valid convertion rate from the currency given to RCN
@param symbol Symbol of the currency
@param data Generic data field, could be used for off-chain signing
*/
function getRate(bytes32 symbol, bytes memory data) public returns (uint256 rate, uint256 decimals);
/**
@dev Adds a currency to the oracle, once added it cannot be removed
@param ticker Symbol of the currency
@return if the creation was done successfully
*/
function addCurrency(string memory ticker) public onlyOwner returns (bool) {
bytes32 currency = encodeCurrency(ticker);
emit NewSymbol(currency);
supported[currency] = true;
currencies.push(currency);
return true;
}
/**
@return the currency encoded as a bytes32
*/
function encodeCurrency(string memory currency) public pure returns (bytes32 o) {
require(bytes(currency).length <= 32);
assembly {
o := mload(add(currency, 32))
}
}
/**
@return the currency string from a encoded bytes32
*/
function decodeCurrency(bytes32 b) public pure returns (string memory o) {
uint256 ns = 256;
while (true) {
if (ns == 0 || (b<<ns-8) != 0)
break;
ns -= 8;
}
assembly {
ns := div(ns, 8)
o := mload(0x40)
mstore(0x40, add(o, and(add(add(ns, 0x20), 0x1f), not(0x1f))))
mstore(o, ns)
mstore(add(o, 32), b)
}
}
}
// File: contracts/core/diaspore/utils/OracleAdapter.sol
pragma solidity ^0.5.7;
contract OracleAdapter is Ownable, RateOracle, ERC165 {
Oracle public legacyOracle;
string private isymbol;
string private iname;
string private imaintainer;
uint256 private idecimals;
bytes32 private icurrency;
address private itoken;
constructor(
Oracle _legacyOracle,
string memory _symbol,
string memory _name,
string memory _maintainer,
uint256 _decimals,
bytes32 _currency,
address _token
) public {
legacyOracle = _legacyOracle;
isymbol = _symbol;
iname = _name;
imaintainer = _maintainer;
idecimals = _decimals;
icurrency = _currency;
itoken = _token;
_registerInterface(RATE_ORACLE_INTERFACE);
}
function symbol() external view returns (string memory) { return isymbol; }
function name() external view returns (string memory) { return iname; }
function decimals() external view returns (uint256) { return idecimals; }
function token() external view returns (address) { return itoken; }
function currency() external view returns (bytes32) { return icurrency; }
function maintainer() external view returns (string memory) { return imaintainer; }
function url() external view returns (string memory) {
return legacyOracle.url();
}
function setMaintainer(string calldata _maintainer) external onlyOwner {
imaintainer = _maintainer;
}
function setName(string calldata _name) external onlyOwner {
iname = _name;
}
function setLegacyOracle(Oracle _legacyOracle) external onlyOwner {
legacyOracle = _legacyOracle;
}
function readSample(bytes calldata _data) external returns (uint256 _tokens, uint256 _equivalent) {
(_tokens, _equivalent) = legacyOracle.getRate(icurrency, _data);
_equivalent = 10 ** _equivalent;
}
} | @title ERC-173 Contract Ownership Standard @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-173.md Note: the ERC-165 identifier for this interface is 0x7f5828d0 | contract IERC173 {
event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner);
function transferOwnership(address _newOwner) external;
}
| 1,038,000 | [
1,
654,
39,
17,
31331,
13456,
14223,
9646,
5310,
8263,
225,
2164,
2333,
2207,
6662,
18,
832,
19,
546,
822,
379,
19,
41,
18246,
19,
10721,
19,
7525,
19,
41,
2579,
55,
19,
73,
625,
17,
31331,
18,
1264,
225,
3609,
30,
326,
4232,
39,
17,
28275,
2756,
364,
333,
1560,
353,
374,
92,
27,
74,
8204,
6030,
72,
20,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
467,
654,
39,
31331,
288,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8808,
389,
11515,
5541,
16,
1758,
8808,
389,
2704,
5541,
1769,
203,
203,
203,
565,
445,
7412,
5460,
12565,
12,
2867,
389,
2704,
5541,
13,
3903,
31,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/3/0x4AE3f435cae4347a47aF1aad87Fd01C8B1980bA8/sources/WaifuDao.sol | File: contracts/WaifuDao.solSPDX-License-Identifier: MITContract based on [https:docs.openzeppelin.com/contracts/3.x/erc721](https:docs.openzeppelin.com/contracts/3.x/erc721) ============ ACCESS CONTROL/SANITY MODIFIERS ============ | contract WaifuDao is ERC721A, IERC2981, Ownable, ReentrancyGuard {
using Counters for Counters.Counter;
using Strings for uint256;
Counters.Counter private tokenCounter;
address private openSeaProxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1;
bool private isOpenSeaProxyActive = true;
uint256 public constant MAX_MINTS_PER_TX = 5;
uint256 public maxSupply = 1100;
uint256 public constant PUBLIC_SALE_PRICE = 0.01 ether;
uint256 public NUM_FREE_MINTS = 555;
bool public isPublicSaleActive = true;
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
}
pragma solidity ^0.8.0;
modifier publicSaleActive() {
require(isPublicSaleActive, "Public sale is not open");
_;
}
modifier maxMintsPerTX(uint256 numberOfTokens) {
require(
numberOfTokens <= MAX_MINTS_PER_TX,
"Max mints per transaction exceeded"
);
_;
}
modifier canMintNFTs(uint256 numberOfTokens) {
require(
totalSupply() + numberOfTokens <=
maxSupply,
"Not enough mints remaining to mint"
);
_;
}
modifier freeMintsAvailable() {
require(
totalSupply() <=
NUM_FREE_MINTS,
"Not enough free mints remain"
);
_;
}
modifier isCorrectPayment(uint256 price, uint256 numberOfTokens) {
if(totalSupply()>NUM_FREE_MINTS){
require(
(price * numberOfTokens) == msg.value,
"Incorrect ETH value sent"
);
}
_;
}
constructor(
modifier isCorrectPayment(uint256 price, uint256 numberOfTokens) {
if(totalSupply()>NUM_FREE_MINTS){
require(
(price * numberOfTokens) == msg.value,
"Incorrect ETH value sent"
);
}
_;
}
constructor(
) ERC721A("WaifuDao", "wfu", 100, maxSupply) {
}
function mint(uint256 numberOfTokens)
external
payable
nonReentrant
isCorrectPayment(PUBLIC_SALE_PRICE, numberOfTokens)
publicSaleActive
canMintNFTs(numberOfTokens)
maxMintsPerTX(numberOfTokens)
{
_safeMint(msg.sender, numberOfTokens);
}
function freeMint(uint256 numberOfTokens)
external
nonReentrant
publicSaleActive
canMintNFTs(numberOfTokens)
maxMintsPerTX(numberOfTokens)
freeMintsAvailable()
{
_safeMint(msg.sender, numberOfTokens);
}
function getBaseURI() external view returns (string memory) {
return baseURI;
}
function setBaseURI(string memory _baseURI) external onlyOwner {
baseURI = _baseURI;
}
function setIsOpenSeaProxyActive(bool _isOpenSeaProxyActive)
external
onlyOwner
{
isOpenSeaProxyActive = _isOpenSeaProxyActive;
}
function setIsPublicSaleActive(bool _isPublicSaleActive)
external
onlyOwner
{
isPublicSaleActive = _isPublicSaleActive;
}
function setNumFreeMints(uint256 _numfreemints)
external
onlyOwner
{
NUM_FREE_MINTS = _numfreemints;
}
function withdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
function withdrawTokens(IERC20 token) public onlyOwner {
uint256 balance = token.balanceOf(address(this));
token.transfer(msg.sender, balance);
}
function nextTokenId() private returns (uint256) {
tokenCounter.increment();
return tokenCounter.current();
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721A, IERC165)
returns (bool)
{
return
interfaceId == type(IERC2981).interfaceId ||
super.supportsInterface(interfaceId);
}
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
ProxyRegistry proxyRegistry = ProxyRegistry(
openSeaProxyRegistryAddress
);
if (
isOpenSeaProxyActive &&
address(proxyRegistry.proxies(owner)) == operator
) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
ProxyRegistry proxyRegistry = ProxyRegistry(
openSeaProxyRegistryAddress
);
if (
isOpenSeaProxyActive &&
address(proxyRegistry.proxies(owner)) == operator
) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), "Nonexistent token");
return
string(abi.encodePacked(baseURI, "/", (tokenId+1).toString(), ".json"));
}
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
require(_exists(tokenId), "Nonexistent token");
return (address(this), SafeMath.div(SafeMath.mul(salePrice, 5), 100));
}
}
| 14,144,805 | [
1,
812,
30,
20092,
19,
59,
69,
430,
89,
11412,
18,
18281,
3118,
28826,
17,
13211,
17,
3004,
30,
490,
1285,
8924,
2511,
603,
306,
4528,
30,
8532,
18,
3190,
94,
881,
84,
292,
267,
18,
832,
19,
16351,
87,
19,
23,
18,
92,
19,
12610,
27,
5340,
29955,
4528,
30,
8532,
18,
3190,
94,
881,
84,
292,
267,
18,
832,
19,
16351,
87,
19,
23,
18,
92,
19,
12610,
27,
5340,
13,
422,
1432,
631,
13255,
8020,
13429,
19,
22721,
4107,
8663,
10591,
55,
422,
1432,
631,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
678,
69,
430,
89,
11412,
353,
4232,
39,
27,
5340,
37,
16,
467,
654,
39,
5540,
11861,
16,
14223,
6914,
16,
868,
8230,
12514,
16709,
288,
203,
565,
1450,
9354,
87,
364,
9354,
87,
18,
4789,
31,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
203,
565,
9354,
87,
18,
4789,
3238,
1147,
4789,
31,
203,
203,
565,
1758,
3238,
1696,
1761,
69,
3886,
4243,
1887,
273,
374,
6995,
6564,
5908,
557,
29,
8204,
39,
10261,
39,
23,
74,
5082,
29,
5292,
28,
70,
378,
2226,
37,
27,
71,
5292,
5528,
38,
20,
4700,
71,
21,
31,
203,
565,
1426,
3238,
16633,
1761,
69,
3886,
3896,
273,
638,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
4552,
67,
49,
3217,
55,
67,
3194,
67,
16556,
273,
1381,
31,
203,
565,
2254,
5034,
1071,
943,
3088,
1283,
273,
4648,
713,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
17187,
67,
5233,
900,
67,
7698,
1441,
273,
374,
18,
1611,
225,
2437,
31,
203,
565,
2254,
5034,
1071,
9443,
67,
28104,
67,
49,
3217,
55,
273,
1381,
2539,
31,
203,
565,
1426,
1071,
19620,
30746,
3896,
273,
638,
31,
203,
203,
203,
203,
203,
203,
225,
445,
389,
5771,
1345,
1429,
18881,
12,
203,
565,
1758,
628,
16,
203,
565,
1758,
358,
16,
203,
565,
2254,
5034,
787,
1345,
548,
16,
203,
565,
2254,
5034,
10457,
203,
203,
225,
445,
389,
5205,
1345,
1429,
18881,
12,
203,
565,
1758,
628,
16,
203,
565,
1758,
358,
16,
203,
565,
2254,
5034,
787,
1345,
548,
16,
2
]
|
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import './TimelockedTokenVault.sol';
/**
* Contract that extends the TimelockedTokenVault with the support to release the capital
* based on a predefiend interval
*/
contract TimelockedIntervalReleasedTokenVault is TimelockedTokenVault {
using SafeERC20 for IERC20;
// the interval
uint256 private immutable _interval;
/**
* @dev Initalizes a new instanc of the TimelockedIntervaldReleased Vault
* @param beneficiary_ the beneficary who gets the holdings
* @param interval_ in seconds
* @param duration_ in seconds
*/
constructor(
address beneficiary_,
uint256 duration_,
uint256 interval_
) TimelockedTokenVault(beneficiary_, duration_) {
_interval = interval_;
}
/**
* @return the interval within which capital will be released
*/
function interval() public view returns (uint256) {
return _interval;
}
/**
* @return returns the available amount to collect for the current time
*/
function availableAmount() public view returns (uint256) {
require(_started, 'Lock not started');
uint256 tokensToRetrieve = 0;
if (block.timestamp >= _startDate + _duration) {
tokensToRetrieve = _token.balanceOf(address(this));
} else {
uint256 parts = _duration / _interval;
uint256 tokensByPart = _startBalance / parts;
uint256 timeSinceStart = block.timestamp - _startDate;
uint256 pastParts = timeSinceStart / _interval;
uint256 tokensToRetrieveSinceStart = pastParts * tokensByPart;
tokensToRetrieve = tokensToRetrieveSinceStart - _retrievedTokens;
}
return tokensToRetrieve;
}
/**
* @dev payout the locked amount of token
*/
function retrieveLockedTokens() public override onlyOwner {
require(_started, 'Lock not started');
uint256 amountToTransfer = availableAmount();
require(amountToTransfer > 0, 'No tokens available for retrieving at this moment.');
_retrievedTokens = _retrievedTokens + amountToTransfer;
_token.safeTransfer(beneficiary(), amountToTransfer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import '../utils/RetrieveTokensFeature.sol';
/**
* Contract that acts as a freeze (timelocked) vault to an immuntable beneficiary.
*/
contract TimelockedTokenVault is RetrieveTokensFeature {
using SafeERC20 for IERC20;
// ERC20 basic token contract being held
IERC20 internal _token;
// beneficiary of tokens after they are released
address internal immutable _beneficiary;
// the duration of the lock in seconds
uint256 internal immutable _duration;
// initial start balance
uint256 internal _startBalance;
// indiacted wheter vault started or not
bool internal _started;
// startDate of the lock in a unix timestamp
uint256 internal _startDate;
// the amount of tokens already retrieved
uint256 internal _retrievedTokens;
/**
* @dev Initalizes a new instanc of the TimelockedTokenVault Vault
* @param beneficiary_ the beneficiary who can collect the holdings
* @param duration_ the duration of the vault in seconds
*/
constructor(address beneficiary_, uint256 duration_) {
require(beneficiary_ != address(0), 'Address 0 as beneficary is not allowed');
_beneficiary = beneficiary_;
_duration = duration_;
_retrievedTokens = 0;
}
/**
* @dev starts the vault
*/
function start(IERC20 token_) public onlyOwner {
require(!_started, 'Lock already started');
require(address(token_) != address(0), 'Token must be set');
_token = token_;
_startDate = block.timestamp;
_startBalance = _token.balanceOf(address(this));
_started = true;
}
/**
* @return the duration being held in seconds
*/
function duration() public view returns (uint256) {
return _duration;
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @return the state of the vault
*/
function started() public view returns (bool) {
return _started;
}
/**
* @return the retrieved tokens
*/
function retrievedTokens() public view returns (uint256) {
return _retrievedTokens;
}
/**
* @return the token being held.
*/
function token() public view returns (IERC20) {
return _token;
}
/**
* @return the start balance
*/
function startBalance() public view returns (uint256) {
return _startBalance;
}
/**
* @return the startDate of the vault
*/
function startDate() public view returns (uint256) {
return _startDate;
}
/**
* @return the enddate of the token being held as timestamp
*/
function endDate() public view returns (uint256) {
return _startDate + _duration;
}
/**
* @dev payout the locked amount of token
*/
function retrieveLockedTokens() public virtual onlyOwner {
require(_started, 'Lock not started');
require(block.timestamp >= endDate(), 'Duration not over');
uint256 tokensToRetrieve = _token.balanceOf(address(this));
_token.safeTransfer(beneficiary(), tokensToRetrieve);
}
/**
* @dev retrieve wrongly assigned tokens, in situation lock wasn't initialized allow full access
*/
function retrieveTokens(address to, address anotherToken) public override onlyOwner {
require(address(_token) != anotherToken, 'The withdraw is restriected to extraneous tokens.');
super.retrieveTokens(to, anotherToken);
}
}
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import '@openzeppelin/contracts/utils/Context.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
/**
* Contract that provides ETH and ERC20 token retriever authorised by the owner
*/
contract RetrieveTokensFeature is Context, Ownable {
using SafeERC20 for IERC20;
/**
* @dev Allows to transfer the whole amount of the given token to a receiver
*/
function retrieveTokens(address to, address anotherToken) public virtual onlyOwner {
IERC20 alienToken = IERC20(anotherToken);
alienToken.safeTransfer(to, alienToken.balanceOf(address(this)));
}
/**
* @dev Allows to transfer contract's ETH to a receiver
*/
function retrieveETH(address payable to) public virtual onlyOwner {
to.transfer(address(this).balance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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);
}
}
}
} | * @dev payout the locked amount of token/ | function retrieveLockedTokens() public override onlyOwner {
require(_started, 'Lock not started');
uint256 amountToTransfer = availableAmount();
require(amountToTransfer > 0, 'No tokens available for retrieving at this moment.');
_retrievedTokens = _retrievedTokens + amountToTransfer;
_token.safeTransfer(beneficiary(), amountToTransfer);
}
| 10,276,831 | [
1,
84,
2012,
326,
8586,
3844,
434,
1147,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4614,
8966,
5157,
1435,
1071,
3849,
1338,
5541,
288,
203,
3639,
2583,
24899,
14561,
16,
296,
2531,
486,
5746,
8284,
203,
3639,
2254,
5034,
3844,
774,
5912,
273,
2319,
6275,
5621,
203,
3639,
2583,
12,
8949,
774,
5912,
405,
374,
16,
296,
2279,
2430,
2319,
364,
17146,
622,
333,
10382,
1093,
1769,
203,
3639,
389,
14580,
2155,
5157,
273,
389,
14580,
2155,
5157,
397,
3844,
774,
5912,
31,
203,
3639,
389,
2316,
18,
4626,
5912,
12,
70,
4009,
74,
14463,
814,
9334,
3844,
774,
5912,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.5.13;
import "./FixidityLib.sol";
import "./ExponentLib.sol";
import "./LogarithmLib.sol";
contract InterestRateModel {
using FixidityLib for FixidityLib.Fixidity;
using ExponentLib for FixidityLib.Fixidity;
using LogarithmLib for FixidityLib.Fixidity;
FixidityLib.Fixidity public fixidity;
address public admin;
address public proposedAdmin;
int256 public constant point1 = 20000000000000000; //0.02 *1e18
int256 public constant point2 = 381966011250105152; //0.382*1e18, (3-sqrt(5))/2
int256 public constant point3 = 618033988749894848; //0.618*1e18, (sqrt(5)-1)/2
int256 public constant point4 = 980000000000000000; //0.98 *1e18
//https://www.mathsisfun.com/numbers/e-eulers-number.html
int256 public constant e = 2718281828459045235; //2.71828182845904523536*1e18
int256 public constant minInterest = 15000000000000000; //0.015*1e18
int256 public reserveRadio = 100000000000000000; //10% spread
int256 public constant ONE_ETH = 1e18;
int256 public constant k = 191337753576934987; //point1^(e-1)
constructor() public {
admin = msg.sender;
}
modifier onlyAdmin() {
require(msg.sender == admin, "only admin can do this!");
_;
}
function proposeNewAdmin(address admin_) external onlyAdmin {
proposedAdmin = admin_;
}
function claimAdministration() external {
require(msg.sender == proposedAdmin, "Not proposed admin.");
admin = proposedAdmin;
proposedAdmin = address(0);
}
// function setAdmin(address newAdmin) external onlyAdmin {
// admin = newAdmin;
// }
function init(uint8 digits) external onlyAdmin {
fixidity.init(digits);
}
function setReserveRatio(int256 radio) external onlyAdmin {
reserveRadio = radio;
}
//y=0.015+x^e; x: [0, (3-sqrt(5))/2], [0,0.382]
function curve1(int256 x) public view returns (int256 y) {
// y = minInterest + x**e;
int256 xPowE = fixidity.power_any(x, e); //x**e
y = fixidity.add(minInterest, xPowE);
}
//y=0.015+((3-sqrt(5))/2)**(e-1)*x; x:[(3-sqrt(5))/2,(sqrt(5)-1)/2], [0.382,0.618]
function lineraSegment(int256 x) public view returns (int256 y) {
// require(x > point1 && x <= point2, "invalid x in lineraSegment");
int256 k = k;
int256 kx = fixidity.multiply(k, x);
y = fixidity.add(minInterest, kx);
}
// y = ((3-sqrt(5))/2)^(e-1) - (1-x)^e + 0.015
// y = 0.015 - (1-x)^e+point2^(e-1)
function curve2(int256 x) public view returns (int256 y) {
if (x == ONE_ETH) {
y = 206337753576934987; //0.206337753576934987*ONE_ETH
} else {
int256 c = k; //point1^(e-1)
c = fixidity.add(c, minInterest);
int256 x2 = fixidity.power_any(fixidity.subtract(ONE_ETH, x), e);
y = fixidity.subtract(c, x2);
}
}
//获取使用率
function getBorrowPercent(int256 cash, int256 borrow)
public
view
returns (int256 y)
{
// int total = fixidity.add(cash, borrow);
// if (total == 0) {
// y = 0;
// } else {
// y = fixidity.divide(borrow, total);
// }
y = fixidity.add(cash, borrow);
if (y != 0) {
y = fixidity.divide(borrow, y);
}
}
//loanRate
function getLoanRate(int256 cash, int256 borrow)
public
view
returns (int256 y)
{
int256 u = getBorrowPercent(cash, borrow);
if (u == 0) {
return minInterest;
}
if (
fixidity.subtract(u, point1) < 0 ||
fixidity.subtract(point4, u) <= 0 ||
(fixidity.subtract(u, point2) >= 0 &&
fixidity.subtract(point3, u) > 0)
) {
y = lineraSegment(u);
} else if (fixidity.subtract(u, point2) < 0) {
y = curve1(u);
} else {
y = curve2(u);
}
}
//depositRate
function getDepositRate(int256 cash, int256 borrow)
external
view
returns (int256 y)
{
int256 loanRate = getLoanRate(cash, borrow);
int256 loanRatePercent = fixidity.multiply(
loanRate,
getBorrowPercent(cash, borrow)
);
y = fixidity.multiply(
loanRatePercent,
fixidity.subtract(ONE_ETH, reserveRadio)
);
}
//index(a, n) = index(a, n-1) * (1 + r*t), index为本金
function calculateInterestIndex(
int256 index,
int256 r,
int256 t
) external view returns (int256 y) {
if (t == 0) {
y = index;
} else {
int256 rt = fixidity.multiply(r, t);
int256 sum = fixidity.add(rt, fixidity.fixed_1);
y = fixidity.multiply(index, sum); //返回本息
}
}
//r为年利率,t为秒数,p*e^(rt)
function pert(
int256 principal,
int256 r,
int256 t
) external view returns (int256 y) {
if (t == 0 || r == 0) {
y = principal;
} else {
int256 r1 = fixidity.log_e(fixidity.add(r, fixidity.fixed_1)); //r1 = ln(r+1)
int256 r2 = fixidity.divide(r1, 60 * 60 * 24 * 365 * ONE_ETH); //r2=r1/(60*60*24*365)
int256 interest = fixidity.power_e(
fixidity.multiply(r2, t * ONE_ETH)
); //e^(r2*t)
y = fixidity.multiply(principal, interest); //返回本息
}
}
function calculateBalance(
int256 principal,
int256 lastIndex,
int256 newIndex
) external view returns (int256 y) {
if (principal == 0 || lastIndex == 0) {
y = 0;
} else {
y = fixidity.divide(
fixidity.multiply(principal, newIndex),
lastIndex
);
}
}
function mul(int256 a, int256 b) internal view returns (int256 c) {
c = fixidity.multiply(a, b);
}
function mul3(
int256 a,
int256 b,
int256 c
) internal view returns (int256 d) {
d = mul(a, mul(b, c));
}
function getNewReserve(
int256 oldReserve,
int256 cash,
int256 borrow,
int256 blockDelta
) external view returns (int256 y) {
int256 borrowRate = getLoanRate(cash, borrow);
int256 simpleInterestFactor = fixidity.multiply(borrowRate, blockDelta);
y = fixidity.add(
oldReserve,
mul3(simpleInterestFactor, borrow, reserveRadio)
);
}
}
| y = ((3-sqrt(5))/2)^(e-1) - (1-x)^e + 0.015 y = 0.015 - (1-x)^e+point2^(e-1) | function curve2(int256 x) public view returns (int256 y) {
if (x == ONE_ETH) {
c = fixidity.add(c, minInterest);
int256 x2 = fixidity.power_any(fixidity.subtract(ONE_ETH, x), e);
y = fixidity.subtract(c, x2);
}
}
| 12,697,832 | [
1,
93,
273,
14015,
23,
17,
24492,
12,
25,
3719,
19,
22,
13,
29020,
73,
17,
21,
13,
300,
261,
21,
17,
92,
13,
66,
73,
397,
374,
18,
1611,
25,
677,
273,
374,
18,
1611,
25,
300,
261,
21,
17,
92,
13,
66,
73,
15,
1153,
22,
29020,
73,
17,
21,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
8882,
22,
12,
474,
5034,
619,
13,
1071,
1476,
1135,
261,
474,
5034,
677,
13,
288,
203,
3639,
309,
261,
92,
422,
15623,
67,
1584,
44,
13,
288,
203,
5411,
276,
273,
2917,
24237,
18,
1289,
12,
71,
16,
1131,
29281,
1769,
203,
5411,
509,
5034,
619,
22,
273,
2917,
24237,
18,
12238,
67,
2273,
12,
904,
24237,
18,
1717,
1575,
12,
5998,
67,
1584,
44,
16,
619,
3631,
425,
1769,
203,
5411,
677,
273,
2917,
24237,
18,
1717,
1575,
12,
71,
16,
619,
22,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.17;
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO";
/**
* @dev Multiplies two numbers, 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, ERROR_MUL_OVERFLOW);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts 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 Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint256 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers 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, ERROR_DIV_ZERO);
return a % b;
}
}
/*
* SPDX-License-Identifier: MIT
*/
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address _who) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/SafeERC20.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
library SafeERC20 {
/**
* @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
* Note that this makes an external call to the provided token and expects it to be already
* verified as a contract.
*/
function safeTransfer(IERC20 _token, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferCallData = abi.encodeWithSelector(
_token.transfer.selector,
_to,
_amount
);
return invokeAndCheckSuccess(address(_token), transferCallData);
}
/**
* @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
* Note that this makes an external call to the provided token and expects it to be already
* verified as a contract.
*/
function safeTransferFrom(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferFromCallData = abi.encodeWithSelector(
_token.transferFrom.selector,
_from,
_to,
_amount
);
return invokeAndCheckSuccess(address(_token), transferFromCallData);
}
/**
* @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
* Note that this makes an external call to the provided token and expects it to be already
* verified as a contract.
*/
function safeApprove(IERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
bytes memory approveCallData = abi.encodeWithSelector(
_token.approve.selector,
_spender,
_amount
);
return invokeAndCheckSuccess(address(_token), approveCallData);
}
function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) {
bool ret;
assembly {
let ptr := mload(0x40) // free memory pointer
let success := call(
gas, // forward all gas
_addr, // address
0, // no value
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
// Check number of bytes returned from last function call
switch returndatasize
// No bytes returned: assume success
case 0 {
ret := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// Only return success if returned data was true
// Already have output in ptr
ret := eq(mload(ptr), 1)
}
// Not sure what was returned: don't mark as success
default { }
}
}
return ret;
}
}
library PctHelpers {
using SafeMath for uint256;
uint256 internal constant PCT_BASE = 10000; // ‱ (1 / 10,000)
function isValid(uint16 _pct) internal pure returns (bool) {
return _pct <= PCT_BASE;
}
function pct(uint256 self, uint16 _pct) internal pure returns (uint256) {
return self.mul(uint256(_pct)) / PCT_BASE;
}
function pct256(uint256 self, uint256 _pct) internal pure returns (uint256) {
return self.mul(_pct) / PCT_BASE;
}
function pctIncrease(uint256 self, uint16 _pct) internal pure returns (uint256) {
// No need for SafeMath: for addition note that `PCT_BASE` is lower than (2^256 - 2^16)
return self.mul(PCT_BASE + uint256(_pct)) / PCT_BASE;
}
}
/**
* @title Checkpointing - Library to handle a historic set of numeric values
*/
library Checkpointing {
uint256 private constant MAX_UINT192 = uint256(uint192(-1));
string private constant ERROR_VALUE_TOO_BIG = "CHECKPOINT_VALUE_TOO_BIG";
string private constant ERROR_CANNOT_ADD_PAST_VALUE = "CHECKPOINT_CANNOT_ADD_PAST_VALUE";
/**
* @dev To specify a value at a given point in time, we need to store two values:
* - `time`: unit-time value to denote the first time when a value was registered
* - `value`: a positive numeric value to registered at a given point in time
*
* Note that `time` does not need to refer necessarily to a timestamp value, any time unit could be used
* for it like block numbers, terms, etc.
*/
struct Checkpoint {
uint64 time;
uint192 value;
}
/**
* @dev A history simply denotes a list of checkpoints
*/
struct History {
Checkpoint[] history;
}
/**
* @dev Add a new value to a history for a given point in time. This function does not allow to add values previous
* to the latest registered value, if the value willing to add corresponds to the latest registered value, it
* will be updated.
* @param self Checkpoints history to be altered
* @param _time Point in time to register the given value
* @param _value Numeric value to be registered at the given point in time
*/
function add(History storage self, uint64 _time, uint256 _value) internal {
require(_value <= MAX_UINT192, ERROR_VALUE_TOO_BIG);
_add192(self, _time, uint192(_value));
}
/**
* @dev Fetch the latest registered value of history, it will return zero if there was no value registered
* @param self Checkpoints history to be queried
*/
function getLast(History storage self) internal view returns (uint256) {
uint256 length = self.history.length;
if (length > 0) {
return uint256(self.history[length - 1].value);
}
return 0;
}
/**
* @dev Fetch the most recent registered past value of a history based on a given point in time that is not known
* how recent it is beforehand. It will return zero if there is no registered value or if given time is
* previous to the first registered value.
* It uses a binary search.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function get(History storage self, uint64 _time) internal view returns (uint256) {
return _binarySearch(self, _time);
}
/**
* @dev Fetch the most recent registered past value of a history based on a given point in time. It will return zero
* if there is no registered value or if given time is previous to the first registered value.
* It uses a linear search starting from the end.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function getRecent(History storage self, uint64 _time) internal view returns (uint256) {
return _backwardsLinearSearch(self, _time);
}
/**
* @dev Private function to add a new value to a history for a given point in time. This function does not allow to
* add values previous to the latest registered value, if the value willing to add corresponds to the latest
* registered value, it will be updated.
* @param self Checkpoints history to be altered
* @param _time Point in time to register the given value
* @param _value Numeric value to be registered at the given point in time
*/
function _add192(History storage self, uint64 _time, uint192 _value) private {
uint256 length = self.history.length;
if (length == 0 || self.history[self.history.length - 1].time < _time) {
// If there was no value registered or the given point in time is after the latest registered value,
// we can insert it to the history directly.
self.history.push(Checkpoint(_time, _value));
} else {
// If the point in time given for the new value is not after the latest registered value, we must ensure
// we are only trying to update the latest value, otherwise we would be changing past data.
Checkpoint storage currentCheckpoint = self.history[length - 1];
require(_time == currentCheckpoint.time, ERROR_CANNOT_ADD_PAST_VALUE);
currentCheckpoint.value = _value;
}
}
/**
* @dev Private function to execute a backwards linear search to find the most recent registered past value of a
* history based on a given point in time. It will return zero if there is no registered value or if given time
* is previous to the first registered value. Note that this function will be more suitable when we already know
* that the time used to index the search is recent in the given history.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function _backwardsLinearSearch(History storage self, uint64 _time) private view returns (uint256) {
// If there was no value registered for the given history return simply zero
uint256 length = self.history.length;
if (length == 0) {
return 0;
}
uint256 index = length - 1;
Checkpoint storage checkpoint = self.history[index];
while (index > 0 && checkpoint.time > _time) {
index--;
checkpoint = self.history[index];
}
return checkpoint.time > _time ? 0 : uint256(checkpoint.value);
}
/**
* @dev Private function execute a binary search to find the most recent registered past value of a history based on
* a given point in time. It will return zero if there is no registered value or if given time is previous to
* the first registered value. Note that this function will be more suitable when don't know how recent the
* time used to index may be.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function _binarySearch(History storage self, uint64 _time) private view returns (uint256) {
// If there was no value registered for the given history return simply zero
uint256 length = self.history.length;
if (length == 0) {
return 0;
}
// If the requested time is equal to or after the time of the latest registered value, return latest value
uint256 lastIndex = length - 1;
if (_time >= self.history[lastIndex].time) {
return uint256(self.history[lastIndex].value);
}
// If the requested time is previous to the first registered value, return zero to denote missing checkpoint
if (_time < self.history[0].time) {
return 0;
}
// Execute a binary search between the checkpointed times of the history
uint256 low = 0;
uint256 high = lastIndex;
while (high > low) {
// No need for SafeMath: for this to overflow array size should be ~2^255
uint256 mid = (high + low + 1) / 2;
Checkpoint storage checkpoint = self.history[mid];
uint64 midTime = checkpoint.time;
if (_time > midTime) {
low = mid;
} else if (_time < midTime) {
// No need for SafeMath: high > low >= 0 => high >= 1 => mid >= 1
high = mid - 1;
} else {
return uint256(checkpoint.value);
}
}
return uint256(self.history[low].value);
}
}
/**
* @title HexSumTree - Library to operate checkpointed 16-ary (hex) sum trees.
* @dev A sum tree is a particular case of a tree where the value of a node is equal to the sum of the values of its
* children. This library provides a set of functions to operate 16-ary sum trees, i.e. trees where every non-leaf
* node has 16 children and its value is equivalent to the sum of the values of all of them. Additionally, a
* checkpointed tree means that each time a value on a node is updated, its previous value will be saved to allow
* accessing historic information.
*
* Example of a checkpointed binary sum tree:
*
* CURRENT PREVIOUS
*
* Level 2 100 ---------------------------------------- 70
* ______|_______ ______|_______
* / \ / \
* Level 1 34 66 ------------------------- 23 47
* _____|_____ _____|_____ _____|_____ _____|_____
* / \ / \ / \ / \
* Level 0 22 12 53 13 ----------- 22 1 17 30
*
*/
library HexSumTree {
using SafeMath for uint256;
using Checkpointing for Checkpointing.History;
string private constant ERROR_UPDATE_OVERFLOW = "SUM_TREE_UPDATE_OVERFLOW";
string private constant ERROR_KEY_DOES_NOT_EXIST = "SUM_TREE_KEY_DOES_NOT_EXIST";
string private constant ERROR_SEARCH_OUT_OF_BOUNDS = "SUM_TREE_SEARCH_OUT_OF_BOUNDS";
string private constant ERROR_MISSING_SEARCH_VALUES = "SUM_TREE_MISSING_SEARCH_VALUES";
// Constants used to perform tree computations
// To change any the following constants, the following relationship must be kept: 2^BITS_IN_NIBBLE = CHILDREN
// The max depth of the tree will be given by: BITS_IN_NIBBLE * MAX_DEPTH = 256 (so in this case it's 64)
uint256 private constant CHILDREN = 16;
uint256 private constant BITS_IN_NIBBLE = 4;
// All items are leaves, inserted at height or level zero. The root height will be increasing as new levels are inserted in the tree.
uint256 private constant ITEMS_LEVEL = 0;
// Tree nodes are identified with a 32-bytes length key. Leaves are identified with consecutive incremental keys
// starting with 0x0000000000000000000000000000000000000000000000000000000000000000, while non-leaf nodes' keys
// are computed based on their level and their children keys.
uint256 private constant BASE_KEY = 0;
// Timestamp used to checkpoint the first value of the tree height during initialization
uint64 private constant INITIALIZATION_INITIAL_TIME = uint64(0);
/**
* @dev The tree is stored using the following structure:
* - nodes: A mapping indexed by a pair (level, key) with a history of the values for each node (level -> key -> value).
* - height: A history of the heights of the tree. Minimum height is 1, a root with 16 children.
* - nextKey: The next key to be used to identify the next new value that will be inserted into the tree.
*/
struct Tree {
uint256 nextKey;
Checkpointing.History height;
mapping (uint256 => mapping (uint256 => Checkpointing.History)) nodes;
}
/**
* @dev Search params to traverse the tree caching previous results:
* - time: Point in time to query the values being searched, this value shouldn't change during a search
* - level: Level being analyzed for the search, it starts at the level under the root and decrements till the leaves
* - parentKey: Key of the parent of the nodes being analyzed at the given level for the search
* - foundValues: Number of values in the list being searched that were already found, it will go from 0 until the size of the list
* - visitedTotal: Total sum of values that were already visited during the search, it will go from 0 until the tree total
*/
struct SearchParams {
uint64 time;
uint256 level;
uint256 parentKey;
uint256 foundValues;
uint256 visitedTotal;
}
/**
* @dev Initialize tree setting the next key and first height checkpoint
*/
function init(Tree storage self) internal {
self.height.add(INITIALIZATION_INITIAL_TIME, ITEMS_LEVEL + 1);
self.nextKey = BASE_KEY;
}
/**
* @dev Insert a new item to the tree at given point in time
* @param _time Point in time to register the given value
* @param _value New numeric value to be added to the tree
* @return Unique key identifying the new value inserted
*/
function insert(Tree storage self, uint64 _time, uint256 _value) internal returns (uint256) {
// As the values are always stored in the leaves of the tree (level 0), the key to index each of them will be
// always incrementing, starting from zero. Add a new level if necessary.
uint256 key = self.nextKey++;
_addLevelIfNecessary(self, key, _time);
// If the new value is not zero, first set the value of the new leaf node, then add a new level at the top of
// the tree if necessary, and finally update sums cached in all the non-leaf nodes.
if (_value > 0) {
_add(self, ITEMS_LEVEL, key, _time, _value);
_updateSums(self, key, _time, _value, true);
}
return key;
}
/**
* @dev Set the value of a leaf node indexed by its key at given point in time
* @param _time Point in time to set the given value
* @param _key Key of the leaf node to be set in the tree
* @param _value New numeric value to be set for the given key
*/
function set(Tree storage self, uint256 _key, uint64 _time, uint256 _value) internal {
require(_key < self.nextKey, ERROR_KEY_DOES_NOT_EXIST);
// Set the new value for the requested leaf node
uint256 lastValue = getItem(self, _key);
_add(self, ITEMS_LEVEL, _key, _time, _value);
// Update sums cached in the non-leaf nodes. Note that overflows are being checked at the end of the whole update.
if (_value > lastValue) {
_updateSums(self, _key, _time, _value - lastValue, true);
} else if (_value < lastValue) {
_updateSums(self, _key, _time, lastValue - _value, false);
}
}
/**
* @dev Update the value of a non-leaf node indexed by its key at given point in time based on a delta
* @param _key Key of the leaf node to be updated in the tree
* @param _time Point in time to update the given value
* @param _delta Numeric delta to update the value of the given key
* @param _positive Boolean to tell whether the given delta should be added to or subtracted from the current value
*/
function update(Tree storage self, uint256 _key, uint64 _time, uint256 _delta, bool _positive) internal {
require(_key < self.nextKey, ERROR_KEY_DOES_NOT_EXIST);
// Update the value of the requested leaf node based on the given delta
uint256 lastValue = getItem(self, _key);
uint256 newValue = _positive ? lastValue.add(_delta) : lastValue.sub(_delta);
_add(self, ITEMS_LEVEL, _key, _time, newValue);
// Update sums cached in the non-leaf nodes. Note that overflows is being checked at the end of the whole update.
_updateSums(self, _key, _time, _delta, _positive);
}
/**
* @dev Search a list of values in the tree at a given point in time. It will return a list with the nearest
* high value in case a value cannot be found. This function assumes the given list of given values to be
* searched is in ascending order. In case of searching a value out of bounds, it will return zeroed results.
* @param _values Ordered list of values to be searched in the tree
* @param _time Point in time to query the values being searched
* @return keys List of keys found for each requested value in the same order
* @return values List of node values found for each requested value in the same order
*/
function search(Tree storage self, uint256[] memory _values, uint64 _time) internal view
returns (uint256[] memory keys, uint256[] memory values)
{
require(_values.length > 0, ERROR_MISSING_SEARCH_VALUES);
// Throw out-of-bounds error if there are no items in the tree or the highest value being searched is greater than the total
uint256 total = getRecentTotalAt(self, _time);
// No need for SafeMath: positive length of array already checked
require(total > 0 && total > _values[_values.length - 1], ERROR_SEARCH_OUT_OF_BOUNDS);
// Build search params for the first iteration
uint256 rootLevel = getRecentHeightAt(self, _time);
SearchParams memory searchParams = SearchParams(_time, rootLevel.sub(1), BASE_KEY, 0, 0);
// These arrays will be used to fill in the results. We are passing them as parameters to avoid extra copies
uint256 length = _values.length;
keys = new uint256[](length);
values = new uint256[](length);
_search(self, _values, searchParams, keys, values);
}
/**
* @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree
*/
function getTotal(Tree storage self) internal view returns (uint256) {
uint256 rootLevel = getHeight(self);
return getNode(self, rootLevel, BASE_KEY);
}
/**
* @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree, at a given point in time
* It uses a binary search for the root node, a linear one for the height.
* @param _time Point in time to query the sum of all the items (leaves) stored in the tree
*/
function getTotalAt(Tree storage self, uint64 _time) internal view returns (uint256) {
uint256 rootLevel = getRecentHeightAt(self, _time);
return getNodeAt(self, rootLevel, BASE_KEY, _time);
}
/**
* @dev Tell the sum of the all the items (leaves) stored in the tree, i.e. value of the root of the tree, at a given point in time
* It uses a linear search starting from the end.
* @param _time Point in time to query the sum of all the items (leaves) stored in the tree
*/
function getRecentTotalAt(Tree storage self, uint64 _time) internal view returns (uint256) {
uint256 rootLevel = getRecentHeightAt(self, _time);
return getRecentNodeAt(self, rootLevel, BASE_KEY, _time);
}
/**
* @dev Tell the value of a certain leaf indexed by a given key
* @param _key Key of the leaf node querying the value of
*/
function getItem(Tree storage self, uint256 _key) internal view returns (uint256) {
return getNode(self, ITEMS_LEVEL, _key);
}
/**
* @dev Tell the value of a certain leaf indexed by a given key at a given point in time
* It uses a binary search.
* @param _key Key of the leaf node querying the value of
* @param _time Point in time to query the value of the requested leaf
*/
function getItemAt(Tree storage self, uint256 _key, uint64 _time) internal view returns (uint256) {
return getNodeAt(self, ITEMS_LEVEL, _key, _time);
}
/**
* @dev Tell the value of a certain node indexed by a given (level,key) pair
* @param _level Level of the node querying the value of
* @param _key Key of the node querying the value of
*/
function getNode(Tree storage self, uint256 _level, uint256 _key) internal view returns (uint256) {
return self.nodes[_level][_key].getLast();
}
/**
* @dev Tell the value of a certain node indexed by a given (level,key) pair at a given point in time
* It uses a binary search.
* @param _level Level of the node querying the value of
* @param _key Key of the node querying the value of
* @param _time Point in time to query the value of the requested node
*/
function getNodeAt(Tree storage self, uint256 _level, uint256 _key, uint64 _time) internal view returns (uint256) {
return self.nodes[_level][_key].get(_time);
}
/**
* @dev Tell the value of a certain node indexed by a given (level,key) pair at a given point in time
* It uses a linear search starting from the end.
* @param _level Level of the node querying the value of
* @param _key Key of the node querying the value of
* @param _time Point in time to query the value of the requested node
*/
function getRecentNodeAt(Tree storage self, uint256 _level, uint256 _key, uint64 _time) internal view returns (uint256) {
return self.nodes[_level][_key].getRecent(_time);
}
/**
* @dev Tell the height of the tree
*/
function getHeight(Tree storage self) internal view returns (uint256) {
return self.height.getLast();
}
/**
* @dev Tell the height of the tree at a given point in time
* It uses a linear search starting from the end.
* @param _time Point in time to query the height of the tree
*/
function getRecentHeightAt(Tree storage self, uint64 _time) internal view returns (uint256) {
return self.height.getRecent(_time);
}
/**
* @dev Private function to update the values of all the ancestors of the given leaf node based on the delta updated
* @param _key Key of the leaf node to update the ancestors of
* @param _time Point in time to update the ancestors' values of the given leaf node
* @param _delta Numeric delta to update the ancestors' values of the given leaf node
* @param _positive Boolean to tell whether the given delta should be added to or subtracted from ancestors' values
*/
function _updateSums(Tree storage self, uint256 _key, uint64 _time, uint256 _delta, bool _positive) private {
uint256 mask = uint256(-1);
uint256 ancestorKey = _key;
uint256 currentHeight = getHeight(self);
for (uint256 level = ITEMS_LEVEL + 1; level <= currentHeight; level++) {
// Build a mask to get the key of the ancestor at a certain level. For example:
// Level 0: leaves don't have children
// Level 1: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0 (up to 16 leaves)
// Level 2: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 (up to 32 leaves)
// ...
// Level 63: 0x0000000000000000000000000000000000000000000000000000000000000000 (up to 16^64 leaves - tree max height)
mask = mask << BITS_IN_NIBBLE;
// The key of the ancestor at that level "i" is equivalent to the "(64 - i)-th" most significant nibbles
// of the ancestor's key of the previous level "i - 1". Thus, we can compute the key of an ancestor at a
// certain level applying the mask to the ancestor's key of the previous level. Note that for the first
// iteration, the key of the ancestor of the previous level is simply the key of the leaf being updated.
ancestorKey = ancestorKey & mask;
// Update value
uint256 lastValue = getNode(self, level, ancestorKey);
uint256 newValue = _positive ? lastValue.add(_delta) : lastValue.sub(_delta);
_add(self, level, ancestorKey, _time, newValue);
}
// Check if there was an overflow. Note that we only need to check the value stored in the root since the
// sum only increases going up through the tree.
require(!_positive || getNode(self, currentHeight, ancestorKey) >= _delta, ERROR_UPDATE_OVERFLOW);
}
/**
* @dev Private function to add a new level to the tree based on a new key that will be inserted
* @param _newKey New key willing to be inserted in the tree
* @param _time Point in time when the new key will be inserted
*/
function _addLevelIfNecessary(Tree storage self, uint256 _newKey, uint64 _time) private {
uint256 currentHeight = getHeight(self);
if (_shouldAddLevel(currentHeight, _newKey)) {
// Max height allowed for the tree is 64 since we are using node keys of 32 bytes. However, note that we
// are not checking if said limit has been hit when inserting new leaves to the tree, for the purpose of
// this system having 2^256 items inserted is unrealistic.
uint256 newHeight = currentHeight + 1;
uint256 rootValue = getNode(self, currentHeight, BASE_KEY);
_add(self, newHeight, BASE_KEY, _time, rootValue);
self.height.add(_time, newHeight);
}
}
/**
* @dev Private function to register a new value in the history of a node at a given point in time
* @param _level Level of the node to add a new value at a given point in time to
* @param _key Key of the node to add a new value at a given point in time to
* @param _time Point in time to register a value for the given node
* @param _value Numeric value to be registered for the given node at a given point in time
*/
function _add(Tree storage self, uint256 _level, uint256 _key, uint64 _time, uint256 _value) private {
self.nodes[_level][_key].add(_time, _value);
}
/**
* @dev Recursive pre-order traversal function
* Every time it checks a node, it traverses the input array to find the initial subset of elements that are
* below its accumulated value and passes that sub-array to the next iteration. Actually, the array is always
* the same, to avoid making extra copies, it just passes the number of values already found , to avoid
* checking values that went through a different branch. The same happens with the result lists of keys and
* values, these are the same on every recursion step. The visited total is carried over each iteration to
* avoid having to subtract all elements in the array.
* @param _values Ordered list of values to be searched in the tree
* @param _params Search parameters for the current recursive step
* @param _resultKeys List of keys found for each requested value in the same order
* @param _resultValues List of node values found for each requested value in the same order
*/
function _search(
Tree storage self,
uint256[] memory _values,
SearchParams memory _params,
uint256[] memory _resultKeys,
uint256[] memory _resultValues
)
private
view
{
uint256 levelKeyLessSignificantNibble = _params.level.mul(BITS_IN_NIBBLE);
for (uint256 childNumber = 0; childNumber < CHILDREN; childNumber++) {
// Return if we already found enough values
if (_params.foundValues >= _values.length) {
break;
}
// Build child node key shifting the child number to the position of the less significant nibble of
// the keys for the level being analyzed, and adding it to the key of the parent node. For example,
// for a tree with height 5, if we are checking the children of the second node of the level 3, whose
// key is 0x0000000000000000000000000000000000000000000000000000000000001000, its children keys are:
// Child 0: 0x0000000000000000000000000000000000000000000000000000000000001000
// Child 1: 0x0000000000000000000000000000000000000000000000000000000000001100
// Child 2: 0x0000000000000000000000000000000000000000000000000000000000001200
// ...
// Child 15: 0x0000000000000000000000000000000000000000000000000000000000001f00
uint256 childNodeKey = _params.parentKey.add(childNumber << levelKeyLessSignificantNibble);
uint256 childNodeValue = getRecentNodeAt(self, _params.level, childNodeKey, _params.time);
// Check how many values belong to the subtree of this node. As they are ordered, it will be a contiguous
// subset starting from the beginning, so we only need to know the length of that subset.
uint256 newVisitedTotal = _params.visitedTotal.add(childNodeValue);
uint256 subtreeIncludedValues = _getValuesIncludedInSubtree(_values, _params.foundValues, newVisitedTotal);
// If there are some values included in the subtree of the child node, visit them
if (subtreeIncludedValues > 0) {
// If the child node being analyzed is a leaf, add it to the list of results a number of times equals
// to the number of values that were included in it. Otherwise, descend one level.
if (_params.level == ITEMS_LEVEL) {
_copyFoundNode(_params.foundValues, subtreeIncludedValues, childNodeKey, _resultKeys, childNodeValue, _resultValues);
} else {
SearchParams memory nextLevelParams = SearchParams(
_params.time,
_params.level - 1, // No need for SafeMath: we already checked above that the level being checked is greater than zero
childNodeKey,
_params.foundValues,
_params.visitedTotal
);
_search(self, _values, nextLevelParams, _resultKeys, _resultValues);
}
// Update the number of values that were already found
_params.foundValues = _params.foundValues.add(subtreeIncludedValues);
}
// Update the visited total for the next node in this level
_params.visitedTotal = newVisitedTotal;
}
}
/**
* @dev Private function to check if a new key can be added to the tree based on the current height of the tree
* @param _currentHeight Current height of the tree to check if it supports adding the given key
* @param _newKey Key willing to be added to the tree with the given current height
* @return True if the current height of the tree should be increased to add the new key, false otherwise.
*/
function _shouldAddLevel(uint256 _currentHeight, uint256 _newKey) private pure returns (bool) {
// Build a mask that will match all the possible keys for the given height. For example:
// Height 1: 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0 (up to 16 keys)
// Height 2: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 (up to 32 keys)
// ...
// Height 64: 0x0000000000000000000000000000000000000000000000000000000000000000 (up to 16^64 keys - tree max height)
uint256 shift = _currentHeight.mul(BITS_IN_NIBBLE);
uint256 mask = uint256(-1) << shift;
// Check if the given key can be represented in the tree with the current given height using the mask.
return (_newKey & mask) != 0;
}
/**
* @dev Private function to tell how many values of a list can be found in a subtree
* @param _values List of values being searched in ascending order
* @param _foundValues Number of values that were already found and should be ignore
* @param _subtreeTotal Total sum of the given subtree to check the numbers that are included in it
* @return Number of values in the list that are included in the given subtree
*/
function _getValuesIncludedInSubtree(uint256[] memory _values, uint256 _foundValues, uint256 _subtreeTotal) private pure returns (uint256) {
// Look for all the values that can be found in the given subtree
uint256 i = _foundValues;
while (i < _values.length && _values[i] < _subtreeTotal) {
i++;
}
return i - _foundValues;
}
/**
* @dev Private function to copy a node a given number of times to a results list. This function assumes the given
* results list have enough size to support the requested copy.
* @param _from Index of the results list to start copying the given node
* @param _times Number of times the given node will be copied
* @param _key Key of the node to be copied
* @param _resultKeys Lists of key results to copy the given node key to
* @param _value Value of the node to be copied
* @param _resultValues Lists of value results to copy the given node value to
*/
function _copyFoundNode(
uint256 _from,
uint256 _times,
uint256 _key,
uint256[] memory _resultKeys,
uint256 _value,
uint256[] memory _resultValues
)
private
pure
{
for (uint256 i = 0; i < _times; i++) {
_resultKeys[_from + i] = _key;
_resultValues[_from + i] = _value;
}
}
}
/**
* @title GuardiansTreeSortition - Library to perform guardians sortition over a `HexSumTree`
*/
library GuardiansTreeSortition {
using SafeMath for uint256;
using HexSumTree for HexSumTree.Tree;
string private constant ERROR_INVALID_INTERVAL_SEARCH = "TREE_INVALID_INTERVAL_SEARCH";
string private constant ERROR_SORTITION_LENGTHS_MISMATCH = "TREE_SORTITION_LENGTHS_MISMATCH";
/**
* @dev Search random items in the tree based on certain restrictions
* @param _termRandomness Randomness to compute the seed for the draft
* @param _disputeId Identification number of the dispute to draft guardians for
* @param _termId Current term when the draft is being computed
* @param _selectedGuardians Number of guardians already selected for the draft
* @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft
* @param _roundRequestedGuardians Total number of guardians requested to be drafted
* @param _sortitionIteration Number of sortitions already performed for the given draft
* @return guardiansIds List of guardian ids obtained based on the requested search
* @return guardiansBalances List of active balances for each guardian obtained based on the requested search
*/
function batchedRandomSearch(
HexSumTree.Tree storage tree,
bytes32 _termRandomness,
uint256 _disputeId,
uint64 _termId,
uint256 _selectedGuardians,
uint256 _batchRequestedGuardians,
uint256 _roundRequestedGuardians,
uint256 _sortitionIteration
)
internal
view
returns (uint256[] memory guardiansIds, uint256[] memory guardiansBalances)
{
(uint256 low, uint256 high) = getSearchBatchBounds(
tree,
_termId,
_selectedGuardians,
_batchRequestedGuardians,
_roundRequestedGuardians
);
uint256[] memory balances = _computeSearchRandomBalances(
_termRandomness,
_disputeId,
_sortitionIteration,
_batchRequestedGuardians,
low,
high
);
(guardiansIds, guardiansBalances) = tree.search(balances, _termId);
require(guardiansIds.length == guardiansBalances.length, ERROR_SORTITION_LENGTHS_MISMATCH);
require(guardiansIds.length == _batchRequestedGuardians, ERROR_SORTITION_LENGTHS_MISMATCH);
}
/**
* @dev Get the bounds for a draft batch based on the active balances of the guardians
* @param _termId Term ID of the active balances that will be used to compute the boundaries
* @param _selectedGuardians Number of guardians already selected for the draft
* @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft
* @param _roundRequestedGuardians Total number of guardians requested to be drafted
* @return low Low bound to be used for the sortition to draft the requested number of guardians for the given batch
* @return high High bound to be used for the sortition to draft the requested number of guardians for the given batch
*/
function getSearchBatchBounds(
HexSumTree.Tree storage tree,
uint64 _termId,
uint256 _selectedGuardians,
uint256 _batchRequestedGuardians,
uint256 _roundRequestedGuardians
)
internal
view
returns (uint256 low, uint256 high)
{
uint256 totalActiveBalance = tree.getRecentTotalAt(_termId);
low = _selectedGuardians.mul(totalActiveBalance).div(_roundRequestedGuardians);
uint256 newSelectedGuardians = _selectedGuardians.add(_batchRequestedGuardians);
high = newSelectedGuardians.mul(totalActiveBalance).div(_roundRequestedGuardians);
}
/**
* @dev Get a random list of active balances to be searched in the guardians tree for a given draft batch
* @param _termRandomness Randomness to compute the seed for the draft
* @param _disputeId Identification number of the dispute to draft guardians for (for randomness)
* @param _sortitionIteration Number of sortitions already performed for the given draft (for randomness)
* @param _batchRequestedGuardians Number of guardians to be selected in the given batch of the draft
* @param _lowBatchBound Low bound to be used for the sortition batch to draft the requested number of guardians
* @param _highBatchBound High bound to be used for the sortition batch to draft the requested number of guardians
* @return Random list of active balances to be searched in the guardians tree for the given draft batch
*/
function _computeSearchRandomBalances(
bytes32 _termRandomness,
uint256 _disputeId,
uint256 _sortitionIteration,
uint256 _batchRequestedGuardians,
uint256 _lowBatchBound,
uint256 _highBatchBound
)
internal
pure
returns (uint256[] memory)
{
// Calculate the interval to be used to search the balances in the tree. Since we are using a modulo function to compute the
// random balances to be searched, intervals will be closed on the left and open on the right, for example [0,10).
require(_highBatchBound > _lowBatchBound, ERROR_INVALID_INTERVAL_SEARCH);
uint256 interval = _highBatchBound - _lowBatchBound;
// Compute an ordered list of random active balance to be searched in the guardians tree
uint256[] memory balances = new uint256[](_batchRequestedGuardians);
for (uint256 batchGuardianNumber = 0; batchGuardianNumber < _batchRequestedGuardians; batchGuardianNumber++) {
// Compute a random seed using:
// - The inherent randomness associated to the term from blockhash
// - The disputeId, so 2 disputes in the same term will have different outcomes
// - The sortition iteration, to avoid getting stuck if resulting guardians are dismissed due to locked balance
// - The guardian number in this batch
bytes32 seed = keccak256(abi.encodePacked(_termRandomness, _disputeId, _sortitionIteration, batchGuardianNumber));
// Compute a random active balance to be searched in the guardians tree using the generated seed within the
// boundaries computed for the current batch.
balances[batchGuardianNumber] = _lowBatchBound.add(uint256(seed) % interval);
// Make sure it's ordered, flip values if necessary
for (uint256 i = batchGuardianNumber; i > 0 && balances[i] < balances[i - 1]; i--) {
uint256 tmp = balances[i - 1];
balances[i - 1] = balances[i];
balances[i] = tmp;
}
}
return balances;
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface ILockManager {
/**
* @dev Tell whether a user can unlock a certain amount of tokens
*/
function canUnlock(address user, uint256 amount) external view returns (bool);
}
/*
* SPDX-License-Identifier: MIT
*/
interface IGuardiansRegistry {
/**
* @dev Assign a requested amount of guardian tokens to a guardian
* @param _guardian Guardian to add an amount of tokens to
* @param _amount Amount of tokens to be added to the available balance of a guardian
*/
function assignTokens(address _guardian, uint256 _amount) external;
/**
* @dev Burn a requested amount of guardian tokens
* @param _amount Amount of tokens to be burned
*/
function burnTokens(uint256 _amount) external;
/**
* @dev Draft a set of guardians based on given requirements for a term id
* @param _params Array containing draft requirements:
* 0. bytes32 Term randomness
* 1. uint256 Dispute id
* 2. uint64 Current term id
* 3. uint256 Number of seats already filled
* 4. uint256 Number of seats left to be filled
* 5. uint64 Number of guardians required for the draft
* 6. uint16 Permyriad of the minimum active balance to be locked for the draft
*
* @return guardians List of guardians selected for the draft
* @return length Size of the list of the draft result
*/
function draft(uint256[7] calldata _params) external returns (address[] memory guardians, uint256 length);
/**
* @dev Slash a set of guardians based on their votes compared to the winning ruling
* @param _termId Current term id
* @param _guardians List of guardian addresses to be slashed
* @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned
* @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not
* @return Total amount of slashed tokens
*/
function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians)
external
returns (uint256 collectedTokens);
/**
* @dev Try to collect a certain amount of tokens from a guardian for the next term
* @param _guardian Guardian to collect the tokens from
* @param _amount Amount of tokens to be collected from the given guardian and for the requested term id
* @param _termId Current term id
* @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise
*/
function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external returns (bool);
/**
* @dev Lock a guardian's withdrawals until a certain term ID
* @param _guardian Address of the guardian to be locked
* @param _termId Term ID until which the guardian's withdrawals will be locked
*/
function lockWithdrawals(address _guardian, uint64 _termId) external;
/**
* @dev Tell the active balance of a guardian for a given term id
* @param _guardian Address of the guardian querying the active balance of
* @param _termId Term ID querying the active balance for
* @return Amount of active tokens for guardian in the requested past term id
*/
function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256);
/**
* @dev Tell the total amount of active guardian tokens at the given term id
* @param _termId Term ID querying the total active balance for
* @return Total amount of active guardian tokens at the given term id
*/
function totalActiveBalanceAt(uint64 _termId) external view returns (uint256);
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/IsContract.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
contract IsContract {
/*
* NOTE: this should NEVER be used for authentication
* (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
*
* This is only intended to be used as a sanity check that an address is actually a contract,
* RATHER THAN an address not being a contract.
*/
function isContract(address _target) internal view returns (bool) {
if (_target == address(0)) {
return false;
}
uint256 size;
assembly { size := extcodesize(_target) }
return size > 0;
}
}
contract ACL {
string private constant ERROR_BAD_FREEZE = "ACL_BAD_FREEZE";
string private constant ERROR_ROLE_ALREADY_FROZEN = "ACL_ROLE_ALREADY_FROZEN";
string private constant ERROR_INVALID_BULK_INPUT = "ACL_INVALID_BULK_INPUT";
enum BulkOp { Grant, Revoke, Freeze }
address internal constant FREEZE_FLAG = address(1);
address internal constant ANY_ADDR = address(-1);
// List of all roles assigned to different addresses
mapping (bytes32 => mapping (address => bool)) public roles;
event Granted(bytes32 indexed id, address indexed who);
event Revoked(bytes32 indexed id, address indexed who);
event Frozen(bytes32 indexed id);
/**
* @dev Tell whether an address has a role assigned
* @param _who Address being queried
* @param _id ID of the role being checked
* @return True if the requested address has assigned the given role, false otherwise
*/
function hasRole(address _who, bytes32 _id) public view returns (bool) {
return roles[_id][_who] || roles[_id][ANY_ADDR];
}
/**
* @dev Tell whether a role is frozen
* @param _id ID of the role being checked
* @return True if the given role is frozen, false otherwise
*/
function isRoleFrozen(bytes32 _id) public view returns (bool) {
return roles[_id][FREEZE_FLAG];
}
/**
* @dev Internal function to grant a role to a given address
* @param _id ID of the role to be granted
* @param _who Address to grant the role to
*/
function _grant(bytes32 _id, address _who) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
require(_who != FREEZE_FLAG, ERROR_BAD_FREEZE);
if (!hasRole(_who, _id)) {
roles[_id][_who] = true;
emit Granted(_id, _who);
}
}
/**
* @dev Internal function to revoke a role from a given address
* @param _id ID of the role to be revoked
* @param _who Address to revoke the role from
*/
function _revoke(bytes32 _id, address _who) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
if (hasRole(_who, _id)) {
roles[_id][_who] = false;
emit Revoked(_id, _who);
}
}
/**
* @dev Internal function to freeze a role
* @param _id ID of the role to be frozen
*/
function _freeze(bytes32 _id) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
roles[_id][FREEZE_FLAG] = true;
emit Frozen(_id);
}
/**
* @dev Internal function to enact a bulk list of ACL operations
*/
function _bulk(BulkOp[] memory _op, bytes32[] memory _id, address[] memory _who) internal {
require(_op.length == _id.length && _op.length == _who.length, ERROR_INVALID_BULK_INPUT);
for (uint256 i = 0; i < _op.length; i++) {
BulkOp op = _op[i];
if (op == BulkOp.Grant) {
_grant(_id[i], _who[i]);
} else if (op == BulkOp.Revoke) {
_revoke(_id[i], _who[i]);
} else if (op == BulkOp.Freeze) {
_freeze(_id[i]);
}
}
}
}
contract ModuleIds {
// DisputeManager module ID - keccak256(abi.encodePacked("DISPUTE_MANAGER"))
bytes32 internal constant MODULE_ID_DISPUTE_MANAGER = 0x14a6c70f0f6d449c014c7bbc9e68e31e79e8474fb03b7194df83109a2d888ae6;
// GuardiansRegistry module ID - keccak256(abi.encodePacked("GUARDIANS_REGISTRY"))
bytes32 internal constant MODULE_ID_GUARDIANS_REGISTRY = 0x8af7b7118de65da3b974a3fd4b0c702b66442f74b9dff6eaed1037254c0b79fe;
// Voting module ID - keccak256(abi.encodePacked("VOTING"))
bytes32 internal constant MODULE_ID_VOTING = 0x7cbb12e82a6d63ff16fe43977f43e3e2b247ecd4e62c0e340da8800a48c67346;
// PaymentsBook module ID - keccak256(abi.encodePacked("PAYMENTS_BOOK"))
bytes32 internal constant MODULE_ID_PAYMENTS_BOOK = 0xfa275b1417437a2a2ea8e91e9fe73c28eaf0a28532a250541da5ac0d1892b418;
// Treasury module ID - keccak256(abi.encodePacked("TREASURY"))
bytes32 internal constant MODULE_ID_TREASURY = 0x06aa03964db1f7257357ef09714a5f0ca3633723df419e97015e0c7a3e83edb7;
}
interface IModulesLinker {
/**
* @notice Update the implementations of a list of modules
* @param _ids List of IDs of the modules to be updated
* @param _addresses List of module addresses to be updated
*/
function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external;
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath64.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
/**
* @title SafeMath64
* @dev Math operations for uint64 with safety checks that revert on error
*/
library SafeMath64 {
string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint256 c = uint256(_a) * uint256(_b);
require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way)
return uint64(c);
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint64 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint64 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint64 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint64 a, uint64 b) internal pure returns (uint64) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
library Uint256Helpers {
uint256 private constant MAX_UINT8 = uint8(-1);
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG";
string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint8(uint256 a) internal pure returns (uint8) {
require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG);
return uint8(a);
}
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG);
return uint64(a);
}
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/TimeHelpers.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
contract TimeHelpers {
using Uint256Helpers for uint256;
/**
* @dev Returns the current block number.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber() internal view returns (uint256) {
return block.number;
}
/**
* @dev Returns the current block number, converted to uint64.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber64() internal view returns (uint64) {
return getBlockNumber().toUint64();
}
/**
* @dev Returns the current timestamp.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp() internal view returns (uint256) {
return block.timestamp; // solium-disable-line security/no-block-members
}
/**
* @dev Returns the current timestamp, converted to uint64.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp64() internal view returns (uint64) {
return getTimestamp().toUint64();
}
}
interface IClock {
/**
* @dev Ensure that the current term of the clock is up-to-date
* @return Identification number of the current term
*/
function ensureCurrentTerm() external returns (uint64);
/**
* @dev Transition up to a certain number of terms to leave the clock up-to-date
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the term ID after executing the heartbeat transitions
*/
function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64);
/**
* @dev Ensure that a certain term has its randomness set
* @return Randomness of the current term
*/
function ensureCurrentTermRandomness() external returns (bytes32);
/**
* @dev Tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function getLastEnsuredTermId() external view returns (uint64);
/**
* @dev Tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function getCurrentTermId() external view returns (uint64);
/**
* @dev Tell the number of terms the clock should transition to be up-to-date
* @return Number of terms the clock should transition to be up-to-date
*/
function getNeededTermTransitions() external view returns (uint64);
/**
* @dev Tell the information related to a term based on its ID
* @param _termId ID of the term being queried
* @return startTime Term start time
* @return randomnessBN Block number used for randomness in the requested term
* @return randomness Randomness computed for the requested term
*/
function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness);
/**
* @dev Tell the randomness of a term even if it wasn't computed yet
* @param _termId Identification number of the term being queried
* @return Randomness of the requested term
*/
function getTermRandomness(uint64 _termId) external view returns (bytes32);
}
contract CourtClock is IClock, TimeHelpers {
using SafeMath64 for uint64;
string private constant ERROR_TERM_DOES_NOT_EXIST = "CLK_TERM_DOES_NOT_EXIST";
string private constant ERROR_TERM_DURATION_TOO_LONG = "CLK_TERM_DURATION_TOO_LONG";
string private constant ERROR_TERM_RANDOMNESS_NOT_YET = "CLK_TERM_RANDOMNESS_NOT_YET";
string private constant ERROR_TERM_RANDOMNESS_UNAVAILABLE = "CLK_TERM_RANDOMNESS_UNAVAILABLE";
string private constant ERROR_BAD_FIRST_TERM_START_TIME = "CLK_BAD_FIRST_TERM_START_TIME";
string private constant ERROR_TOO_MANY_TRANSITIONS = "CLK_TOO_MANY_TRANSITIONS";
string private constant ERROR_INVALID_TRANSITION_TERMS = "CLK_INVALID_TRANSITION_TERMS";
string private constant ERROR_CANNOT_DELAY_STARTED_COURT = "CLK_CANNOT_DELAY_STARTED_PROT";
string private constant ERROR_CANNOT_DELAY_PAST_START_TIME = "CLK_CANNOT_DELAY_PAST_START_TIME";
// Maximum number of term transitions a callee may have to assume in order to call certain functions that require the Court being up-to-date
uint64 internal constant MAX_AUTO_TERM_TRANSITIONS_ALLOWED = 1;
// Max duration in seconds that a term can last
uint64 internal constant MAX_TERM_DURATION = 365 days;
// Max time until first term starts since contract is deployed
uint64 internal constant MAX_FIRST_TERM_DELAY_PERIOD = 2 * MAX_TERM_DURATION;
struct Term {
uint64 startTime; // Timestamp when the term started
uint64 randomnessBN; // Block number for entropy
bytes32 randomness; // Entropy from randomnessBN block hash
}
// Duration in seconds for each term of the Court
uint64 private termDuration;
// Last ensured term id
uint64 private termId;
// List of Court terms indexed by id
mapping (uint64 => Term) private terms;
event Heartbeat(uint64 previousTermId, uint64 currentTermId);
event StartTimeDelayed(uint64 previousStartTime, uint64 currentStartTime);
/**
* @dev Ensure a certain term has already been processed
* @param _termId Identification number of the term to be checked
*/
modifier termExists(uint64 _termId) {
require(_termId <= termId, ERROR_TERM_DOES_NOT_EXIST);
_;
}
/**
* @dev Constructor function
* @param _termParams Array containing:
* 0. _termDuration Duration in seconds per term
* 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding)
*/
constructor(uint64[2] memory _termParams) public {
uint64 _termDuration = _termParams[0];
uint64 _firstTermStartTime = _termParams[1];
require(_termDuration < MAX_TERM_DURATION, ERROR_TERM_DURATION_TOO_LONG);
require(_firstTermStartTime >= getTimestamp64() + _termDuration, ERROR_BAD_FIRST_TERM_START_TIME);
require(_firstTermStartTime <= getTimestamp64() + MAX_FIRST_TERM_DELAY_PERIOD, ERROR_BAD_FIRST_TERM_START_TIME);
termDuration = _termDuration;
// No need for SafeMath: we already checked values above
terms[0].startTime = _firstTermStartTime - _termDuration;
}
/**
* @notice Ensure that the current term of the Court is up-to-date. If the Court is outdated by more than `MAX_AUTO_TERM_TRANSITIONS_ALLOWED`
* terms, the heartbeat function must be called manually instead.
* @return Identification number of the current term
*/
function ensureCurrentTerm() external returns (uint64) {
return _ensureCurrentTerm();
}
/**
* @notice Transition up to `_maxRequestedTransitions` terms
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the term ID after executing the heartbeat transitions
*/
function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64) {
return _heartbeat(_maxRequestedTransitions);
}
/**
* @notice Ensure that a certain term has its randomness set. As we allow to draft disputes requested for previous terms, if there
* were mined more than 256 blocks for the current term, the blockhash of its randomness BN is no longer available, given
* round will be able to be drafted in the following term.
* @return Randomness of the current term
*/
function ensureCurrentTermRandomness() external returns (bytes32) {
// If the randomness for the given term was already computed, return
uint64 currentTermId = termId;
Term storage term = terms[currentTermId];
bytes32 termRandomness = term.randomness;
if (termRandomness != bytes32(0)) {
return termRandomness;
}
// Compute term randomness
bytes32 newRandomness = _computeTermRandomness(currentTermId);
require(newRandomness != bytes32(0), ERROR_TERM_RANDOMNESS_UNAVAILABLE);
term.randomness = newRandomness;
return newRandomness;
}
/**
* @dev Tell the term duration of the Court
* @return Duration in seconds of the Court term
*/
function getTermDuration() external view returns (uint64) {
return termDuration;
}
/**
* @dev Tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function getLastEnsuredTermId() external view returns (uint64) {
return _lastEnsuredTermId();
}
/**
* @dev Tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function getCurrentTermId() external view returns (uint64) {
return _currentTermId();
}
/**
* @dev Tell the number of terms the Court should transition to be up-to-date
* @return Number of terms the Court should transition to be up-to-date
*/
function getNeededTermTransitions() external view returns (uint64) {
return _neededTermTransitions();
}
/**
* @dev Tell the information related to a term based on its ID. Note that if the term has not been reached, the
* information returned won't be computed yet. This function allows querying future terms that were not computed yet.
* @param _termId ID of the term being queried
* @return startTime Term start time
* @return randomnessBN Block number used for randomness in the requested term
* @return randomness Randomness computed for the requested term
*/
function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness) {
Term storage term = terms[_termId];
return (term.startTime, term.randomnessBN, term.randomness);
}
/**
* @dev Tell the randomness of a term even if it wasn't computed yet
* @param _termId Identification number of the term being queried
* @return Randomness of the requested term
*/
function getTermRandomness(uint64 _termId) external view termExists(_termId) returns (bytes32) {
return _computeTermRandomness(_termId);
}
/**
* @dev Internal function to ensure that the current term of the Court is up-to-date. If the Court is outdated by more than
* `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` terms, the heartbeat function must be called manually.
* @return Identification number of the resultant term ID after executing the corresponding transitions
*/
function _ensureCurrentTerm() internal returns (uint64) {
// Check the required number of transitions does not exceeds the max allowed number to be processed automatically
uint64 requiredTransitions = _neededTermTransitions();
require(requiredTransitions <= MAX_AUTO_TERM_TRANSITIONS_ALLOWED, ERROR_TOO_MANY_TRANSITIONS);
// If there are no transitions pending, return the last ensured term id
if (uint256(requiredTransitions) == 0) {
return termId;
}
// Process transition if there is at least one pending
return _heartbeat(requiredTransitions);
}
/**
* @dev Internal function to transition the Court terms up to a requested number of terms
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the resultant term ID after executing the requested transitions
*/
function _heartbeat(uint64 _maxRequestedTransitions) internal returns (uint64) {
// Transition the minimum number of terms between the amount requested and the amount actually needed
uint64 neededTransitions = _neededTermTransitions();
uint256 transitions = uint256(_maxRequestedTransitions < neededTransitions ? _maxRequestedTransitions : neededTransitions);
require(transitions > 0, ERROR_INVALID_TRANSITION_TERMS);
uint64 blockNumber = getBlockNumber64();
uint64 previousTermId = termId;
uint64 currentTermId = previousTermId;
for (uint256 transition = 1; transition <= transitions; transition++) {
// Term IDs are incremented by one based on the number of time periods since the Court started. Since time is represented in uint64,
// even if we chose the minimum duration possible for a term (1 second), we can ensure terms will never reach 2^64 since time is
// already assumed to fit in uint64.
Term storage previousTerm = terms[currentTermId++];
Term storage currentTerm = terms[currentTermId];
_onTermTransitioned(currentTermId);
// Set the start time of the new term. Note that we are using a constant term duration value to guarantee
// equally long terms, regardless of heartbeats.
currentTerm.startTime = previousTerm.startTime.add(termDuration);
// In order to draft a random number of guardians in a term, we use a randomness factor for each term based on a
// block number that is set once the term has started. Note that this information could not be known beforehand.
currentTerm.randomnessBN = blockNumber + 1;
}
termId = currentTermId;
emit Heartbeat(previousTermId, currentTermId);
return currentTermId;
}
/**
* @dev Internal function to delay the first term start time only if it wasn't reached yet
* @param _newFirstTermStartTime New timestamp in seconds when the court will open
*/
function _delayStartTime(uint64 _newFirstTermStartTime) internal {
require(_currentTermId() == 0, ERROR_CANNOT_DELAY_STARTED_COURT);
Term storage term = terms[0];
uint64 currentFirstTermStartTime = term.startTime.add(termDuration);
require(_newFirstTermStartTime > currentFirstTermStartTime, ERROR_CANNOT_DELAY_PAST_START_TIME);
// No need for SafeMath: we already checked above that `_newFirstTermStartTime` > `currentFirstTermStartTime` >= `termDuration`
term.startTime = _newFirstTermStartTime - termDuration;
emit StartTimeDelayed(currentFirstTermStartTime, _newFirstTermStartTime);
}
/**
* @dev Internal function to notify when a term has been transitioned. This function must be overridden to provide custom behavior.
* @param _termId Identification number of the new current term that has been transitioned
*/
function _onTermTransitioned(uint64 _termId) internal;
/**
* @dev Internal function to tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function _lastEnsuredTermId() internal view returns (uint64) {
return termId;
}
/**
* @dev Internal function to tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function _currentTermId() internal view returns (uint64) {
return termId.add(_neededTermTransitions());
}
/**
* @dev Internal function to tell the number of terms the Court should transition to be up-to-date
* @return Number of terms the Court should transition to be up-to-date
*/
function _neededTermTransitions() internal view returns (uint64) {
// Note that the Court is always initialized providing a start time for the first-term in the future. If that's the case,
// no term transitions are required.
uint64 currentTermStartTime = terms[termId].startTime;
if (getTimestamp64() < currentTermStartTime) {
return uint64(0);
}
// No need for SafeMath: we already know that the start time of the current term is in the past
return (getTimestamp64() - currentTermStartTime) / termDuration;
}
/**
* @dev Internal function to compute the randomness that will be used to draft guardians for the given term. This
* function assumes the given term exists. To determine the randomness factor for a term we use the hash of a
* block number that is set once the term has started to ensure it cannot be known beforehand. Note that the
* hash function being used only works for the 256 most recent block numbers.
* @param _termId Identification number of the term being queried
* @return Randomness computed for the given term
*/
function _computeTermRandomness(uint64 _termId) internal view returns (bytes32) {
Term storage term = terms[_termId];
require(getBlockNumber64() > term.randomnessBN, ERROR_TERM_RANDOMNESS_NOT_YET);
return blockhash(term.randomnessBN);
}
}
interface IConfig {
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
);
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct);
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256);
}
contract CourtConfigData {
struct Config {
FeesConfig fees; // Full fees-related config
DisputesConfig disputes; // Full disputes-related config
uint256 minActiveBalance; // Minimum amount of tokens guardians have to activate to participate in the Court
}
struct FeesConfig {
IERC20 token; // ERC20 token to be used for the fees of the Court
uint16 finalRoundReduction; // Permyriad of fees reduction applied for final appeal round (‱ - 1/10,000)
uint256 guardianFee; // Amount of tokens paid to draft a guardian to adjudicate a dispute
uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians
uint256 settleFee; // Amount of tokens paid per round to cover the costs of slashing guardians
}
struct DisputesConfig {
uint64 evidenceTerms; // Max submitting evidence period duration in terms
uint64 commitTerms; // Committing period duration in terms
uint64 revealTerms; // Revealing period duration in terms
uint64 appealTerms; // Appealing period duration in terms
uint64 appealConfirmTerms; // Confirmation appeal period duration in terms
uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
uint64 firstRoundGuardiansNumber; // Number of guardians drafted on first round
uint64 appealStepFactor; // Factor in which the guardians number is increased on each appeal
uint64 finalRoundLockTerms; // Period a coherent guardian in the final round will remain locked
uint256 maxRegularAppealRounds; // Before the final appeal
uint256 appealCollateralFactor; // Permyriad multiple of dispute fees required to appeal a preliminary ruling (‱ - 1/10,000)
uint256 appealConfirmCollateralFactor; // Permyriad multiple of dispute fees required to confirm appeal (‱ - 1/10,000)
}
struct DraftConfig {
IERC20 feeToken; // ERC20 token to be used for the fees of the Court
uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians
}
}
contract CourtConfig is IConfig, CourtConfigData {
using SafeMath64 for uint64;
using PctHelpers for uint256;
string private constant ERROR_TOO_OLD_TERM = "CONF_TOO_OLD_TERM";
string private constant ERROR_INVALID_PENALTY_PCT = "CONF_INVALID_PENALTY_PCT";
string private constant ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT = "CONF_INVALID_FINAL_ROUND_RED_PCT";
string private constant ERROR_INVALID_MAX_APPEAL_ROUNDS = "CONF_INVALID_MAX_APPEAL_ROUNDS";
string private constant ERROR_LARGE_ROUND_PHASE_DURATION = "CONF_LARGE_ROUND_PHASE_DURATION";
string private constant ERROR_BAD_INITIAL_GUARDIANS_NUMBER = "CONF_BAD_INITIAL_GUARDIAN_NUMBER";
string private constant ERROR_BAD_APPEAL_STEP_FACTOR = "CONF_BAD_APPEAL_STEP_FACTOR";
string private constant ERROR_ZERO_COLLATERAL_FACTOR = "CONF_ZERO_COLLATERAL_FACTOR";
string private constant ERROR_ZERO_MIN_ACTIVE_BALANCE = "CONF_ZERO_MIN_ACTIVE_BALANCE";
// Max number of terms that each of the different adjudication states can last (if lasted 1h, this would be a year)
uint64 internal constant MAX_ADJ_STATE_DURATION = 8670;
// Cap the max number of regular appeal rounds
uint256 internal constant MAX_REGULAR_APPEAL_ROUNDS_LIMIT = 10;
// Future term ID in which a config change has been scheduled
uint64 private configChangeTermId;
// List of all the configs used in the Court
Config[] private configs;
// List of configs indexed by id
mapping (uint64 => uint256) private configIdByTerm;
event NewConfig(uint64 fromTermId, uint64 courtConfigId);
/**
* @dev Constructor function
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
constructor(
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
public
{
// Leave config at index 0 empty for non-scheduled config changes
configs.length = 1;
_setConfig(
0,
0,
_feeToken,
_fees,
_roundStateDurations,
_pcts,
_roundParams,
_appealCollateralParams,
_minActiveBalance
);
}
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
);
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct);
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256);
/**
* @dev Tell the term identification number of the next scheduled config change
* @return Term identification number of the next scheduled config change
*/
function getConfigChangeTermId() external view returns (uint64) {
return configChangeTermId;
}
/**
* @dev Internal to make sure to set a config for the new term, it will copy the previous term config if none
* @param _termId Identification number of the new current term that has been transitioned
*/
function _ensureTermConfig(uint64 _termId) internal {
// If the term being transitioned had no config change scheduled, keep the previous one
uint256 currentConfigId = configIdByTerm[_termId];
if (currentConfigId == 0) {
uint256 previousConfigId = configIdByTerm[_termId.sub(1)];
configIdByTerm[_termId] = previousConfigId;
}
}
/**
* @dev Assumes that sender it's allowed (either it's from governor or it's on init)
* @param _termId Identification number of the current Court term
* @param _fromTermId Identification number of the term in which the config will be effective at
* @param _feeToken Address of the token contract that is used to pay for fees.
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function _setConfig(
uint64 _termId,
uint64 _fromTermId,
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
internal
{
// If the current term is not zero, changes must be scheduled at least after the current period.
// No need to ensure delays for on-going disputes since these already use their creation term for that.
require(_termId == 0 || _fromTermId > _termId, ERROR_TOO_OLD_TERM);
// Make sure appeal collateral factors are greater than zero
require(_appealCollateralParams[0] > 0 && _appealCollateralParams[1] > 0, ERROR_ZERO_COLLATERAL_FACTOR);
// Make sure the given penalty and final round reduction pcts are not greater than 100%
require(PctHelpers.isValid(_pcts[0]), ERROR_INVALID_PENALTY_PCT);
require(PctHelpers.isValid(_pcts[1]), ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT);
// Disputes must request at least one guardian to be drafted initially
require(_roundParams[0] > 0, ERROR_BAD_INITIAL_GUARDIANS_NUMBER);
// Prevent that further rounds have zero guardians
require(_roundParams[1] > 0, ERROR_BAD_APPEAL_STEP_FACTOR);
// Make sure the max number of appeals allowed does not reach the limit
uint256 _maxRegularAppealRounds = _roundParams[2];
bool isMaxAppealRoundsValid = _maxRegularAppealRounds > 0 && _maxRegularAppealRounds <= MAX_REGULAR_APPEAL_ROUNDS_LIMIT;
require(isMaxAppealRoundsValid, ERROR_INVALID_MAX_APPEAL_ROUNDS);
// Make sure each adjudication round phase duration is valid
for (uint i = 0; i < _roundStateDurations.length; i++) {
require(_roundStateDurations[i] > 0 && _roundStateDurations[i] < MAX_ADJ_STATE_DURATION, ERROR_LARGE_ROUND_PHASE_DURATION);
}
// Make sure min active balance is not zero
require(_minActiveBalance > 0, ERROR_ZERO_MIN_ACTIVE_BALANCE);
// If there was a config change already scheduled, reset it (in that case we will overwrite last array item).
// Otherwise, schedule a new config.
if (configChangeTermId > _termId) {
configIdByTerm[configChangeTermId] = 0;
} else {
configs.length++;
}
uint64 courtConfigId = uint64(configs.length - 1);
Config storage config = configs[courtConfigId];
config.fees = FeesConfig({
token: _feeToken,
guardianFee: _fees[0],
draftFee: _fees[1],
settleFee: _fees[2],
finalRoundReduction: _pcts[1]
});
config.disputes = DisputesConfig({
evidenceTerms: _roundStateDurations[0],
commitTerms: _roundStateDurations[1],
revealTerms: _roundStateDurations[2],
appealTerms: _roundStateDurations[3],
appealConfirmTerms: _roundStateDurations[4],
penaltyPct: _pcts[0],
firstRoundGuardiansNumber: _roundParams[0],
appealStepFactor: _roundParams[1],
maxRegularAppealRounds: _maxRegularAppealRounds,
finalRoundLockTerms: _roundParams[3],
appealCollateralFactor: _appealCollateralParams[0],
appealConfirmCollateralFactor: _appealCollateralParams[1]
});
config.minActiveBalance = _minActiveBalance;
configIdByTerm[_fromTermId] = courtConfigId;
configChangeTermId = _fromTermId;
emit NewConfig(_fromTermId, courtConfigId);
}
/**
* @dev Internal function to get the Court config for a given term
* @param _termId Identification number of the term querying the Court config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function _getConfigAt(uint64 _termId, uint64 _lastEnsuredTermId) internal view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
)
{
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
FeesConfig storage feesConfig = config.fees;
feeToken = feesConfig.token;
fees = [feesConfig.guardianFee, feesConfig.draftFee, feesConfig.settleFee];
DisputesConfig storage disputesConfig = config.disputes;
roundStateDurations = [
disputesConfig.evidenceTerms,
disputesConfig.commitTerms,
disputesConfig.revealTerms,
disputesConfig.appealTerms,
disputesConfig.appealConfirmTerms
];
pcts = [disputesConfig.penaltyPct, feesConfig.finalRoundReduction];
roundParams = [
disputesConfig.firstRoundGuardiansNumber,
disputesConfig.appealStepFactor,
uint64(disputesConfig.maxRegularAppealRounds),
disputesConfig.finalRoundLockTerms
];
appealCollateralParams = [disputesConfig.appealCollateralFactor, disputesConfig.appealConfirmCollateralFactor];
minActiveBalance = config.minActiveBalance;
}
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function _getDraftConfig(uint64 _termId, uint64 _lastEnsuredTermId) internal view
returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct)
{
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
return (config.fees.token, config.fees.draftFee, config.disputes.penaltyPct);
}
/**
* @dev Internal function to get the min active balance config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Minimum amount of guardian tokens that can be activated at the given term
*/
function _getMinActiveBalance(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) {
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
return config.minActiveBalance;
}
/**
* @dev Internal function to get the Court config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Court config for the given term
*/
function _getConfigFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (Config storage) {
uint256 id = _getConfigIdFor(_termId, _lastEnsuredTermId);
return configs[id];
}
/**
* @dev Internal function to get the Court config ID for a given term
* @param _termId Identification number of the term querying the Court config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Identification number of the config for the given terms
*/
function _getConfigIdFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) {
// If the given term is lower or equal to the last ensured Court term, it is safe to use a past Court config
if (_termId <= _lastEnsuredTermId) {
return configIdByTerm[_termId];
}
// If the given term is in the future but there is a config change scheduled before it, use the incoming config
uint64 scheduledChangeTermId = configChangeTermId;
if (scheduledChangeTermId <= _termId) {
return configIdByTerm[scheduledChangeTermId];
}
// If no changes are scheduled, use the Court config of the last ensured term
return configIdByTerm[_lastEnsuredTermId];
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface IArbitrator {
/**
* @dev Create a dispute over the Arbitrable sender with a number of possible rulings
* @param _possibleRulings Number of possible rulings allowed for the dispute
* @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created
* @return Dispute identification number
*/
function createDispute(uint256 _possibleRulings, bytes calldata _metadata) external returns (uint256);
/**
* @dev Submit evidence for a dispute
* @param _disputeId Id of the dispute in the Court
* @param _submitter Address of the account submitting the evidence
* @param _evidence Data submitted for the evidence related to the dispute
*/
function submitEvidence(uint256 _disputeId, address _submitter, bytes calldata _evidence) external;
/**
* @dev Close the evidence period of a dispute
* @param _disputeId Identification number of the dispute to close its evidence submitting period
*/
function closeEvidencePeriod(uint256 _disputeId) external;
/**
* @notice Rule dispute #`_disputeId` if ready
* @param _disputeId Identification number of the dispute to be ruled
* @return subject Subject associated to the dispute
* @return ruling Ruling number computed for the given dispute
*/
function rule(uint256 _disputeId) external returns (address subject, uint256 ruling);
/**
* @dev Tell the dispute fees information to create a dispute
* @return recipient Address where the corresponding dispute fees must be transferred to
* @return feeToken ERC20 token used for the fees
* @return feeAmount Total amount of fees that must be allowed to the recipient
*/
function getDisputeFees() external view returns (address recipient, IERC20 feeToken, uint256 feeAmount);
/**
* @dev Tell the payments recipient address
* @return Address of the payments recipient module
*/
function getPaymentsRecipient() external view returns (address);
}
/*
* SPDX-License-Identifier: MIT
*/
/**
* @dev The Arbitrable instances actually don't require to follow any specific interface.
* Note that this is actually optional, although it does allow the Court to at least have a way to identify a specific set of instances.
*/
contract IArbitrable {
/**
* @dev Emitted when an IArbitrable instance's dispute is ruled by an IArbitrator
* @param arbitrator IArbitrator instance ruling the dispute
* @param disputeId Identification number of the dispute being ruled by the arbitrator
* @param ruling Ruling given by the arbitrator
*/
event Ruled(IArbitrator indexed arbitrator, uint256 indexed disputeId, uint256 ruling);
}
interface IDisputeManager {
enum DisputeState {
PreDraft,
Adjudicating,
Ruled
}
enum AdjudicationState {
Invalid,
Committing,
Revealing,
Appealing,
ConfirmingAppeal,
Ended
}
/**
* @dev Create a dispute to be drafted in a future term
* @param _subject Arbitrable instance creating the dispute
* @param _possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute
* @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created
* @return Dispute identification number
*/
function createDispute(IArbitrable _subject, uint8 _possibleRulings, bytes calldata _metadata) external returns (uint256);
/**
* @dev Submit evidence for a dispute
* @param _subject Arbitrable instance submitting the dispute
* @param _disputeId Identification number of the dispute receiving new evidence
* @param _submitter Address of the account submitting the evidence
* @param _evidence Data submitted for the evidence of the dispute
*/
function submitEvidence(IArbitrable _subject, uint256 _disputeId, address _submitter, bytes calldata _evidence) external;
/**
* @dev Close the evidence period of a dispute
* @param _subject IArbitrable instance requesting to close the evidence submission period
* @param _disputeId Identification number of the dispute to close its evidence submitting period
*/
function closeEvidencePeriod(IArbitrable _subject, uint256 _disputeId) external;
/**
* @dev Draft guardians for the next round of a dispute
* @param _disputeId Identification number of the dispute to be drafted
*/
function draft(uint256 _disputeId) external;
/**
* @dev Appeal round of a dispute in favor of a certain ruling
* @param _disputeId Identification number of the dispute being appealed
* @param _roundId Identification number of the dispute round being appealed
* @param _ruling Ruling appealing a dispute round in favor of
*/
function createAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external;
/**
* @dev Confirm appeal for a round of a dispute in favor of a ruling
* @param _disputeId Identification number of the dispute confirming an appeal of
* @param _roundId Identification number of the dispute round confirming an appeal of
* @param _ruling Ruling being confirmed against a dispute round appeal
*/
function confirmAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external;
/**
* @dev Compute the final ruling for a dispute
* @param _disputeId Identification number of the dispute to compute its final ruling
* @return subject Arbitrable instance associated to the dispute
* @return finalRuling Final ruling decided for the given dispute
*/
function computeRuling(uint256 _disputeId) external returns (IArbitrable subject, uint8 finalRuling);
/**
* @dev Settle penalties for a round of a dispute
* @param _disputeId Identification number of the dispute to settle penalties for
* @param _roundId Identification number of the dispute round to settle penalties for
* @param _guardiansToSettle Maximum number of guardians to be slashed in this call
*/
function settlePenalties(uint256 _disputeId, uint256 _roundId, uint256 _guardiansToSettle) external;
/**
* @dev Claim rewards for a round of a dispute for guardian
* @dev For regular rounds, it will only reward winning guardians
* @param _disputeId Identification number of the dispute to settle rewards for
* @param _roundId Identification number of the dispute round to settle rewards for
* @param _guardian Address of the guardian to settle their rewards
*/
function settleReward(uint256 _disputeId, uint256 _roundId, address _guardian) external;
/**
* @dev Settle appeal deposits for a round of a dispute
* @param _disputeId Identification number of the dispute to settle appeal deposits for
* @param _roundId Identification number of the dispute round to settle appeal deposits for
*/
function settleAppealDeposit(uint256 _disputeId, uint256 _roundId) external;
/**
* @dev Tell the amount of token fees required to create a dispute
* @return feeToken ERC20 token used for the fees
* @return feeAmount Total amount of fees to be paid for a dispute at the given term
*/
function getDisputeFees() external view returns (IERC20 feeToken, uint256 feeAmount);
/**
* @dev Tell information of a certain dispute
* @param _disputeId Identification number of the dispute being queried
* @return subject Arbitrable subject being disputed
* @return possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute
* @return state Current state of the dispute being queried: pre-draft, adjudicating, or ruled
* @return finalRuling The winning ruling in case the dispute is finished
* @return lastRoundId Identification number of the last round created for the dispute
* @return createTermId Identification number of the term when the dispute was created
*/
function getDispute(uint256 _disputeId) external view
returns (IArbitrable subject, uint8 possibleRulings, DisputeState state, uint8 finalRuling, uint256 lastRoundId, uint64 createTermId);
/**
* @dev Tell information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @return draftTerm Term from which the requested round can be drafted
* @return delayedTerms Number of terms the given round was delayed based on its requested draft term id
* @return guardiansNumber Number of guardians requested for the round
* @return selectedGuardians Number of guardians already selected for the requested round
* @return settledPenalties Whether or not penalties have been settled for the requested round
* @return collectedTokens Amount of guardian tokens that were collected from slashed guardians for the requested round
* @return coherentGuardians Number of guardians that voted in favor of the final ruling in the requested round
* @return state Adjudication state of the requested round
*/
function getRound(uint256 _disputeId, uint256 _roundId) external view
returns (
uint64 draftTerm,
uint64 delayedTerms,
uint64 guardiansNumber,
uint64 selectedGuardians,
uint256 guardianFees,
bool settledPenalties,
uint256 collectedTokens,
uint64 coherentGuardians,
AdjudicationState state
);
/**
* @dev Tell appeal-related information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @return maker Address of the account appealing the given round
* @return appealedRuling Ruling confirmed by the appealer of the given round
* @return taker Address of the account confirming the appeal of the given round
* @return opposedRuling Ruling confirmed by the appeal taker of the given round
*/
function getAppeal(uint256 _disputeId, uint256 _roundId) external view
returns (address maker, uint64 appealedRuling, address taker, uint64 opposedRuling);
/**
* @dev Tell information related to the next round due to an appeal of a certain round given.
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round requesting the appeal details of
* @return nextRoundStartTerm Term ID from which the next round will start
* @return nextRoundGuardiansNumber Guardians number for the next round
* @return newDisputeState New state for the dispute associated to the given round after the appeal
* @return feeToken ERC20 token used for the next round fees
* @return guardianFees Total amount of fees to be distributed between the winning guardians of the next round
* @return totalFees Total amount of fees for a regular round at the given term
* @return appealDeposit Amount to be deposit of fees for a regular round at the given term
* @return confirmAppealDeposit Total amount of fees for a regular round at the given term
*/
function getNextRoundDetails(uint256 _disputeId, uint256 _roundId) external view
returns (
uint64 nextRoundStartTerm,
uint64 nextRoundGuardiansNumber,
DisputeState newDisputeState,
IERC20 feeToken,
uint256 totalFees,
uint256 guardianFees,
uint256 appealDeposit,
uint256 confirmAppealDeposit
);
/**
* @dev Tell guardian-related information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @param _guardian Address of the guardian being queried
* @return weight Guardian weight drafted for the requested round
* @return rewarded Whether or not the given guardian was rewarded based on the requested round
*/
function getGuardian(uint256 _disputeId, uint256 _roundId, address _guardian) external view returns (uint64 weight, bool rewarded);
}
contract Controller is IsContract, ModuleIds, CourtClock, CourtConfig, ACL {
string private constant ERROR_SENDER_NOT_GOVERNOR = "CTR_SENDER_NOT_GOVERNOR";
string private constant ERROR_INVALID_GOVERNOR_ADDRESS = "CTR_INVALID_GOVERNOR_ADDRESS";
string private constant ERROR_MODULE_NOT_SET = "CTR_MODULE_NOT_SET";
string private constant ERROR_MODULE_ALREADY_ENABLED = "CTR_MODULE_ALREADY_ENABLED";
string private constant ERROR_MODULE_ALREADY_DISABLED = "CTR_MODULE_ALREADY_DISABLED";
string private constant ERROR_DISPUTE_MANAGER_NOT_ACTIVE = "CTR_DISPUTE_MANAGER_NOT_ACTIVE";
string private constant ERROR_CUSTOM_FUNCTION_NOT_SET = "CTR_CUSTOM_FUNCTION_NOT_SET";
string private constant ERROR_IMPLEMENTATION_NOT_CONTRACT = "CTR_IMPLEMENTATION_NOT_CONTRACT";
string private constant ERROR_INVALID_IMPLS_INPUT_LENGTH = "CTR_INVALID_IMPLS_INPUT_LENGTH";
address private constant ZERO_ADDRESS = address(0);
/**
* @dev Governor of the whole system. Set of three addresses to recover funds, change configuration settings and setup modules
*/
struct Governor {
address funds; // This address can be unset at any time. It is allowed to recover funds from the ControlledRecoverable modules
address config; // This address is meant not to be unset. It is allowed to change the different configurations of the whole system
address modules; // This address can be unset at any time. It is allowed to plug/unplug modules from the system
}
/**
* @dev Module information
*/
struct Module {
bytes32 id; // ID associated to a module
bool disabled; // Whether the module is disabled
}
// Governor addresses of the system
Governor private governor;
// List of current modules registered for the system indexed by ID
mapping (bytes32 => address) internal currentModules;
// List of all historical modules registered for the system indexed by address
mapping (address => Module) internal allModules;
// List of custom function targets indexed by signature
mapping (bytes4 => address) internal customFunctions;
event ModuleSet(bytes32 id, address addr);
event ModuleEnabled(bytes32 id, address addr);
event ModuleDisabled(bytes32 id, address addr);
event CustomFunctionSet(bytes4 signature, address target);
event FundsGovernorChanged(address previousGovernor, address currentGovernor);
event ConfigGovernorChanged(address previousGovernor, address currentGovernor);
event ModulesGovernorChanged(address previousGovernor, address currentGovernor);
/**
* @dev Ensure the msg.sender is the funds governor
*/
modifier onlyFundsGovernor {
require(msg.sender == governor.funds, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the modules governor
*/
modifier onlyConfigGovernor {
require(msg.sender == governor.config, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the modules governor
*/
modifier onlyModulesGovernor {
require(msg.sender == governor.modules, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the given dispute manager is active
*/
modifier onlyActiveDisputeManager(IDisputeManager _disputeManager) {
require(!_isModuleDisabled(address(_disputeManager)), ERROR_DISPUTE_MANAGER_NOT_ACTIVE);
_;
}
/**
* @dev Constructor function
* @param _termParams Array containing:
* 0. _termDuration Duration in seconds per term
* 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding)
* @param _governors Array containing:
* 0. _fundsGovernor Address of the funds governor
* 1. _configGovernor Address of the config governor
* 2. _modulesGovernor Address of the modules governor
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling
* 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
constructor(
uint64[2] memory _termParams,
address[3] memory _governors,
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
public
CourtClock(_termParams)
CourtConfig(_feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance)
{
_setFundsGovernor(_governors[0]);
_setConfigGovernor(_governors[1]);
_setModulesGovernor(_governors[2]);
}
/**
* @dev Fallback function allows to forward calls to a specific address in case it was previously registered
* Note the sender will be always the controller in case it is forwarded
*/
function () external payable {
address target = customFunctions[msg.sig];
require(target != address(0), ERROR_CUSTOM_FUNCTION_NOT_SET);
// solium-disable-next-line security/no-call-value
(bool success,) = address(target).call.value(msg.value)(msg.data);
assembly {
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
let result := success
switch result case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
/**
* @notice Change Court configuration params
* @param _fromTermId Identification number of the term in which the config will be effective at
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling
* 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function setConfig(
uint64 _fromTermId,
IERC20 _feeToken,
uint256[3] calldata _fees,
uint64[5] calldata _roundStateDurations,
uint16[2] calldata _pcts,
uint64[4] calldata _roundParams,
uint256[2] calldata _appealCollateralParams,
uint256 _minActiveBalance
)
external
onlyConfigGovernor
{
uint64 currentTermId = _ensureCurrentTerm();
_setConfig(
currentTermId,
_fromTermId,
_feeToken,
_fees,
_roundStateDurations,
_pcts,
_roundParams,
_appealCollateralParams,
_minActiveBalance
);
}
/**
* @notice Delay the Court start time to `_newFirstTermStartTime`
* @param _newFirstTermStartTime New timestamp in seconds when the court will open
*/
function delayStartTime(uint64 _newFirstTermStartTime) external onlyConfigGovernor {
_delayStartTime(_newFirstTermStartTime);
}
/**
* @notice Change funds governor address to `_newFundsGovernor`
* @param _newFundsGovernor Address of the new funds governor to be set
*/
function changeFundsGovernor(address _newFundsGovernor) external onlyFundsGovernor {
require(_newFundsGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setFundsGovernor(_newFundsGovernor);
}
/**
* @notice Change config governor address to `_newConfigGovernor`
* @param _newConfigGovernor Address of the new config governor to be set
*/
function changeConfigGovernor(address _newConfigGovernor) external onlyConfigGovernor {
require(_newConfigGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setConfigGovernor(_newConfigGovernor);
}
/**
* @notice Change modules governor address to `_newModulesGovernor`
* @param _newModulesGovernor Address of the new governor to be set
*/
function changeModulesGovernor(address _newModulesGovernor) external onlyModulesGovernor {
require(_newModulesGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setModulesGovernor(_newModulesGovernor);
}
/**
* @notice Remove the funds governor. Set the funds governor to the zero address.
* @dev This action cannot be rolled back, once the funds governor has been unset, funds cannot be recovered from recoverable modules anymore
*/
function ejectFundsGovernor() external onlyFundsGovernor {
_setFundsGovernor(ZERO_ADDRESS);
}
/**
* @notice Remove the modules governor. Set the modules governor to the zero address.
* @dev This action cannot be rolled back, once the modules governor has been unset, system modules cannot be changed anymore
*/
function ejectModulesGovernor() external onlyModulesGovernor {
_setModulesGovernor(ZERO_ADDRESS);
}
/**
* @notice Grant `_id` role to `_who`
* @param _id ID of the role to be granted
* @param _who Address to grant the role to
*/
function grant(bytes32 _id, address _who) external onlyConfigGovernor {
_grant(_id, _who);
}
/**
* @notice Revoke `_id` role from `_who`
* @param _id ID of the role to be revoked
* @param _who Address to revoke the role from
*/
function revoke(bytes32 _id, address _who) external onlyConfigGovernor {
_revoke(_id, _who);
}
/**
* @notice Freeze `_id` role
* @param _id ID of the role to be frozen
*/
function freeze(bytes32 _id) external onlyConfigGovernor {
_freeze(_id);
}
/**
* @notice Enact a bulk list of ACL operations
*/
function bulk(BulkOp[] calldata _op, bytes32[] calldata _id, address[] calldata _who) external onlyConfigGovernor {
_bulk(_op, _id, _who);
}
/**
* @notice Set module `_id` to `_addr`
* @param _id ID of the module to be set
* @param _addr Address of the module to be set
*/
function setModule(bytes32 _id, address _addr) external onlyModulesGovernor {
_setModule(_id, _addr);
}
/**
* @notice Set and link many modules at once
* @param _newModuleIds List of IDs of the new modules to be set
* @param _newModuleAddresses List of addresses of the new modules to be set
* @param _newModuleLinks List of IDs of the modules that will be linked in the new modules being set
* @param _currentModulesToBeSynced List of addresses of current modules to be re-linked to the new modules being set
*/
function setModules(
bytes32[] calldata _newModuleIds,
address[] calldata _newModuleAddresses,
bytes32[] calldata _newModuleLinks,
address[] calldata _currentModulesToBeSynced
)
external
onlyModulesGovernor
{
// We only care about the modules being set, links are optional
require(_newModuleIds.length == _newModuleAddresses.length, ERROR_INVALID_IMPLS_INPUT_LENGTH);
// First set the addresses of the new modules or the modules to be updated
for (uint256 i = 0; i < _newModuleIds.length; i++) {
_setModule(_newModuleIds[i], _newModuleAddresses[i]);
}
// Then sync the links of the new modules based on the list of IDs specified (ideally the IDs of their dependencies)
_syncModuleLinks(_newModuleAddresses, _newModuleLinks);
// Finally sync the links of the existing modules to be synced to the new modules being set
_syncModuleLinks(_currentModulesToBeSynced, _newModuleIds);
}
/**
* @notice Sync modules for a list of modules IDs based on their current implementation address
* @param _modulesToBeSynced List of addresses of connected modules to be synced
* @param _idsToBeSet List of IDs of the modules included in the sync
*/
function syncModuleLinks(address[] calldata _modulesToBeSynced, bytes32[] calldata _idsToBeSet)
external
onlyModulesGovernor
{
require(_idsToBeSet.length > 0 && _modulesToBeSynced.length > 0, ERROR_INVALID_IMPLS_INPUT_LENGTH);
_syncModuleLinks(_modulesToBeSynced, _idsToBeSet);
}
/**
* @notice Disable module `_addr`
* @dev Current modules can be disabled to allow pausing the court. However, these can be enabled back again, see `enableModule`
* @param _addr Address of the module to be disabled
*/
function disableModule(address _addr) external onlyModulesGovernor {
Module storage module = allModules[_addr];
_ensureModuleExists(module);
require(!module.disabled, ERROR_MODULE_ALREADY_DISABLED);
module.disabled = true;
emit ModuleDisabled(module.id, _addr);
}
/**
* @notice Enable module `_addr`
* @param _addr Address of the module to be enabled
*/
function enableModule(address _addr) external onlyModulesGovernor {
Module storage module = allModules[_addr];
_ensureModuleExists(module);
require(module.disabled, ERROR_MODULE_ALREADY_ENABLED);
module.disabled = false;
emit ModuleEnabled(module.id, _addr);
}
/**
* @notice Set custom function `_sig` for `_target`
* @param _sig Signature of the function to be set
* @param _target Address of the target implementation to be registered for the given signature
*/
function setCustomFunction(bytes4 _sig, address _target) external onlyModulesGovernor {
customFunctions[_sig] = _target;
emit CustomFunctionSet(_sig, _target);
}
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
)
{
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getConfigAt(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) {
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getDraftConfig(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Identification number of the term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256) {
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getMinActiveBalance(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the address of the funds governor
* @return Address of the funds governor
*/
function getFundsGovernor() external view returns (address) {
return governor.funds;
}
/**
* @dev Tell the address of the config governor
* @return Address of the config governor
*/
function getConfigGovernor() external view returns (address) {
return governor.config;
}
/**
* @dev Tell the address of the modules governor
* @return Address of the modules governor
*/
function getModulesGovernor() external view returns (address) {
return governor.modules;
}
/**
* @dev Tell if a given module is active
* @param _id ID of the module to be checked
* @param _addr Address of the module to be checked
* @return True if the given module address has the requested ID and is enabled
*/
function isActive(bytes32 _id, address _addr) external view returns (bool) {
Module storage module = allModules[_addr];
return module.id == _id && !module.disabled;
}
/**
* @dev Tell the current ID and disable status of a module based on a given address
* @param _addr Address of the requested module
* @return id ID of the module being queried
* @return disabled Whether the module has been disabled
*/
function getModuleByAddress(address _addr) external view returns (bytes32 id, bool disabled) {
Module storage module = allModules[_addr];
id = module.id;
disabled = module.disabled;
}
/**
* @dev Tell the current address and disable status of a module based on a given ID
* @param _id ID of the module being queried
* @return addr Current address of the requested module
* @return disabled Whether the module has been disabled
*/
function getModule(bytes32 _id) external view returns (address addr, bool disabled) {
return _getModule(_id);
}
/**
* @dev Tell the information for the current DisputeManager module
* @return addr Current address of the DisputeManager module
* @return disabled Whether the module has been disabled
*/
function getDisputeManager() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_DISPUTE_MANAGER);
}
/**
* @dev Tell the information for the current GuardiansRegistry module
* @return addr Current address of the GuardiansRegistry module
* @return disabled Whether the module has been disabled
*/
function getGuardiansRegistry() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_GUARDIANS_REGISTRY);
}
/**
* @dev Tell the information for the current Voting module
* @return addr Current address of the Voting module
* @return disabled Whether the module has been disabled
*/
function getVoting() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_VOTING);
}
/**
* @dev Tell the information for the current PaymentsBook module
* @return addr Current address of the PaymentsBook module
* @return disabled Whether the module has been disabled
*/
function getPaymentsBook() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_PAYMENTS_BOOK);
}
/**
* @dev Tell the information for the current Treasury module
* @return addr Current address of the Treasury module
* @return disabled Whether the module has been disabled
*/
function getTreasury() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_TREASURY);
}
/**
* @dev Tell the target registered for a custom function
* @param _sig Signature of the function being queried
* @return Address of the target where the function call will be forwarded
*/
function getCustomFunction(bytes4 _sig) external view returns (address) {
return customFunctions[_sig];
}
/**
* @dev Internal function to set the address of the funds governor
* @param _newFundsGovernor Address of the new config governor to be set
*/
function _setFundsGovernor(address _newFundsGovernor) internal {
emit FundsGovernorChanged(governor.funds, _newFundsGovernor);
governor.funds = _newFundsGovernor;
}
/**
* @dev Internal function to set the address of the config governor
* @param _newConfigGovernor Address of the new config governor to be set
*/
function _setConfigGovernor(address _newConfigGovernor) internal {
emit ConfigGovernorChanged(governor.config, _newConfigGovernor);
governor.config = _newConfigGovernor;
}
/**
* @dev Internal function to set the address of the modules governor
* @param _newModulesGovernor Address of the new modules governor to be set
*/
function _setModulesGovernor(address _newModulesGovernor) internal {
emit ModulesGovernorChanged(governor.modules, _newModulesGovernor);
governor.modules = _newModulesGovernor;
}
/**
* @dev Internal function to set an address as the current implementation for a module
* Note that the disabled condition is not affected, if the module was not set before it will be enabled by default
* @param _id Id of the module to be set
* @param _addr Address of the module to be set
*/
function _setModule(bytes32 _id, address _addr) internal {
require(isContract(_addr), ERROR_IMPLEMENTATION_NOT_CONTRACT);
currentModules[_id] = _addr;
allModules[_addr].id = _id;
emit ModuleSet(_id, _addr);
}
/**
* @dev Internal function to sync the modules for a list of modules IDs based on their current implementation address
* @param _modulesToBeSynced List of addresses of connected modules to be synced
* @param _idsToBeSet List of IDs of the modules to be linked
*/
function _syncModuleLinks(address[] memory _modulesToBeSynced, bytes32[] memory _idsToBeSet) internal {
address[] memory addressesToBeSet = new address[](_idsToBeSet.length);
// Load the addresses associated with the requested module ids
for (uint256 i = 0; i < _idsToBeSet.length; i++) {
address moduleAddress = _getModuleAddress(_idsToBeSet[i]);
Module storage module = allModules[moduleAddress];
_ensureModuleExists(module);
addressesToBeSet[i] = moduleAddress;
}
// Update the links of all the requested modules
for (uint256 j = 0; j < _modulesToBeSynced.length; j++) {
IModulesLinker(_modulesToBeSynced[j]).linkModules(_idsToBeSet, addressesToBeSet);
}
}
/**
* @dev Internal function to notify when a term has been transitioned
* @param _termId Identification number of the new current term that has been transitioned
*/
function _onTermTransitioned(uint64 _termId) internal {
_ensureTermConfig(_termId);
}
/**
* @dev Internal function to check if a module was set
* @param _module Module to be checked
*/
function _ensureModuleExists(Module storage _module) internal view {
require(_module.id != bytes32(0), ERROR_MODULE_NOT_SET);
}
/**
* @dev Internal function to tell the information for a module based on a given ID
* @param _id ID of the module being queried
* @return addr Current address of the requested module
* @return disabled Whether the module has been disabled
*/
function _getModule(bytes32 _id) internal view returns (address addr, bool disabled) {
addr = _getModuleAddress(_id);
disabled = _isModuleDisabled(addr);
}
/**
* @dev Tell the current address for a module by ID
* @param _id ID of the module being queried
* @return Current address of the requested module
*/
function _getModuleAddress(bytes32 _id) internal view returns (address) {
return currentModules[_id];
}
/**
* @dev Tell whether a module is disabled
* @param _addr Address of the module being queried
* @return True if the module is disabled, false otherwise
*/
function _isModuleDisabled(address _addr) internal view returns (bool) {
return allModules[_addr].disabled;
}
}
contract ConfigConsumer is CourtConfigData {
/**
* @dev Internal function to fetch the address of the Config module from the controller
* @return Address of the Config module
*/
function _courtConfig() internal view returns (IConfig);
/**
* @dev Internal function to get the Court config for a certain term
* @param _termId Identification number of the term querying the Court config of
* @return Court config for the given term
*/
function _getConfigAt(uint64 _termId) internal view returns (Config memory) {
(IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance) = _courtConfig().getConfig(_termId);
Config memory config;
config.fees = FeesConfig({
token: _feeToken,
guardianFee: _fees[0],
draftFee: _fees[1],
settleFee: _fees[2],
finalRoundReduction: _pcts[1]
});
config.disputes = DisputesConfig({
evidenceTerms: _roundStateDurations[0],
commitTerms: _roundStateDurations[1],
revealTerms: _roundStateDurations[2],
appealTerms: _roundStateDurations[3],
appealConfirmTerms: _roundStateDurations[4],
penaltyPct: _pcts[0],
firstRoundGuardiansNumber: _roundParams[0],
appealStepFactor: _roundParams[1],
maxRegularAppealRounds: _roundParams[2],
finalRoundLockTerms: _roundParams[3],
appealCollateralFactor: _appealCollateralParams[0],
appealConfirmCollateralFactor: _appealCollateralParams[1]
});
config.minActiveBalance = _minActiveBalance;
return config;
}
/**
* @dev Internal function to get the draft config for a given term
* @param _termId Identification number of the term querying the draft config of
* @return Draft config for the given term
*/
function _getDraftConfig(uint64 _termId) internal view returns (DraftConfig memory) {
(IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) = _courtConfig().getDraftConfig(_termId);
return DraftConfig({ feeToken: feeToken, draftFee: draftFee, penaltyPct: penaltyPct });
}
/**
* @dev Internal function to get the min active balance config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @return Minimum amount of guardian tokens that can be activated
*/
function _getMinActiveBalance(uint64 _termId) internal view returns (uint256) {
return _courtConfig().getMinActiveBalance(_termId);
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface ICRVotingOwner {
/**
* @dev Ensure votes can be committed for a vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
*/
function ensureCanCommit(uint256 _voteId) external;
/**
* @dev Ensure a certain voter can commit votes for a vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
* @param _voter Address of the voter querying the weight of
*/
function ensureCanCommit(uint256 _voteId, address _voter) external;
/**
* @dev Ensure a certain voter can reveal votes for vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
* @param _voter Address of the voter querying the weight of
* @return Weight of the requested guardian for the requested vote instance
*/
function ensureCanReveal(uint256 _voteId, address _voter) external returns (uint64);
}
/*
* SPDX-License-Identifier: MIT
*/
interface ICRVoting {
/**
* @dev Create a new vote instance
* @dev This function can only be called by the CRVoting owner
* @param _voteId ID of the new vote instance to be created
* @param _possibleOutcomes Number of possible outcomes for the new vote instance to be created
*/
function createVote(uint256 _voteId, uint8 _possibleOutcomes) external;
/**
* @dev Get the winning outcome of a vote instance
* @param _voteId ID of the vote instance querying the winning outcome of
* @return Winning outcome of the given vote instance or refused in case it's missing
*/
function getWinningOutcome(uint256 _voteId) external view returns (uint8);
/**
* @dev Get the tally of an outcome for a certain vote instance
* @param _voteId ID of the vote instance querying the tally of
* @param _outcome Outcome querying the tally of
* @return Tally of the outcome being queried for the given vote instance
*/
function getOutcomeTally(uint256 _voteId, uint8 _outcome) external view returns (uint256);
/**
* @dev Tell whether an outcome is valid for a given vote instance or not
* @param _voteId ID of the vote instance to check the outcome of
* @param _outcome Outcome to check if valid or not
* @return True if the given outcome is valid for the requested vote instance, false otherwise
*/
function isValidOutcome(uint256 _voteId, uint8 _outcome) external view returns (bool);
/**
* @dev Get the outcome voted by a voter for a certain vote instance
* @param _voteId ID of the vote instance querying the outcome of
* @param _voter Address of the voter querying the outcome of
* @return Outcome of the voter for the given vote instance
*/
function getVoterOutcome(uint256 _voteId, address _voter) external view returns (uint8);
/**
* @dev Tell whether a voter voted in favor of a certain outcome in a vote instance or not
* @param _voteId ID of the vote instance to query if a voter voted in favor of a certain outcome
* @param _outcome Outcome to query if the given voter voted in favor of
* @param _voter Address of the voter to query if voted in favor of the given outcome
* @return True if the given voter voted in favor of the given outcome, false otherwise
*/
function hasVotedInFavorOf(uint256 _voteId, uint8 _outcome, address _voter) external view returns (bool);
/**
* @dev Filter a list of voters based on whether they voted in favor of a certain outcome in a vote instance or not
* @param _voteId ID of the vote instance to be checked
* @param _outcome Outcome to filter the list of voters of
* @param _voters List of addresses of the voters to be filtered
* @return List of results to tell whether a voter voted in favor of the given outcome or not
*/
function getVotersInFavorOf(uint256 _voteId, uint8 _outcome, address[] calldata _voters) external view returns (bool[] memory);
}
/*
* SPDX-License-Identifier: MIT
*/
interface ITreasury {
/**
* @dev Assign a certain amount of tokens to an account
* @param _token ERC20 token to be assigned
* @param _to Address of the recipient that will be assigned the tokens to
* @param _amount Amount of tokens to be assigned to the recipient
*/
function assign(IERC20 _token, address _to, uint256 _amount) external;
/**
* @dev Withdraw a certain amount of tokens
* @param _token ERC20 token to be withdrawn
* @param _from Address withdrawing the tokens from
* @param _to Address of the recipient that will receive the tokens
* @param _amount Amount of tokens to be withdrawn from the sender
*/
function withdraw(IERC20 _token, address _from, address _to, uint256 _amount) external;
}
/*
* SPDX-License-Identifier: MIT
*/
interface IPaymentsBook {
/**
* @dev Pay an amount of tokens
* @param _token Address of the token being paid
* @param _amount Amount of tokens being paid
* @param _payer Address paying on behalf of
* @param _data Optional data
*/
function pay(address _token, uint256 _amount, address _payer, bytes calldata _data) external payable;
}
contract Controlled is IModulesLinker, IsContract, ModuleIds, ConfigConsumer {
string private constant ERROR_MODULE_NOT_SET = "CTD_MODULE_NOT_SET";
string private constant ERROR_INVALID_MODULES_LINK_INPUT = "CTD_INVALID_MODULES_LINK_INPUT";
string private constant ERROR_CONTROLLER_NOT_CONTRACT = "CTD_CONTROLLER_NOT_CONTRACT";
string private constant ERROR_SENDER_NOT_ALLOWED = "CTD_SENDER_NOT_ALLOWED";
string private constant ERROR_SENDER_NOT_CONTROLLER = "CTD_SENDER_NOT_CONTROLLER";
string private constant ERROR_SENDER_NOT_CONFIG_GOVERNOR = "CTD_SENDER_NOT_CONFIG_GOVERNOR";
string private constant ERROR_SENDER_NOT_ACTIVE_VOTING = "CTD_SENDER_NOT_ACTIVE_VOTING";
string private constant ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER = "CTD_SEND_NOT_ACTIVE_DISPUTE_MGR";
string private constant ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER = "CTD_SEND_NOT_CURRENT_DISPUTE_MGR";
// Address of the controller
Controller public controller;
// List of modules linked indexed by ID
mapping (bytes32 => address) public linkedModules;
event ModuleLinked(bytes32 id, address addr);
/**
* @dev Ensure the msg.sender is the controller's config governor
*/
modifier onlyConfigGovernor {
require(msg.sender == _configGovernor(), ERROR_SENDER_NOT_CONFIG_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the controller
*/
modifier onlyController() {
require(msg.sender == address(controller), ERROR_SENDER_NOT_CONTROLLER);
_;
}
/**
* @dev Ensure the msg.sender is an active DisputeManager module
*/
modifier onlyActiveDisputeManager() {
require(controller.isActive(MODULE_ID_DISPUTE_MANAGER, msg.sender), ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER);
_;
}
/**
* @dev Ensure the msg.sender is the current DisputeManager module
*/
modifier onlyCurrentDisputeManager() {
(address addr, bool disabled) = controller.getDisputeManager();
require(msg.sender == addr, ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER);
require(!disabled, ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER);
_;
}
/**
* @dev Ensure the msg.sender is an active Voting module
*/
modifier onlyActiveVoting() {
require(controller.isActive(MODULE_ID_VOTING, msg.sender), ERROR_SENDER_NOT_ACTIVE_VOTING);
_;
}
/**
* @dev This modifier will check that the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
*/
modifier authenticateSender(address _user) {
_authenticateSender(_user);
_;
}
/**
* @dev Constructor function
* @param _controller Address of the controller
*/
constructor(Controller _controller) public {
require(isContract(address(_controller)), ERROR_CONTROLLER_NOT_CONTRACT);
controller = _controller;
}
/**
* @notice Update the implementation links of a list of modules
* @dev The controller is expected to ensure the given addresses are correct modules
* @param _ids List of IDs of the modules to be updated
* @param _addresses List of module addresses to be updated
*/
function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external onlyController {
require(_ids.length == _addresses.length, ERROR_INVALID_MODULES_LINK_INPUT);
for (uint256 i = 0; i < _ids.length; i++) {
linkedModules[_ids[i]] = _addresses[i];
emit ModuleLinked(_ids[i], _addresses[i]);
}
}
/**
* @dev Internal function to ensure the Court term is up-to-date, it will try to update it if not
* @return Identification number of the current Court term
*/
function _ensureCurrentTerm() internal returns (uint64) {
return _clock().ensureCurrentTerm();
}
/**
* @dev Internal function to fetch the last ensured term ID of the Court
* @return Identification number of the last ensured term
*/
function _getLastEnsuredTermId() internal view returns (uint64) {
return _clock().getLastEnsuredTermId();
}
/**
* @dev Internal function to tell the current term identification number
* @return Identification number of the current term
*/
function _getCurrentTermId() internal view returns (uint64) {
return _clock().getCurrentTermId();
}
/**
* @dev Internal function to fetch the controller's config governor
* @return Address of the controller's config governor
*/
function _configGovernor() internal view returns (address) {
return controller.getConfigGovernor();
}
/**
* @dev Internal function to fetch the address of the DisputeManager module
* @return Address of the DisputeManager module
*/
function _disputeManager() internal view returns (IDisputeManager) {
return IDisputeManager(_getLinkedModule(MODULE_ID_DISPUTE_MANAGER));
}
/**
* @dev Internal function to fetch the address of the GuardianRegistry module implementation
* @return Address of the GuardianRegistry module implementation
*/
function _guardiansRegistry() internal view returns (IGuardiansRegistry) {
return IGuardiansRegistry(_getLinkedModule(MODULE_ID_GUARDIANS_REGISTRY));
}
/**
* @dev Internal function to fetch the address of the Voting module implementation
* @return Address of the Voting module implementation
*/
function _voting() internal view returns (ICRVoting) {
return ICRVoting(_getLinkedModule(MODULE_ID_VOTING));
}
/**
* @dev Internal function to fetch the address of the PaymentsBook module implementation
* @return Address of the PaymentsBook module implementation
*/
function _paymentsBook() internal view returns (IPaymentsBook) {
return IPaymentsBook(_getLinkedModule(MODULE_ID_PAYMENTS_BOOK));
}
/**
* @dev Internal function to fetch the address of the Treasury module implementation
* @return Address of the Treasury module implementation
*/
function _treasury() internal view returns (ITreasury) {
return ITreasury(_getLinkedModule(MODULE_ID_TREASURY));
}
/**
* @dev Internal function to tell the address linked for a module based on a given ID
* @param _id ID of the module being queried
* @return Linked address of the requested module
*/
function _getLinkedModule(bytes32 _id) internal view returns (address) {
address module = linkedModules[_id];
require(module != address(0), ERROR_MODULE_NOT_SET);
return module;
}
/**
* @dev Internal function to fetch the address of the Clock module from the controller
* @return Address of the Clock module
*/
function _clock() internal view returns (IClock) {
return IClock(controller);
}
/**
* @dev Internal function to fetch the address of the Config module from the controller
* @return Address of the Config module
*/
function _courtConfig() internal view returns (IConfig) {
return IConfig(controller);
}
/**
* @dev Ensure that the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
*/
function _authenticateSender(address _user) internal view {
require(_isSenderAllowed(_user), ERROR_SENDER_NOT_ALLOWED);
}
/**
* @dev Tell whether the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
* @return True if the sender is the user to act on behalf of or someone with the required permission, false otherwise
*/
function _isSenderAllowed(address _user) internal view returns (bool) {
return msg.sender == _user || _hasRole(msg.sender);
}
/**
* @dev Tell whether an address holds the required permission to access the requested functionality
* @param _addr Address being checked
* @return True if the given address has the required permission to access the requested functionality, false otherwise
*/
function _hasRole(address _addr) internal view returns (bool) {
bytes32 roleId = keccak256(abi.encodePacked(address(this), msg.sig));
return controller.hasRole(_addr, roleId);
}
}
contract ControlledRecoverable is Controlled {
using SafeERC20 for IERC20;
string private constant ERROR_SENDER_NOT_FUNDS_GOVERNOR = "CTD_SENDER_NOT_FUNDS_GOVERNOR";
string private constant ERROR_INSUFFICIENT_RECOVER_FUNDS = "CTD_INSUFFICIENT_RECOVER_FUNDS";
string private constant ERROR_RECOVER_TOKEN_FUNDS_FAILED = "CTD_RECOVER_TOKEN_FUNDS_FAILED";
event RecoverFunds(address token, address recipient, uint256 balance);
/**
* @dev Ensure the msg.sender is the controller's funds governor
*/
modifier onlyFundsGovernor {
require(msg.sender == controller.getFundsGovernor(), ERROR_SENDER_NOT_FUNDS_GOVERNOR);
_;
}
/**
* @notice Transfer all `_token` tokens to `_to`
* @param _token Address of the token to be recovered
* @param _to Address of the recipient that will be receive all the funds of the requested token
*/
function recoverFunds(address _token, address payable _to) external payable onlyFundsGovernor {
uint256 balance;
if (_token == address(0)) {
balance = address(this).balance;
require(_to.send(balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED);
} else {
balance = IERC20(_token).balanceOf(address(this));
require(balance > 0, ERROR_INSUFFICIENT_RECOVER_FUNDS);
// No need to verify _token to be a contract as we have already checked the balance
require(IERC20(_token).safeTransfer(_to, balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED);
}
emit RecoverFunds(_token, _to, balance);
}
}
contract GuardiansRegistry is IGuardiansRegistry, ControlledRecoverable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using PctHelpers for uint256;
using HexSumTree for HexSumTree.Tree;
using GuardiansTreeSortition for HexSumTree.Tree;
string private constant ERROR_NOT_CONTRACT = "GR_NOT_CONTRACT";
string private constant ERROR_INVALID_ZERO_AMOUNT = "GR_INVALID_ZERO_AMOUNT";
string private constant ERROR_INVALID_ACTIVATION_AMOUNT = "GR_INVALID_ACTIVATION_AMOUNT";
string private constant ERROR_INVALID_DEACTIVATION_AMOUNT = "GR_INVALID_DEACTIVATION_AMOUNT";
string private constant ERROR_INVALID_LOCKED_AMOUNTS_LENGTH = "GR_INVALID_LOCKED_AMOUNTS_LEN";
string private constant ERROR_INVALID_REWARDED_GUARDIANS_LENGTH = "GR_INVALID_REWARD_GUARDIANS_LEN";
string private constant ERROR_ACTIVE_BALANCE_BELOW_MIN = "GR_ACTIVE_BALANCE_BELOW_MIN";
string private constant ERROR_NOT_ENOUGH_AVAILABLE_BALANCE = "GR_NOT_ENOUGH_AVAILABLE_BALANCE";
string private constant ERROR_CANNOT_REDUCE_DEACTIVATION_REQUEST = "GR_CANT_REDUCE_DEACTIVATION_REQ";
string private constant ERROR_TOKEN_TRANSFER_FAILED = "GR_TOKEN_TRANSFER_FAILED";
string private constant ERROR_TOKEN_APPROVE_NOT_ALLOWED = "GR_TOKEN_APPROVE_NOT_ALLOWED";
string private constant ERROR_BAD_TOTAL_ACTIVE_BALANCE_LIMIT = "GR_BAD_TOTAL_ACTIVE_BAL_LIMIT";
string private constant ERROR_TOTAL_ACTIVE_BALANCE_EXCEEDED = "GR_TOTAL_ACTIVE_BALANCE_EXCEEDED";
string private constant ERROR_DEACTIVATION_AMOUNT_EXCEEDS_LOCK = "GR_DEACTIV_AMOUNT_EXCEEDS_LOCK";
string private constant ERROR_CANNOT_UNLOCK_ACTIVATION = "GR_CANNOT_UNLOCK_ACTIVATION";
string private constant ERROR_ZERO_LOCK_ACTIVATION = "GR_ZERO_LOCK_ACTIVATION";
string private constant ERROR_INVALID_UNLOCK_ACTIVATION_AMOUNT = "GR_INVALID_UNLOCK_ACTIVAT_AMOUNT";
string private constant ERROR_LOCK_MANAGER_NOT_ALLOWED = "GR_LOCK_MANAGER_NOT_ALLOWED";
string private constant ERROR_WITHDRAWALS_LOCK = "GR_WITHDRAWALS_LOCK";
// Address that will be used to burn guardian tokens
address internal constant BURN_ACCOUNT = address(0x000000000000000000000000000000000000dEaD);
// Maximum number of sortition iterations allowed per draft call
uint256 internal constant MAX_DRAFT_ITERATIONS = 10;
// "ERC20-lite" interface to provide help for tooling
string public constant name = "Court Staked Aragon Network Token";
string public constant symbol = "sANT";
uint8 public constant decimals = 18;
/**
* @dev Guardians have three kind of balances, these are:
* - active: tokens activated for the Court that can be locked in case the guardian is drafted
* - locked: amount of active tokens that are locked for a draft
* - available: tokens that are not activated for the Court and can be withdrawn by the guardian at any time
*
* Due to a gas optimization for drafting, the "active" tokens are stored in a `HexSumTree`, while the others
* are stored in this contract as `lockedBalance` and `availableBalance` respectively. Given that the guardians'
* active balances cannot be affected during the current Court term, if guardians want to deactivate some of
* their active tokens, their balance will be updated for the following term, and they won't be allowed to
* withdraw them until the current term has ended.
*
* Note that even though guardians balances are stored separately, all the balances are held by this contract.
*/
struct Guardian {
uint256 id; // Key in the guardians tree used for drafting
uint256 lockedBalance; // Maximum amount of tokens that can be slashed based on the guardian's drafts
uint256 availableBalance; // Available tokens that can be withdrawn at any time
uint64 withdrawalsLockTermId; // Term ID until which the guardian's withdrawals will be locked
ActivationLocks activationLocks; // Guardian's activation locks
DeactivationRequest deactivationRequest; // Guardian's pending deactivation request
}
/**
* @dev Guardians can define lock managers to control their minimum active balance in the registry
*/
struct ActivationLocks {
uint256 total; // Total amount of active balance locked
mapping (address => uint256) lockedBy; // List of locked amounts indexed by lock manager
}
/**
* @dev Given that the guardians balances cannot be affected during a Court term, if guardians want to deactivate some
* of their tokens, the tree will always be updated for the following term, and they won't be able to
* withdraw the requested amount until the current term has finished. Thus, we need to keep track the term
* when a token deactivation was requested and its corresponding amount.
*/
struct DeactivationRequest {
uint256 amount; // Amount requested for deactivation
uint64 availableTermId; // Term ID when guardians can withdraw their requested deactivation tokens
}
/**
* @dev Internal struct to wrap all the params required to perform guardians drafting
*/
struct DraftParams {
bytes32 termRandomness; // Randomness seed to be used for the draft
uint256 disputeId; // ID of the dispute being drafted
uint64 termId; // Term ID of the dispute's draft term
uint256 selectedGuardians; // Number of guardians already selected for the draft
uint256 batchRequestedGuardians; // Number of guardians to be selected in the given batch of the draft
uint256 roundRequestedGuardians; // Total number of guardians requested to be drafted
uint256 draftLockAmount; // Amount of tokens to be locked to each drafted guardian
uint256 iteration; // Sortition iteration number
}
// Maximum amount of total active balance that can be held in the registry
uint256 public totalActiveBalanceLimit;
// Guardian ERC20 token
IERC20 public guardiansToken;
// Mapping of guardian data indexed by address
mapping (address => Guardian) internal guardiansByAddress;
// Mapping of guardian addresses indexed by id
mapping (uint256 => address) internal guardiansAddressById;
// Tree to store guardians active balance by term for the drafting process
HexSumTree.Tree internal tree;
event Staked(address indexed guardian, uint256 amount, uint256 total);
event Unstaked(address indexed guardian, uint256 amount, uint256 total);
event GuardianActivated(address indexed guardian, uint64 fromTermId, uint256 amount);
event GuardianDeactivationRequested(address indexed guardian, uint64 availableTermId, uint256 amount);
event GuardianDeactivationProcessed(address indexed guardian, uint64 availableTermId, uint256 amount, uint64 processedTermId);
event GuardianDeactivationUpdated(address indexed guardian, uint64 availableTermId, uint256 amount, uint64 updateTermId);
event GuardianActivationLockChanged(address indexed guardian, address indexed lockManager, uint256 amount, uint256 total);
event GuardianBalanceLocked(address indexed guardian, uint256 amount);
event GuardianBalanceUnlocked(address indexed guardian, uint256 amount);
event GuardianSlashed(address indexed guardian, uint256 amount, uint64 effectiveTermId);
event GuardianTokensAssigned(address indexed guardian, uint256 amount);
event GuardianTokensBurned(uint256 amount);
event GuardianTokensCollected(address indexed guardian, uint256 amount, uint64 effectiveTermId);
event TotalActiveBalanceLimitChanged(uint256 previousTotalActiveBalanceLimit, uint256 currentTotalActiveBalanceLimit);
/**
* @dev Constructor function
* @param _controller Address of the controller
* @param _guardiansToken Address of the ERC20 token to be used as guardian token for the registry
* @param _totalActiveBalanceLimit Maximum amount of total active balance that can be held in the registry
*/
constructor(Controller _controller, IERC20 _guardiansToken, uint256 _totalActiveBalanceLimit) Controlled(_controller) public {
require(isContract(address(_guardiansToken)), ERROR_NOT_CONTRACT);
guardiansToken = _guardiansToken;
_setTotalActiveBalanceLimit(_totalActiveBalanceLimit);
tree.init();
// First tree item is an empty guardian
assert(tree.insert(0, 0) == 0);
}
/**
* @notice Stake `@tokenAmount(self.token(), _amount)` for `_guardian`
* @param _guardian Address of the guardian to stake tokens to
* @param _amount Amount of tokens to be staked
*/
function stake(address _guardian, uint256 _amount) external {
_stake(_guardian, _amount);
}
/**
* @notice Unstake `@tokenAmount(self.token(), _amount)` from `_guardian`
* @param _guardian Address of the guardian to unstake tokens from
* @param _amount Amount of tokens to be unstaked
*/
function unstake(address _guardian, uint256 _amount) external authenticateSender(_guardian) {
_unstake(_guardian, _amount);
}
/**
* @notice Activate `@tokenAmount(self.token(), _amount)` for `_guardian`
* @param _guardian Address of the guardian activating the tokens for
* @param _amount Amount of guardian tokens to be activated for the next term
*/
function activate(address _guardian, uint256 _amount) external authenticateSender(_guardian) {
_activate(_guardian, _amount);
}
/**
* @notice Deactivate `_amount == 0 ? 'all unlocked tokens' : @tokenAmount(self.token(), _amount)` for `_guardian`
* @param _guardian Address of the guardian deactivating the tokens for
* @param _amount Amount of guardian tokens to be deactivated for the next term
*/
function deactivate(address _guardian, uint256 _amount) external authenticateSender(_guardian) {
_deactivate(_guardian, _amount);
}
/**
* @notice Stake and activate `@tokenAmount(self.token(), _amount)` for `_guardian`
* @param _guardian Address of the guardian staking and activating tokens for
* @param _amount Amount of tokens to be staked and activated
*/
function stakeAndActivate(address _guardian, uint256 _amount) external authenticateSender(_guardian) {
_stake(_guardian, _amount);
_activate(_guardian, _amount);
}
/**
* @notice Lock `@tokenAmount(self.token(), _amount)` of `_guardian`'s active balance
* @param _guardian Address of the guardian locking the activation for
* @param _lockManager Address of the lock manager that will control the lock
* @param _amount Amount of active tokens to be locked
*/
function lockActivation(address _guardian, address _lockManager, uint256 _amount) external {
// Make sure the sender is the guardian, someone allowed by the guardian, or the lock manager itself
bool isLockManagerAllowed = msg.sender == _lockManager || _isSenderAllowed(_guardian);
// Make sure that the given lock manager is allowed
require(isLockManagerAllowed && _hasRole(_lockManager), ERROR_LOCK_MANAGER_NOT_ALLOWED);
_lockActivation(_guardian, _lockManager, _amount);
}
/**
* @notice Unlock `_amount == 0 ? 'all unlocked tokens' : @tokenAmount(self.token(), _amount)` of `_guardian`'s active balance
* @param _guardian Address of the guardian unlocking the active balance of
* @param _lockManager Address of the lock manager controlling the lock
* @param _amount Amount of active tokens to be unlocked
* @param _requestDeactivation Whether the unlocked amount must be requested for deactivation immediately
*/
function unlockActivation(address _guardian, address _lockManager, uint256 _amount, bool _requestDeactivation) external {
ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks;
uint256 lockedAmount = activationLocks.lockedBy[_lockManager];
require(lockedAmount > 0, ERROR_ZERO_LOCK_ACTIVATION);
uint256 amountToUnlock = _amount == 0 ? lockedAmount : _amount;
require(amountToUnlock <= lockedAmount, ERROR_INVALID_UNLOCK_ACTIVATION_AMOUNT);
// Always allow the lock manager to unlock
bool canUnlock = _lockManager == msg.sender || ILockManager(_lockManager).canUnlock(_guardian, amountToUnlock);
require(canUnlock, ERROR_CANNOT_UNLOCK_ACTIVATION);
uint256 newLockedAmount = lockedAmount.sub(amountToUnlock);
uint256 newTotalLocked = activationLocks.total.sub(amountToUnlock);
activationLocks.total = newTotalLocked;
activationLocks.lockedBy[_lockManager] = newLockedAmount;
emit GuardianActivationLockChanged(_guardian, _lockManager, newLockedAmount, newTotalLocked);
// In order to request a deactivation, the request must have been originally authorized from the guardian or someone authorized to do it
if (_requestDeactivation) {
_authenticateSender(_guardian);
_deactivate(_guardian, _amount);
}
}
/**
* @notice Process a token deactivation requested for `_guardian` if there is any
* @param _guardian Address of the guardian to process the deactivation request of
*/
function processDeactivationRequest(address _guardian) external {
uint64 termId = _ensureCurrentTerm();
_processDeactivationRequest(_guardian, termId);
}
/**
* @notice Assign `@tokenAmount(self.token(), _amount)` to the available balance of `_guardian`
* @param _guardian Guardian to add an amount of tokens to
* @param _amount Amount of tokens to be added to the available balance of a guardian
*/
function assignTokens(address _guardian, uint256 _amount) external onlyActiveDisputeManager {
if (_amount > 0) {
_updateAvailableBalanceOf(_guardian, _amount, true);
emit GuardianTokensAssigned(_guardian, _amount);
}
}
/**
* @notice Burn `@tokenAmount(self.token(), _amount)`
* @param _amount Amount of tokens to be burned
*/
function burnTokens(uint256 _amount) external onlyActiveDisputeManager {
if (_amount > 0) {
_updateAvailableBalanceOf(BURN_ACCOUNT, _amount, true);
emit GuardianTokensBurned(_amount);
}
}
/**
* @notice Draft a set of guardians based on given requirements for a term id
* @param _params Array containing draft requirements:
* 0. bytes32 Term randomness
* 1. uint256 Dispute id
* 2. uint64 Current term id
* 3. uint256 Number of seats already filled
* 4. uint256 Number of seats left to be filled
* 5. uint64 Number of guardians required for the draft
* 6. uint16 Permyriad of the minimum active balance to be locked for the draft
*
* @return guardians List of guardians selected for the draft
* @return length Size of the list of the draft result
*/
function draft(uint256[7] calldata _params) external onlyActiveDisputeManager returns (address[] memory guardians, uint256 length) {
DraftParams memory draftParams = _buildDraftParams(_params);
guardians = new address[](draftParams.batchRequestedGuardians);
// Guardians returned by the tree multi-sortition may not have enough unlocked active balance to be drafted. Thus,
// we compute several sortitions until all the requested guardians are selected. To guarantee a different set of
// guardians on each sortition, the iteration number will be part of the random seed to be used in the sortition.
// Note that we are capping the number of iterations to avoid an OOG error, which means that this function could
// return less guardians than the requested number.
for (draftParams.iteration = 0;
length < draftParams.batchRequestedGuardians && draftParams.iteration < MAX_DRAFT_ITERATIONS;
draftParams.iteration++
) {
(uint256[] memory guardianIds, uint256[] memory activeBalances) = _treeSearch(draftParams);
for (uint256 i = 0; i < guardianIds.length && length < draftParams.batchRequestedGuardians; i++) {
// We assume the selected guardians are registered in the registry, we are not checking their addresses exist
address guardianAddress = guardiansAddressById[guardianIds[i]];
Guardian storage guardian = guardiansByAddress[guardianAddress];
// Compute new locked balance for a guardian based on the penalty applied when being drafted
uint256 newLockedBalance = guardian.lockedBalance.add(draftParams.draftLockAmount);
// Check if there is any deactivation requests for the next term. Drafts are always computed for the current term
// but we have to make sure we are locking an amount that will exist in the next term.
uint256 nextTermDeactivationRequestAmount = _deactivationRequestedAmountForTerm(guardian, draftParams.termId + 1);
// Check if guardian has enough active tokens to lock the requested amount for the draft, skip it otherwise.
uint256 currentActiveBalance = activeBalances[i];
if (currentActiveBalance >= newLockedBalance) {
// Check if the amount of active tokens for the next term is enough to lock the required amount for
// the draft. Otherwise, reduce the requested deactivation amount of the next term.
// Next term deactivation amount should always be less than current active balance, but we make sure using SafeMath
uint256 nextTermActiveBalance = currentActiveBalance.sub(nextTermDeactivationRequestAmount);
if (nextTermActiveBalance < newLockedBalance) {
// No need for SafeMath: we already checked values above
_reduceDeactivationRequest(guardianAddress, newLockedBalance - nextTermActiveBalance, draftParams.termId);
}
// Update the current active locked balance of the guardian
guardian.lockedBalance = newLockedBalance;
guardians[length++] = guardianAddress;
emit GuardianBalanceLocked(guardianAddress, draftParams.draftLockAmount);
}
}
}
}
/**
* @notice Slash a set of guardians based on their votes compared to the winning ruling. This function will unlock the
* corresponding locked balances of those guardians that are set to be slashed.
* @param _termId Current term id
* @param _guardians List of guardian addresses to be slashed
* @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned
* @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not
* @return Total amount of slashed tokens
*/
function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians)
external
onlyActiveDisputeManager
returns (uint256)
{
require(_guardians.length == _lockedAmounts.length, ERROR_INVALID_LOCKED_AMOUNTS_LENGTH);
require(_guardians.length == _rewardedGuardians.length, ERROR_INVALID_REWARDED_GUARDIANS_LENGTH);
uint64 nextTermId = _termId + 1;
uint256 collectedTokens;
for (uint256 i = 0; i < _guardians.length; i++) {
uint256 lockedAmount = _lockedAmounts[i];
address guardianAddress = _guardians[i];
Guardian storage guardian = guardiansByAddress[guardianAddress];
guardian.lockedBalance = guardian.lockedBalance.sub(lockedAmount);
// Slash guardian if requested. Note that there's no need to check if there was a deactivation
// request since we're working with already locked balances.
if (_rewardedGuardians[i]) {
emit GuardianBalanceUnlocked(guardianAddress, lockedAmount);
} else {
collectedTokens = collectedTokens.add(lockedAmount);
tree.update(guardian.id, nextTermId, lockedAmount, false);
emit GuardianSlashed(guardianAddress, lockedAmount, nextTermId);
}
}
return collectedTokens;
}
/**
* @notice Try to collect `@tokenAmount(self.token(), _amount)` from `_guardian` for the term #`_termId + 1`.
* @dev This function tries to decrease the active balance of a guardian for the next term based on the requested
* amount. It can be seen as a way to early-slash a guardian's active balance.
* @param _guardian Guardian to collect the tokens from
* @param _amount Amount of tokens to be collected from the given guardian and for the requested term id
* @param _termId Current term id
* @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise
*/
function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external onlyActiveDisputeManager returns (bool) {
if (_amount == 0) {
return true;
}
uint64 nextTermId = _termId + 1;
Guardian storage guardian = guardiansByAddress[_guardian];
uint256 unlockedActiveBalance = _lastUnlockedActiveBalanceOf(guardian);
uint256 nextTermDeactivationRequestAmount = _deactivationRequestedAmountForTerm(guardian, nextTermId);
// Check if the guardian has enough unlocked tokens to collect the requested amount
// Note that we're also considering the deactivation request if there is any
uint256 totalUnlockedActiveBalance = unlockedActiveBalance.add(nextTermDeactivationRequestAmount);
if (_amount > totalUnlockedActiveBalance) {
return false;
}
// Check if the amount of active tokens is enough to collect the requested amount, otherwise reduce the requested deactivation amount of
// the next term. Note that this behaviour is different to the one when drafting guardians since this function is called as a side effect
// of a guardian deliberately voting in a final round, while drafts occur randomly.
if (_amount > unlockedActiveBalance) {
// No need for SafeMath: amounts were already checked above
uint256 amountToReduce = _amount - unlockedActiveBalance;
_reduceDeactivationRequest(_guardian, amountToReduce, _termId);
}
tree.update(guardian.id, nextTermId, _amount, false);
emit GuardianTokensCollected(_guardian, _amount, nextTermId);
return true;
}
/**
* @notice Lock `_guardian`'s withdrawals until term #`_termId`
* @dev This is intended for guardians who voted in a final round and were coherent with the final ruling to prevent 51% attacks
* @param _guardian Address of the guardian to be locked
* @param _termId Term ID until which the guardian's withdrawals will be locked
*/
function lockWithdrawals(address _guardian, uint64 _termId) external onlyActiveDisputeManager {
Guardian storage guardian = guardiansByAddress[_guardian];
guardian.withdrawalsLockTermId = _termId;
}
/**
* @notice Set new limit of total active balance of guardian tokens
* @param _totalActiveBalanceLimit New limit of total active balance of guardian tokens
*/
function setTotalActiveBalanceLimit(uint256 _totalActiveBalanceLimit) external onlyConfigGovernor {
_setTotalActiveBalanceLimit(_totalActiveBalanceLimit);
}
/**
* @dev Tell the total supply of guardian tokens staked
* @return Supply of guardian tokens staked
*/
function totalSupply() external view returns (uint256) {
return guardiansToken.balanceOf(address(this));
}
/**
* @dev Tell the total amount of active guardian tokens
* @return Total amount of active guardian tokens
*/
function totalActiveBalance() external view returns (uint256) {
return tree.getTotal();
}
/**
* @dev Tell the total amount of active guardian tokens for a given term id
* @param _termId Term ID to query on
* @return Total amount of active guardian tokens at the given term id
*/
function totalActiveBalanceAt(uint64 _termId) external view returns (uint256) {
return _totalActiveBalanceAt(_termId);
}
/**
* @dev Tell the total balance of tokens held by a guardian
* This includes the active balance, the available balances, and the pending balance for deactivation.
* Note that we don't have to include the locked balances since these represent the amount of active tokens
* that are locked for drafts, i.e. these are already included in the active balance of the guardian.
* @param _guardian Address of the guardian querying the balance of
* @return Total amount of tokens of a guardian
*/
function balanceOf(address _guardian) external view returns (uint256) {
return _balanceOf(_guardian);
}
/**
* @dev Tell the detailed balance information of a guardian
* @param _guardian Address of the guardian querying the detailed balance information of
* @return active Amount of active tokens of a guardian
* @return available Amount of available tokens of a guardian
* @return locked Amount of active tokens that are locked due to ongoing disputes
* @return pendingDeactivation Amount of active tokens that were requested for deactivation
*/
function detailedBalanceOf(address _guardian) external view
returns (uint256 active, uint256 available, uint256 locked, uint256 pendingDeactivation)
{
return _detailedBalanceOf(_guardian);
}
/**
* @dev Tell the active balance of a guardian for a given term id
* @param _guardian Address of the guardian querying the active balance of
* @param _termId Term ID to query on
* @return Amount of active tokens for guardian in the requested past term id
*/
function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256) {
return _activeBalanceOfAt(_guardian, _termId);
}
/**
* @dev Tell the amount of active tokens of a guardian at the last ensured term that are not locked due to ongoing disputes
* @param _guardian Address of the guardian querying the unlocked balance of
* @return Amount of active tokens of a guardian that are not locked due to ongoing disputes
*/
function unlockedActiveBalanceOf(address _guardian) external view returns (uint256) {
Guardian storage guardian = guardiansByAddress[_guardian];
return _currentUnlockedActiveBalanceOf(guardian);
}
/**
* @dev Tell the pending deactivation details for a guardian
* @param _guardian Address of the guardian whose info is requested
* @return amount Amount to be deactivated
* @return availableTermId Term in which the deactivated amount will be available
*/
function getDeactivationRequest(address _guardian) external view returns (uint256 amount, uint64 availableTermId) {
DeactivationRequest storage request = guardiansByAddress[_guardian].deactivationRequest;
return (request.amount, request.availableTermId);
}
/**
* @dev Tell the activation amount locked for a guardian by a lock manager
* @param _guardian Address of the guardian whose info is requested
* @param _lockManager Address of the lock manager querying the lock of
* @return amount Activation amount locked by the lock manager
* @return total Total activation amount locked for the guardian
*/
function getActivationLock(address _guardian, address _lockManager) external view returns (uint256 amount, uint256 total) {
ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks;
total = activationLocks.total;
amount = activationLocks.lockedBy[_lockManager];
}
/**
* @dev Tell the withdrawals lock term ID for a guardian
* @param _guardian Address of the guardian whose info is requested
* @return Term ID until which the guardian's withdrawals will be locked
*/
function getWithdrawalsLockTermId(address _guardian) external view returns (uint64) {
return guardiansByAddress[_guardian].withdrawalsLockTermId;
}
/**
* @dev Tell the identification number associated to a guardian address
* @param _guardian Address of the guardian querying the identification number of
* @return Identification number associated to a guardian address, zero in case it wasn't registered yet
*/
function getGuardianId(address _guardian) external view returns (uint256) {
return guardiansByAddress[_guardian].id;
}
/**
* @dev Internal function to activate a given amount of tokens for a guardian.
* This function assumes that the given term is the current term and has already been ensured.
* @param _guardian Address of the guardian to activate tokens
* @param _amount Amount of guardian tokens to be activated
*/
function _activate(address _guardian, uint256 _amount) internal {
uint64 termId = _ensureCurrentTerm();
// Try to clean a previous deactivation request if any
_processDeactivationRequest(_guardian, termId);
uint256 availableBalance = guardiansByAddress[_guardian].availableBalance;
uint256 amountToActivate = _amount == 0 ? availableBalance : _amount;
require(amountToActivate > 0, ERROR_INVALID_ZERO_AMOUNT);
require(amountToActivate <= availableBalance, ERROR_INVALID_ACTIVATION_AMOUNT);
uint64 nextTermId = termId + 1;
_checkTotalActiveBalance(nextTermId, amountToActivate);
Guardian storage guardian = guardiansByAddress[_guardian];
uint256 minActiveBalance = _getMinActiveBalance(nextTermId);
if (_existsGuardian(guardian)) {
// Even though we are adding amounts, let's check the new active balance is greater than or equal to the
// minimum active amount. Note that the guardian might have been slashed.
uint256 activeBalance = tree.getItem(guardian.id);
require(activeBalance.add(amountToActivate) >= minActiveBalance, ERROR_ACTIVE_BALANCE_BELOW_MIN);
tree.update(guardian.id, nextTermId, amountToActivate, true);
} else {
require(amountToActivate >= minActiveBalance, ERROR_ACTIVE_BALANCE_BELOW_MIN);
guardian.id = tree.insert(nextTermId, amountToActivate);
guardiansAddressById[guardian.id] = _guardian;
}
_updateAvailableBalanceOf(_guardian, amountToActivate, false);
emit GuardianActivated(_guardian, nextTermId, amountToActivate);
}
/**
* @dev Internal function to deactivate a given amount of tokens for a guardian.
* @param _guardian Address of the guardian to deactivate tokens
* @param _amount Amount of guardian tokens to be deactivated for the next term
*/
function _deactivate(address _guardian, uint256 _amount) internal {
uint64 termId = _ensureCurrentTerm();
Guardian storage guardian = guardiansByAddress[_guardian];
uint256 unlockedActiveBalance = _lastUnlockedActiveBalanceOf(guardian);
uint256 amountToDeactivate = _amount == 0 ? unlockedActiveBalance : _amount;
require(amountToDeactivate > 0, ERROR_INVALID_ZERO_AMOUNT);
require(amountToDeactivate <= unlockedActiveBalance, ERROR_INVALID_DEACTIVATION_AMOUNT);
// Check future balance is not below the total activation lock of the guardian
// No need for SafeMath: we already checked values above
uint256 futureActiveBalance = unlockedActiveBalance - amountToDeactivate;
uint256 totalActivationLock = guardian.activationLocks.total;
require(futureActiveBalance >= totalActivationLock, ERROR_DEACTIVATION_AMOUNT_EXCEEDS_LOCK);
// Check that the guardian is leaving or that the minimum active balance is met
uint256 minActiveBalance = _getMinActiveBalance(termId);
require(futureActiveBalance == 0 || futureActiveBalance >= minActiveBalance, ERROR_INVALID_DEACTIVATION_AMOUNT);
_createDeactivationRequest(_guardian, amountToDeactivate);
}
/**
* @dev Internal function to create a token deactivation request for a guardian. Guardians will be allowed
* to process a deactivation request from the next term.
* @param _guardian Address of the guardian to create a token deactivation request for
* @param _amount Amount of guardian tokens requested for deactivation
*/
function _createDeactivationRequest(address _guardian, uint256 _amount) internal {
uint64 termId = _ensureCurrentTerm();
// Try to clean a previous deactivation request if possible
_processDeactivationRequest(_guardian, termId);
uint64 nextTermId = termId + 1;
Guardian storage guardian = guardiansByAddress[_guardian];
DeactivationRequest storage request = guardian.deactivationRequest;
request.amount = request.amount.add(_amount);
request.availableTermId = nextTermId;
tree.update(guardian.id, nextTermId, _amount, false);
emit GuardianDeactivationRequested(_guardian, nextTermId, _amount);
}
/**
* @dev Internal function to process a token deactivation requested by a guardian. It will move the requested amount
* to the available balance of the guardian if the term when the deactivation was requested has already finished.
* @param _guardian Address of the guardian to process the deactivation request of
* @param _termId Current term id
*/
function _processDeactivationRequest(address _guardian, uint64 _termId) internal {
Guardian storage guardian = guardiansByAddress[_guardian];
DeactivationRequest storage request = guardian.deactivationRequest;
uint64 deactivationAvailableTermId = request.availableTermId;
// If there is a deactivation request, ensure that the deactivation term has been reached
if (deactivationAvailableTermId == uint64(0) || _termId < deactivationAvailableTermId) {
return;
}
uint256 deactivationAmount = request.amount;
// Note that we can use a zeroed term ID to denote void here since we are storing
// the minimum allowed term to deactivate tokens which will always be at least 1.
request.availableTermId = uint64(0);
request.amount = 0;
_updateAvailableBalanceOf(_guardian, deactivationAmount, true);
emit GuardianDeactivationProcessed(_guardian, deactivationAvailableTermId, deactivationAmount, _termId);
}
/**
* @dev Internal function to reduce a token deactivation requested by a guardian. It assumes the deactivation request
* cannot be processed for the given term yet.
* @param _guardian Address of the guardian to reduce the deactivation request of
* @param _amount Amount to be reduced from the current deactivation request
* @param _termId Term ID in which the deactivation request is being reduced
*/
function _reduceDeactivationRequest(address _guardian, uint256 _amount, uint64 _termId) internal {
Guardian storage guardian = guardiansByAddress[_guardian];
DeactivationRequest storage request = guardian.deactivationRequest;
uint256 currentRequestAmount = request.amount;
require(currentRequestAmount >= _amount, ERROR_CANNOT_REDUCE_DEACTIVATION_REQUEST);
// No need for SafeMath: we already checked values above
uint256 newRequestAmount = currentRequestAmount - _amount;
request.amount = newRequestAmount;
// Move amount back to the tree
tree.update(guardian.id, _termId + 1, _amount, true);
emit GuardianDeactivationUpdated(_guardian, request.availableTermId, newRequestAmount, _termId);
}
/**
* @dev Internal function to update the activation locked amount of a guardian
* @param _guardian Guardian to update the activation locked amount of
* @param _lockManager Address of the lock manager controlling the lock
* @param _amount Amount of tokens to be added to the activation locked amount of the guardian
*/
function _lockActivation(address _guardian, address _lockManager, uint256 _amount) internal {
ActivationLocks storage activationLocks = guardiansByAddress[_guardian].activationLocks;
uint256 newTotalLocked = activationLocks.total.add(_amount);
uint256 newLockedAmount = activationLocks.lockedBy[_lockManager].add(_amount);
activationLocks.total = newTotalLocked;
activationLocks.lockedBy[_lockManager] = newLockedAmount;
emit GuardianActivationLockChanged(_guardian, _lockManager, newLockedAmount, newTotalLocked);
}
/**
* @dev Internal function to stake an amount of tokens for a guardian
* @param _guardian Address of the guardian to deposit the tokens to
* @param _amount Amount of tokens to be deposited
*/
function _stake(address _guardian, uint256 _amount) internal {
require(_amount > 0, ERROR_INVALID_ZERO_AMOUNT);
_updateAvailableBalanceOf(_guardian, _amount, true);
emit Staked(_guardian, _amount, _balanceOf(_guardian));
require(guardiansToken.safeTransferFrom(msg.sender, address(this), _amount), ERROR_TOKEN_TRANSFER_FAILED);
}
/**
* @dev Internal function to unstake an amount of tokens of a guardian
* @param _guardian Address of the guardian to to unstake the tokens of
* @param _amount Amount of tokens to be unstaked
*/
function _unstake(address _guardian, uint256 _amount) internal {
require(_amount > 0, ERROR_INVALID_ZERO_AMOUNT);
// Try to process a deactivation request for the current term if there is one. Note that we don't need to ensure
// the current term this time since deactivation requests always work with future terms, which means that if
// the current term is outdated, it will never match the deactivation term id. We avoid ensuring the term here
// to avoid forcing guardians to do that in order to withdraw their available balance. Same applies to final round locks.
uint64 lastEnsuredTermId = _getLastEnsuredTermId();
// Check that guardian's withdrawals are not locked
uint64 withdrawalsLockTermId = guardiansByAddress[_guardian].withdrawalsLockTermId;
require(withdrawalsLockTermId == 0 || withdrawalsLockTermId < lastEnsuredTermId, ERROR_WITHDRAWALS_LOCK);
_processDeactivationRequest(_guardian, lastEnsuredTermId);
_updateAvailableBalanceOf(_guardian, _amount, false);
emit Unstaked(_guardian, _amount, _balanceOf(_guardian));
require(guardiansToken.safeTransfer(_guardian, _amount), ERROR_TOKEN_TRANSFER_FAILED);
}
/**
* @dev Internal function to update the available balance of a guardian
* @param _guardian Guardian to update the available balance of
* @param _amount Amount of tokens to be added to or removed from the available balance of a guardian
* @param _positive True if the given amount should be added, or false to remove it from the available balance
*/
function _updateAvailableBalanceOf(address _guardian, uint256 _amount, bool _positive) internal {
// We are not using a require here to avoid reverting in case any of the treasury maths reaches this point
// with a zeroed amount value. Instead, we are doing this validation in the external entry points such as
// stake, unstake, activate, deactivate, among others.
if (_amount == 0) {
return;
}
Guardian storage guardian = guardiansByAddress[_guardian];
if (_positive) {
guardian.availableBalance = guardian.availableBalance.add(_amount);
} else {
require(_amount <= guardian.availableBalance, ERROR_NOT_ENOUGH_AVAILABLE_BALANCE);
// No need for SafeMath: we already checked values right above
guardian.availableBalance -= _amount;
}
}
/**
* @dev Internal function to set new limit of total active balance of guardian tokens
* @param _totalActiveBalanceLimit New limit of total active balance of guardian tokens
*/
function _setTotalActiveBalanceLimit(uint256 _totalActiveBalanceLimit) internal {
require(_totalActiveBalanceLimit > 0, ERROR_BAD_TOTAL_ACTIVE_BALANCE_LIMIT);
emit TotalActiveBalanceLimitChanged(totalActiveBalanceLimit, _totalActiveBalanceLimit);
totalActiveBalanceLimit = _totalActiveBalanceLimit;
}
/**
* @dev Internal function to tell the total balance of tokens held by a guardian
* @param _guardian Address of the guardian querying the total balance of
* @return Total amount of tokens of a guardian
*/
function _balanceOf(address _guardian) internal view returns (uint256) {
(uint256 active, uint256 available, , uint256 pendingDeactivation) = _detailedBalanceOf(_guardian);
return available.add(active).add(pendingDeactivation);
}
/**
* @dev Internal function to tell the detailed balance information of a guardian
* @param _guardian Address of the guardian querying the balance information of
* @return active Amount of active tokens of a guardian
* @return available Amount of available tokens of a guardian
* @return locked Amount of active tokens that are locked due to ongoing disputes
* @return pendingDeactivation Amount of active tokens that were requested for deactivation
*/
function _detailedBalanceOf(address _guardian) internal view
returns (uint256 active, uint256 available, uint256 locked, uint256 pendingDeactivation)
{
Guardian storage guardian = guardiansByAddress[_guardian];
active = _existsGuardian(guardian) ? tree.getItem(guardian.id) : 0;
(available, locked, pendingDeactivation) = _getBalances(guardian);
}
/**
* @dev Tell the active balance of a guardian for a given term id
* @param _guardian Address of the guardian querying the active balance of
* @param _termId Term ID querying the active balance for
* @return Amount of active tokens for guardian in the requested past term id
*/
function _activeBalanceOfAt(address _guardian, uint64 _termId) internal view returns (uint256) {
Guardian storage guardian = guardiansByAddress[_guardian];
return _existsGuardian(guardian) ? tree.getItemAt(guardian.id, _termId) : 0;
}
/**
* @dev Internal function to get the amount of active tokens of a guardian that are not locked due to ongoing disputes
* It will use the last value, that might be in a future term
* @param _guardian Guardian querying the unlocked active balance of
* @return Amount of active tokens of a guardian that are not locked due to ongoing disputes
*/
function _lastUnlockedActiveBalanceOf(Guardian storage _guardian) internal view returns (uint256) {
return _existsGuardian(_guardian) ? tree.getItem(_guardian.id).sub(_guardian.lockedBalance) : 0;
}
/**
* @dev Internal function to get the amount of active tokens at the last ensured term of a guardian that are not locked due to ongoing disputes
* @param _guardian Guardian querying the unlocked active balance of
* @return Amount of active tokens of a guardian that are not locked due to ongoing disputes
*/
function _currentUnlockedActiveBalanceOf(Guardian storage _guardian) internal view returns (uint256) {
uint64 lastEnsuredTermId = _getLastEnsuredTermId();
return _existsGuardian(_guardian) ? tree.getItemAt(_guardian.id, lastEnsuredTermId).sub(_guardian.lockedBalance) : 0;
}
/**
* @dev Internal function to check if a guardian was already registered
* @param _guardian Guardian to be checked
* @return True if the given guardian was already registered, false otherwise
*/
function _existsGuardian(Guardian storage _guardian) internal view returns (bool) {
return _guardian.id != 0;
}
/**
* @dev Internal function to get the amount of a deactivation request for a given term id
* @param _guardian Guardian to query the deactivation request amount of
* @param _termId Term ID of the deactivation request to be queried
* @return Amount of the deactivation request for the given term, 0 otherwise
*/
function _deactivationRequestedAmountForTerm(Guardian storage _guardian, uint64 _termId) internal view returns (uint256) {
DeactivationRequest storage request = _guardian.deactivationRequest;
return request.availableTermId == _termId ? request.amount : 0;
}
/**
* @dev Internal function to tell the total amount of active guardian tokens at the given term id
* @param _termId Term ID querying the total active balance for
* @return Total amount of active guardian tokens at the given term id
*/
function _totalActiveBalanceAt(uint64 _termId) internal view returns (uint256) {
// This function will return always the same values, the only difference remains on gas costs. In case we look for a
// recent term, in this case current or future ones, we perform a backwards linear search from the last checkpoint.
// Otherwise, a binary search is computed.
bool recent = _termId >= _getLastEnsuredTermId();
return recent ? tree.getRecentTotalAt(_termId) : tree.getTotalAt(_termId);
}
/**
* @dev Internal function to check if its possible to add a given new amount to the registry or not
* @param _termId Term ID when the new amount will be added
* @param _amount Amount of tokens willing to be added to the registry
*/
function _checkTotalActiveBalance(uint64 _termId, uint256 _amount) internal view {
uint256 currentTotalActiveBalance = _totalActiveBalanceAt(_termId);
uint256 newTotalActiveBalance = currentTotalActiveBalance.add(_amount);
require(newTotalActiveBalance <= totalActiveBalanceLimit, ERROR_TOTAL_ACTIVE_BALANCE_EXCEEDED);
}
/**
* @dev Tell the local balance information of a guardian (that is not on the tree)
* @param _guardian Address of the guardian querying the balance information of
* @return available Amount of available tokens of a guardian
* @return locked Amount of active tokens that are locked due to ongoing disputes
* @return pendingDeactivation Amount of active tokens that were requested for deactivation
*/
function _getBalances(Guardian storage _guardian) internal view returns (uint256 available, uint256 locked, uint256 pendingDeactivation) {
available = _guardian.availableBalance;
locked = _guardian.lockedBalance;
pendingDeactivation = _guardian.deactivationRequest.amount;
}
/**
* @dev Internal function to search guardians in the tree based on certain search restrictions
* @param _params Draft params to be used for the guardians search
* @return ids List of guardian ids obtained based on the requested search
* @return activeBalances List of active balances for each guardian obtained based on the requested search
*/
function _treeSearch(DraftParams memory _params) internal view returns (uint256[] memory ids, uint256[] memory activeBalances) {
(ids, activeBalances) = tree.batchedRandomSearch(
_params.termRandomness,
_params.disputeId,
_params.termId,
_params.selectedGuardians,
_params.batchRequestedGuardians,
_params.roundRequestedGuardians,
_params.iteration
);
}
/**
* @dev Private function to parse a certain set given of draft params
* @param _params Array containing draft requirements:
* 0. bytes32 Term randomness
* 1. uint256 Dispute id
* 2. uint64 Current term id
* 3. uint256 Number of seats already filled
* 4. uint256 Number of seats left to be filled
* 5. uint64 Number of guardians required for the draft
* 6. uint16 Permyriad of the minimum active balance to be locked for the draft
*
* @return Draft params object parsed
*/
function _buildDraftParams(uint256[7] memory _params) private view returns (DraftParams memory) {
uint64 termId = uint64(_params[2]);
uint256 minActiveBalance = _getMinActiveBalance(termId);
return DraftParams({
termRandomness: bytes32(_params[0]),
disputeId: _params[1],
termId: termId,
selectedGuardians: _params[3],
batchRequestedGuardians: _params[4],
roundRequestedGuardians: _params[5],
draftLockAmount: minActiveBalance.pct(uint16(_params[6])),
iteration: 0
});
}
} | Solidity only automatically asserts when dividing by 0
| require(_b > 0, ERROR_DIV_ZERO); | 91,483 | [
1,
25044,
560,
1338,
6635,
26124,
1347,
3739,
10415,
635,
374,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2583,
24899,
70,
405,
374,
16,
5475,
67,
31901,
67,
24968,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.18;
// From https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/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) {
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;
}
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
assert(b >= 0);
return b;
}
}
/**
* @title SafeMathInt
* @dev Math operations with safety checks that throw on error
* @dev SafeMath adapted for int256
*/
library SafeMathInt {
function mul(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when multiplying INT256_MIN with -1
// https://github.com/RequestNetwork/requestNetwork/issues/43
assert(!(a == - 2**255 && b == -1) && !(b == - 2**255 && a == -1));
int256 c = a * b;
assert((b == 0) || (c / b == a));
return c;
}
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing INT256_MIN by -1
// https://github.com/RequestNetwork/requestNetwork/issues/43
assert(!(a == - 2**255 && b == -1));
// assert(b > 0); // Solidity automatically throws when dividing by 0
int256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(int256 a, int256 b) internal pure returns (int256) {
assert((b >= 0 && a - b <= a) || (b < 0 && a - b > a));
return a - b;
}
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
assert((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
assert(a>=0);
return uint256(a);
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
* @dev SafeMath adapted for uint96
*/
library SafeMathUint96 {
function mul(uint96 a, uint96 b) internal pure returns (uint96) {
uint96 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint96 a, uint96 b) internal pure returns (uint96) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint96 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint96 a, uint96 b) internal pure returns (uint96) {
assert(b <= a);
return a - b;
}
function add(uint96 a, uint96 b) internal pure returns (uint96) {
uint96 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
* @dev SafeMath adapted for uint8
*/
library SafeMathUint8 {
function mul(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint8 a, uint8 b) internal pure returns (uint8) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint8 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint8 a, uint8 b) internal pure returns (uint8) {
assert(b <= a);
return a - b;
}
function add(uint8 a, uint8 b) internal pure returns (uint8) {
uint8 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title Administrable
* @dev Base contract for the administration of Core. Handles whitelisting of currency contracts
*/
contract Administrable is Pausable {
// mapping of address of trusted contract
mapping(address => uint8) public trustedCurrencyContracts;
// Events of the system
event NewTrustedContract(address newContract);
event RemoveTrustedContract(address oldContract);
/**
* @dev add a trusted currencyContract
*
* @param _newContractAddress The address of the currencyContract
*/
function adminAddTrustedCurrencyContract(address _newContractAddress)
external
onlyOwner
{
trustedCurrencyContracts[_newContractAddress] = 1; //Using int instead of boolean in case we need several states in the future.
NewTrustedContract(_newContractAddress);
}
/**
* @dev remove a trusted currencyContract
*
* @param _oldTrustedContractAddress The address of the currencyContract
*/
function adminRemoveTrustedCurrencyContract(address _oldTrustedContractAddress)
external
onlyOwner
{
require(trustedCurrencyContracts[_oldTrustedContractAddress] != 0);
trustedCurrencyContracts[_oldTrustedContractAddress] = 0;
RemoveTrustedContract(_oldTrustedContractAddress);
}
/**
* @dev get the status of a trusted currencyContract
* @dev Not used today, useful if we have several states in the future.
*
* @param _contractAddress The address of the currencyContract
* @return The status of the currencyContract. If trusted 1, otherwise 0
*/
function getStatusContract(address _contractAddress)
view
external
returns(uint8)
{
return trustedCurrencyContracts[_contractAddress];
}
/**
* @dev check if a currencyContract is trusted
*
* @param _contractAddress The address of the currencyContract
* @return bool true if contract is trusted
*/
function isTrustedContract(address _contractAddress)
public
view
returns(bool)
{
return trustedCurrencyContracts[_contractAddress] == 1;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant 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 constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title RequestCore
*
* @dev The Core is the main contract which stores all the requests.
*
* @dev The Core philosophy is to be as much flexible as possible to adapt in the future to any new system
* @dev All the important conditions and an important part of the business logic takes place in the currency contracts.
* @dev Requests can only be created in the currency contracts
* @dev Currency contracts have to be allowed by the Core and respect the business logic.
* @dev Request Network will develop one currency contracts per currency and anyone can creates its own currency contracts.
*/
contract RequestCore is Administrable {
using SafeMath for uint256;
using SafeMathUint96 for uint96;
using SafeMathInt for int256;
using SafeMathUint8 for uint8;
enum State { Created, Accepted, Canceled }
struct Request {
// ID address of the payer
address payer;
// Address of the contract managing the request
address currencyContract;
// State of the request
State state;
// Main payee
Payee payee;
}
// Structure for the payees. A sub payee is an additional entity which will be paid during the processing of the invoice.
// ex: can be used for routing taxes or fees at the moment of the payment.
struct Payee {
// ID address of the payee
address addr;
// amount expected for the payee.
// Not uint for evolution (may need negative amounts one day), and simpler operations
int256 expectedAmount;
// balance of the payee
int256 balance;
}
// Count of request in the mapping. A maximum of 2^96 requests can be created per Core contract.
// Integer, incremented for each request of a Core contract, starting from 0
// RequestId (256bits) = contract address (160bits) + numRequest
uint96 public numRequests;
// Mapping of all the Requests. The key is the request ID.
// not anymore public to avoid "UnimplementedFeatureError: Only in-memory reference type can be stored."
// https://github.com/ethereum/solidity/issues/3577
mapping(bytes32 => Request) requests;
// Mapping of subPayees of the requests. The key is the request ID.
// This array is outside the Request structure to optimize the gas cost when there is only 1 payee.
mapping(bytes32 => Payee[256]) public subPayees;
/*
* Events
*/
event Created(bytes32 indexed requestId, address indexed payee, address indexed payer, address creator, string data);
event Accepted(bytes32 indexed requestId);
event Canceled(bytes32 indexed requestId);
// Event for Payee & subPayees
event NewSubPayee(bytes32 indexed requestId, address indexed payee); // Separated from the Created Event to allow a 4th indexed parameter (subpayees)
event UpdateExpectedAmount(bytes32 indexed requestId, uint8 payeeIndex, int256 deltaAmount);
event UpdateBalance(bytes32 indexed requestId, uint8 payeeIndex, int256 deltaAmount);
/*
* @dev Function used by currency contracts to create a request in the Core
*
* @dev _payees and _expectedAmounts must have the same size
*
* @param _creator Request creator. The creator is the one who initiated the request (create or sign) and not necessarily the one who broadcasted it
* @param _payees array of payees address (the index 0 will be the payee the others are subPayees). Size must be smaller than 256.
* @param _expectedAmounts array of Expected amount to be received by each payees. Must be in same order than the payees. Size must be smaller than 256.
* @param _payer Entity expected to pay
* @param _data data of the request
* @return Returns the id of the request
*/
function createRequest(
address _creator,
address[] _payees,
int256[] _expectedAmounts,
address _payer,
string _data)
external
whenNotPaused
returns (bytes32 requestId)
{
// creator must not be null
require(_creator!=0); // not as modifier to lighten the stack
// call must come from a trusted contract
require(isTrustedContract(msg.sender)); // not as modifier to lighten the stack
// Generate the requestId
requestId = generateRequestId();
address mainPayee;
int256 mainExpectedAmount;
// extract the main payee if filled
if(_payees.length!=0) {
mainPayee = _payees[0];
mainExpectedAmount = _expectedAmounts[0];
}
// Store the new request
requests[requestId] = Request(_payer, msg.sender, State.Created, Payee(mainPayee, mainExpectedAmount, 0));
// Declare the new request
Created(requestId, mainPayee, _payer, _creator, _data);
// Store and declare the sub payees (needed in internal function to avoid "stack too deep")
initSubPayees(requestId, _payees, _expectedAmounts);
return requestId;
}
/*
* @dev Function used by currency contracts to create a request in the Core from bytes
* @dev Used to avoid receiving a stack too deep error when called from a currency contract with too many parameters.
* @audit Note that to optimize the stack size and the gas cost we do not extract the params and store them in the stack. As a result there is some code redundancy
* @param _data bytes containing all the data packed :
address(creator)
address(payer)
uint8(number_of_payees)
[
address(main_payee_address)
int256(main_payee_expected_amount)
address(second_payee_address)
int256(second_payee_expected_amount)
...
]
uint8(data_string_size)
size(data)
* @return Returns the id of the request
*/
function createRequestFromBytes(bytes _data)
external
whenNotPaused
returns (bytes32 requestId)
{
// call must come from a trusted contract
require(isTrustedContract(msg.sender)); // not as modifier to lighten the stack
// extract address creator & payer
address creator = extractAddress(_data, 0);
address payer = extractAddress(_data, 20);
// creator must not be null
require(creator!=0);
// extract the number of payees
uint8 payeesCount = uint8(_data[40]);
// get the position of the dataSize in the byte (= number_of_payees * (address_payee_size + int256_payee_size) + address_creator_size + address_payer_size + payees_count_size
// (= number_of_payees * (20+32) + 20 + 20 + 1 )
uint256 offsetDataSize = uint256(payeesCount).mul(52).add(41);
// extract the data size and then the data itself
uint8 dataSize = uint8(_data[offsetDataSize]);
string memory dataStr = extractString(_data, dataSize, offsetDataSize.add(1));
address mainPayee;
int256 mainExpectedAmount;
// extract the main payee if possible
if(payeesCount!=0) {
mainPayee = extractAddress(_data, 41);
mainExpectedAmount = int256(extractBytes32(_data, 61));
}
// Generate the requestId
requestId = generateRequestId();
// Store the new request
requests[requestId] = Request(payer, msg.sender, State.Created, Payee(mainPayee, mainExpectedAmount, 0));
// Declare the new request
Created(requestId, mainPayee, payer, creator, dataStr);
// Store and declare the sub payees
for(uint8 i = 1; i < payeesCount; i = i.add(1)) {
address subPayeeAddress = extractAddress(_data, uint256(i).mul(52).add(41));
// payees address cannot be 0x0
require(subPayeeAddress != 0);
subPayees[requestId][i-1] = Payee(subPayeeAddress, int256(extractBytes32(_data, uint256(i).mul(52).add(61))), 0);
NewSubPayee(requestId, subPayeeAddress);
}
return requestId;
}
/*
* @dev Function used by currency contracts to accept a request in the Core.
* @dev callable only by the currency contract of the request
* @param _requestId Request id
*/
function accept(bytes32 _requestId)
external
{
Request storage r = requests[_requestId];
require(r.currencyContract==msg.sender);
r.state = State.Accepted;
Accepted(_requestId);
}
/*
* @dev Function used by currency contracts to cancel a request in the Core. Several reasons can lead to cancel a request, see request life cycle for more info.
* @dev callable only by the currency contract of the request
* @param _requestId Request id
*/
function cancel(bytes32 _requestId)
external
{
Request storage r = requests[_requestId];
require(r.currencyContract==msg.sender);
r.state = State.Canceled;
Canceled(_requestId);
}
/*
* @dev Function used to update the balance
* @dev callable only by the currency contract of the request
* @param _requestId Request id
* @param _payeeIndex index of the payee (0 = main payee)
* @param _deltaAmount modifier amount
*/
function updateBalance(bytes32 _requestId, uint8 _payeeIndex, int256 _deltaAmount)
external
{
Request storage r = requests[_requestId];
require(r.currencyContract==msg.sender);
if( _payeeIndex == 0 ) {
// modify the main payee
r.payee.balance = r.payee.balance.add(_deltaAmount);
} else {
// modify the sub payee
Payee storage sp = subPayees[_requestId][_payeeIndex-1];
sp.balance = sp.balance.add(_deltaAmount);
}
UpdateBalance(_requestId, _payeeIndex, _deltaAmount);
}
/*
* @dev Function update the expectedAmount adding additional or subtract
* @dev callable only by the currency contract of the request
* @param _requestId Request id
* @param _payeeIndex index of the payee (0 = main payee)
* @param _deltaAmount modifier amount
*/
function updateExpectedAmount(bytes32 _requestId, uint8 _payeeIndex, int256 _deltaAmount)
external
{
Request storage r = requests[_requestId];
require(r.currencyContract==msg.sender);
if( _payeeIndex == 0 ) {
// modify the main payee
r.payee.expectedAmount = r.payee.expectedAmount.add(_deltaAmount);
} else {
// modify the sub payee
Payee storage sp = subPayees[_requestId][_payeeIndex-1];
sp.expectedAmount = sp.expectedAmount.add(_deltaAmount);
}
UpdateExpectedAmount(_requestId, _payeeIndex, _deltaAmount);
}
/*
* @dev Internal: Init payees for a request (needed to avoid 'stack too deep' in createRequest())
* @param _requestId Request id
* @param _payees array of payees address
* @param _expectedAmounts array of payees initial expected amounts
*/
function initSubPayees(bytes32 _requestId, address[] _payees, int256[] _expectedAmounts)
internal
{
require(_payees.length == _expectedAmounts.length);
for (uint8 i = 1; i < _payees.length; i = i.add(1))
{
// payees address cannot be 0x0
require(_payees[i] != 0);
subPayees[_requestId][i-1] = Payee(_payees[i], _expectedAmounts[i], 0);
NewSubPayee(_requestId, _payees[i]);
}
}
/* GETTER */
/*
* @dev Get address of a payee
* @param _requestId Request id
* @param _payeeIndex payee index (0 = main payee)
* @return payee address
*/
function getPayeeAddress(bytes32 _requestId, uint8 _payeeIndex)
public
constant
returns(address)
{
if(_payeeIndex == 0) {
return requests[_requestId].payee.addr;
} else {
return subPayees[_requestId][_payeeIndex-1].addr;
}
}
/*
* @dev Get payer of a request
* @param _requestId Request id
* @return payer address
*/
function getPayer(bytes32 _requestId)
public
constant
returns(address)
{
return requests[_requestId].payer;
}
/*
* @dev Get amount expected of a payee
* @param _requestId Request id
* @param _payeeIndex payee index (0 = main payee)
* @return amount expected
*/
function getPayeeExpectedAmount(bytes32 _requestId, uint8 _payeeIndex)
public
constant
returns(int256)
{
if(_payeeIndex == 0) {
return requests[_requestId].payee.expectedAmount;
} else {
return subPayees[_requestId][_payeeIndex-1].expectedAmount;
}
}
/*
* @dev Get number of subPayees for a request
* @param _requestId Request id
* @return number of subPayees
*/
function getSubPayeesCount(bytes32 _requestId)
public
constant
returns(uint8)
{
for (uint8 i = 0; subPayees[_requestId][i].addr != address(0); i = i.add(1)) {
// nothing to do
}
return i;
}
/*
* @dev Get currencyContract of a request
* @param _requestId Request id
* @return currencyContract address
*/
function getCurrencyContract(bytes32 _requestId)
public
constant
returns(address)
{
return requests[_requestId].currencyContract;
}
/*
* @dev Get balance of a payee
* @param _requestId Request id
* @param _payeeIndex payee index (0 = main payee)
* @return balance
*/
function getPayeeBalance(bytes32 _requestId, uint8 _payeeIndex)
public
constant
returns(int256)
{
if(_payeeIndex == 0) {
return requests[_requestId].payee.balance;
} else {
return subPayees[_requestId][_payeeIndex-1].balance;
}
}
/*
* @dev Get balance total of a request
* @param _requestId Request id
* @return balance
*/
function getBalance(bytes32 _requestId)
public
constant
returns(int256)
{
int256 balance = requests[_requestId].payee.balance;
for (uint8 i = 0; subPayees[_requestId][i].addr != address(0); i = i.add(1))
{
balance = balance.add(subPayees[_requestId][i].balance);
}
return balance;
}
/*
* @dev check if all the payees balances are null
* @param _requestId Request id
* @return true if all the payees balances are equals to 0
*/
function areAllBalanceNull(bytes32 _requestId)
public
constant
returns(bool isNull)
{
isNull = requests[_requestId].payee.balance == 0;
for (uint8 i = 0; isNull && subPayees[_requestId][i].addr != address(0); i = i.add(1))
{
isNull = subPayees[_requestId][i].balance == 0;
}
return isNull;
}
/*
* @dev Get total expectedAmount of a request
* @param _requestId Request id
* @return balance
*/
function getExpectedAmount(bytes32 _requestId)
public
constant
returns(int256)
{
int256 expectedAmount = requests[_requestId].payee.expectedAmount;
for (uint8 i = 0; subPayees[_requestId][i].addr != address(0); i = i.add(1))
{
expectedAmount = expectedAmount.add(subPayees[_requestId][i].expectedAmount);
}
return expectedAmount;
}
/*
* @dev Get state of a request
* @param _requestId Request id
* @return state
*/
function getState(bytes32 _requestId)
public
constant
returns(State)
{
return requests[_requestId].state;
}
/*
* @dev Get address of a payee
* @param _requestId Request id
* @return payee index (0 = main payee) or -1 if not address not found
*/
function getPayeeIndex(bytes32 _requestId, address _address)
public
constant
returns(int16)
{
// return 0 if main payee
if(requests[_requestId].payee.addr == _address) return 0;
for (uint8 i = 0; subPayees[_requestId][i].addr != address(0); i = i.add(1))
{
if(subPayees[_requestId][i].addr == _address) {
// if found return subPayee index + 1 (0 is main payee)
return i+1;
}
}
return -1;
}
/*
* @dev getter of a request
* @param _requestId Request id
* @return request as a tuple : (address payer, address currencyContract, State state, address payeeAddr, int256 payeeExpectedAmount, int256 payeeBalance)
*/
function getRequest(bytes32 _requestId)
external
constant
returns(address payer, address currencyContract, State state, address payeeAddr, int256 payeeExpectedAmount, int256 payeeBalance)
{
Request storage r = requests[_requestId];
return ( r.payer,
r.currencyContract,
r.state,
r.payee.addr,
r.payee.expectedAmount,
r.payee.balance );
}
/*
* @dev extract a string from a bytes. Extracts a sub-part from tha bytes and convert it to string
* @param data bytes from where the string will be extracted
* @param size string size to extract
* @param _offset position of the first byte of the string in bytes
* @return string
*/
function extractString(bytes data, uint8 size, uint _offset)
internal
pure
returns (string)
{
bytes memory bytesString = new bytes(size);
for (uint j = 0; j < size; j++) {
bytesString[j] = data[_offset+j];
}
return string(bytesString);
}
/*
* @dev generate a new unique requestId
* @return a bytes32 requestId
*/
function generateRequestId()
internal
returns (bytes32)
{
// Update numRequest
numRequests = numRequests.add(1);
// requestId = ADDRESS_CONTRACT_CORE + numRequests (0xADRRESSCONTRACT00000NUMREQUEST)
return bytes32((uint256(this) << 96).add(numRequests));
}
/*
* @dev extract an address from a bytes at a given position
* @param _data bytes from where the address will be extract
* @param _offset position of the first byte of the address
* @return address
*/
function extractAddress(bytes _data, uint offset)
internal
pure
returns (address m)
{
require(offset >=0 && offset + 20 <= _data.length);
assembly {
m := and( mload(add(_data, add(20, offset))),
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
}
/*
* @dev extract a bytes32 from a bytes
* @param data bytes from where the bytes32 will be extract
* @param offset position of the first byte of the bytes32
* @return address
*/
function extractBytes32(bytes _data, uint offset)
public
pure
returns (bytes32 bs)
{
require(offset >=0 && offset + 32 <= _data.length);
assembly {
bs := mload(add(_data, add(32, offset)))
}
}
/**
* @dev transfer to owner any tokens send by mistake on this contracts
* @param token The address of the token to transfer.
* @param amount The amount to be transfered.
*/
function emergencyERC20Drain(ERC20 token, uint amount )
public
onlyOwner
{
token.transfer(owner, amount);
}
}
/**
* @title RequestCollectInterface
*
* @dev RequestCollectInterface is a contract managing the fees for currency contracts
*/
contract RequestCollectInterface is Pausable {
using SafeMath for uint256;
uint256 public rateFeesNumerator;
uint256 public rateFeesDenominator;
uint256 public maxFees;
// address of the contract that will burn req token (through Kyber)
address public requestBurnerContract;
/*
* Events
*/
event UpdateRateFees(uint256 rateFeesNumerator, uint256 rateFeesDenominator);
event UpdateMaxFees(uint256 maxFees);
/*
* @dev Constructor
* @param _requestBurnerContract Address of the contract where to send the ethers.
* This burner contract will have a function that can be called by anyone and will exchange ethers to req via Kyber and burn the REQ
*/
function RequestCollectInterface(address _requestBurnerContract)
public
{
requestBurnerContract = _requestBurnerContract;
}
/*
* @dev send fees to the request burning address
* @param _amount amount to send to the burning address
*/
function collectForREQBurning(uint256 _amount)
internal
returns(bool)
{
return requestBurnerContract.send(_amount);
}
/*
* @dev compute the fees
* @param _expectedAmount amount expected for the request
* @return the expected amount of fees in wei
*/
function collectEstimation(int256 _expectedAmount)
public
view
returns(uint256)
{
if(_expectedAmount<0) return 0;
uint256 computedCollect = uint256(_expectedAmount).mul(rateFeesNumerator);
if(rateFeesDenominator != 0) {
computedCollect = computedCollect.div(rateFeesDenominator);
}
return computedCollect < maxFees ? computedCollect : maxFees;
}
/*
* @dev set the fees rate
* NB: if the _rateFeesDenominator is 0, it will be treated as 1. (in other words, the computation of the fees will not use it)
* @param _rateFeesNumerator numerator rate
* @param _rateFeesDenominator denominator rate
*/
function setRateFees(uint256 _rateFeesNumerator, uint256 _rateFeesDenominator)
external
onlyOwner
{
rateFeesNumerator = _rateFeesNumerator;
rateFeesDenominator = _rateFeesDenominator;
UpdateRateFees(rateFeesNumerator, rateFeesDenominator);
}
/*
* @dev set the maximum fees in wei
* @param _newMax new max
*/
function setMaxCollectable(uint256 _newMaxFees)
external
onlyOwner
{
maxFees = _newMaxFees;
UpdateMaxFees(maxFees);
}
/*
* @dev set the request burner address
* @param _requestBurnerContract address of the contract that will burn req token (probably through Kyber)
*/
function setRequestBurnerContract(address _requestBurnerContract)
external
onlyOwner
{
requestBurnerContract=_requestBurnerContract;
}
}
/**
* @title RequestCurrencyContractInterface
*
* @dev RequestCurrencyContractInterface is the currency contract managing the request in Ethereum
* @dev The contract can be paused. In this case, nobody can create Requests anymore but people can still interact with them or withdraw funds.
*
* @dev Requests can be created by the Payee with createRequestAsPayee(), by the payer with createRequestAsPayer() or by the payer from a request signed offchain by the payee with broadcastSignedRequestAsPayer
*/
contract RequestCurrencyContractInterface is RequestCollectInterface {
using SafeMath for uint256;
using SafeMathInt for int256;
using SafeMathUint8 for uint8;
// RequestCore object
RequestCore public requestCore;
/*
* @dev Constructor
* @param _requestCoreAddress Request Core address
*/
function RequestCurrencyContractInterface(address _requestCoreAddress, address _addressBurner)
RequestCollectInterface(_addressBurner)
public
{
requestCore=RequestCore(_requestCoreAddress);
}
function createCoreRequestInternal(
address _payer,
address[] _payeesIdAddress,
int256[] _expectedAmounts,
string _data)
internal
whenNotPaused
returns(bytes32 requestId, int256 totalExpectedAmounts)
{
totalExpectedAmounts = 0;
for (uint8 i = 0; i < _expectedAmounts.length; i = i.add(1))
{
// all expected amount must be positive
require(_expectedAmounts[i]>=0);
// compute the total expected amount of the request
totalExpectedAmounts = totalExpectedAmounts.add(_expectedAmounts[i]);
}
// store request in the core
requestId= requestCore.createRequest(msg.sender, _payeesIdAddress, _expectedAmounts, _payer, _data);
}
function acceptAction(bytes32 _requestId)
public
whenNotPaused
onlyRequestPayer(_requestId)
{
// only a created request can be accepted
require(requestCore.getState(_requestId)==RequestCore.State.Created);
// declare the acceptation in the core
requestCore.accept(_requestId);
}
function cancelAction(bytes32 _requestId)
public
whenNotPaused
{
// payer can cancel if request is just created
// payee can cancel when request is not canceled yet
require((requestCore.getPayer(_requestId)==msg.sender && requestCore.getState(_requestId)==RequestCore.State.Created)
|| (requestCore.getPayeeAddress(_requestId,0)==msg.sender && requestCore.getState(_requestId)!=RequestCore.State.Canceled));
// impossible to cancel a Request with any payees balance != 0
require(requestCore.areAllBalanceNull(_requestId));
// declare the cancellation in the core
requestCore.cancel(_requestId);
}
function additionalAction(bytes32 _requestId, uint256[] _additionalAmounts)
public
whenNotPaused
onlyRequestPayer(_requestId)
{
// impossible to make additional if request is canceled
require(requestCore.getState(_requestId)!=RequestCore.State.Canceled);
// impossible to declare more additionals than the number of payees
require(_additionalAmounts.length <= requestCore.getSubPayeesCount(_requestId).add(1));
for(uint8 i = 0; i < _additionalAmounts.length; i = i.add(1)) {
// no need to declare a zero as additional
if(_additionalAmounts[i] != 0) {
// Store and declare the additional in the core
requestCore.updateExpectedAmount(_requestId, i, _additionalAmounts[i].toInt256Safe());
}
}
}
function subtractAction(bytes32 _requestId, uint256[] _subtractAmounts)
public
whenNotPaused
onlyRequestPayee(_requestId)
{
// impossible to make subtracts if request is canceled
require(requestCore.getState(_requestId)!=RequestCore.State.Canceled);
// impossible to declare more subtracts than the number of payees
require(_subtractAmounts.length <= requestCore.getSubPayeesCount(_requestId).add(1));
for(uint8 i = 0; i < _subtractAmounts.length; i = i.add(1)) {
// no need to declare a zero as subtracts
if(_subtractAmounts[i] != 0) {
// subtract must be equal or lower than amount expected
require(requestCore.getPayeeExpectedAmount(_requestId,i) >= _subtractAmounts[i].toInt256Safe());
// Store and declare the subtract in the core
requestCore.updateExpectedAmount(_requestId, i, -_subtractAmounts[i].toInt256Safe());
}
}
}
// ----------------------------------------------------------------------------------------
/*
* @dev Modifier to check if msg.sender is the main payee
* @dev Revert if msg.sender is not the main payee
* @param _requestId id of the request
*/
modifier onlyRequestPayee(bytes32 _requestId)
{
require(requestCore.getPayeeAddress(_requestId, 0)==msg.sender);
_;
}
/*
* @dev Modifier to check if msg.sender is payer
* @dev Revert if msg.sender is not payer
* @param _requestId id of the request
*/
modifier onlyRequestPayer(bytes32 _requestId)
{
require(requestCore.getPayer(_requestId)==msg.sender);
_;
}
}
/**
* @title RequestBitcoinNodesValidation
*
* @dev RequestBitcoinNodesValidation is the currency contract managing the request in Bitcoin
* @dev The contract can be paused. In this case, nobody can create Requests anymore but people can still interact with them or withdraw funds.
*
* @dev Requests can be created by the Payee with createRequestAsPayee(), by the payer with createRequestAsPayer() or by the payer from a request signed offchain by the payee with broadcastSignedRequestAsPayer
*/
contract RequestBitcoinNodesValidation is RequestCurrencyContractInterface {
using SafeMath for uint256;
using SafeMathInt for int256;
using SafeMathUint8 for uint8;
// bitcoin addresses for payment and refund by requestid
// every time a transaction is sent to one of these addresses, it will be interpreted offchain as a payment (index 0 is the main payee, next indexes are for sub-payee)
mapping(bytes32 => string[256]) public payeesPaymentAddress;
// every time a transaction is sent to one of these addresses, it will be interpreted offchain as a refund (index 0 is the main payee, next indexes are for sub-payee)
mapping(bytes32 => string[256]) public payerRefundAddress;
/*
* @dev Constructor
* @param _requestCoreAddress Request Core address
* @param _requestBurnerAddress Request Burner contract address
*/
function RequestBitcoinNodesValidation(address _requestCoreAddress, address _requestBurnerAddress)
RequestCurrencyContractInterface(_requestCoreAddress, _requestBurnerAddress)
public
{
// nothing to do here
}
/*
* @dev Function to create a request as payee
*
* @dev msg.sender must be the main payee
*
* @param _payeesIdAddress array of payees address (the index 0 will be the payee - must be msg.sender - the others are subPayees)
* @param _payeesPaymentAddress array of payees bitcoin address for payment as bytes (bitcoin address don't have a fixed size)
* [
* uint8(payee1_bitcoin_address_size)
* string(payee1_bitcoin_address)
* uint8(payee2_bitcoin_address_size)
* string(payee2_bitcoin_address)
* ...
* ]
* @param _expectedAmounts array of Expected amount to be received by each payees
* @param _payer Entity expected to pay
* @param _payerRefundAddress payer bitcoin addresses for refund as bytes (bitcoin address don't have a fixed size)
* [
* uint8(payee1_refund_bitcoin_address_size)
* string(payee1_refund_bitcoin_address)
* uint8(payee2_refund_bitcoin_address_size)
* string(payee2_refund_bitcoin_address)
* ...
* ]
* @param _data Hash linking to additional data on the Request stored on IPFS
*
* @return Returns the id of the request
*/
function createRequestAsPayeeAction(
address[] _payeesIdAddress,
bytes _payeesPaymentAddress,
int256[] _expectedAmounts,
address _payer,
bytes _payerRefundAddress,
string _data)
external
payable
whenNotPaused
returns(bytes32 requestId)
{
require(msg.sender == _payeesIdAddress[0] && msg.sender != _payer && _payer != 0);
int256 totalExpectedAmounts;
(requestId, totalExpectedAmounts) = createCoreRequestInternal(_payer, _payeesIdAddress, _expectedAmounts, _data);
// compute and send fees
uint256 fees = collectEstimation(totalExpectedAmounts);
require(fees == msg.value && collectForREQBurning(fees));
extractAndStoreBitcoinAddresses(requestId, _payeesIdAddress.length, _payeesPaymentAddress, _payerRefundAddress);
return requestId;
}
/*
* @dev Internal function to extract and store bitcoin addresses from bytes
*
* @param _requestId id of the request
* @param _payeesCount number of payees
* @param _payeesPaymentAddress array of payees bitcoin address for payment as bytes
* [
* uint8(payee1_bitcoin_address_size)
* string(payee1_bitcoin_address)
* uint8(payee2_bitcoin_address_size)
* string(payee2_bitcoin_address)
* ...
* ]
* @param _payerRefundAddress payer bitcoin addresses for refund as bytes
* [
* uint8(payee1_refund_bitcoin_address_size)
* string(payee1_refund_bitcoin_address)
* uint8(payee2_refund_bitcoin_address_size)
* string(payee2_refund_bitcoin_address)
* ...
* ]
*/
function extractAndStoreBitcoinAddresses(
bytes32 _requestId,
uint256 _payeesCount,
bytes _payeesPaymentAddress,
bytes _payerRefundAddress)
internal
{
// set payment addresses for payees
uint256 cursor = 0;
uint8 sizeCurrentBitcoinAddress;
uint8 j;
for (j = 0; j < _payeesCount; j = j.add(1)) {
// get the size of the current bitcoin address
sizeCurrentBitcoinAddress = uint8(_payeesPaymentAddress[cursor]);
// extract and store the current bitcoin address
payeesPaymentAddress[_requestId][j] = extractString(_payeesPaymentAddress, sizeCurrentBitcoinAddress, ++cursor);
// move the cursor to the next bicoin address
cursor += sizeCurrentBitcoinAddress;
}
// set payment address for payer
cursor = 0;
for (j = 0; j < _payeesCount; j = j.add(1)) {
// get the size of the current bitcoin address
sizeCurrentBitcoinAddress = uint8(_payerRefundAddress[cursor]);
// extract and store the current bitcoin address
payerRefundAddress[_requestId][j] = extractString(_payerRefundAddress, sizeCurrentBitcoinAddress, ++cursor);
// move the cursor to the next bicoin address
cursor += sizeCurrentBitcoinAddress;
}
}
/*
* @dev Function to broadcast and accept an offchain signed request (the broadcaster can also pays and makes additionals )
*
* @dev msg.sender will be the _payer
* @dev only the _payer can additionals
*
* @param _requestData nested bytes containing : creator, payer, payees|expectedAmounts, data
* @param _payeesPaymentAddress array of payees bitcoin address for payment as bytes
* [
* uint8(payee1_bitcoin_address_size)
* string(payee1_bitcoin_address)
* uint8(payee2_bitcoin_address_size)
* string(payee2_bitcoin_address)
* ...
* ]
* @param _payerRefundAddress payer bitcoin addresses for refund as bytes
* [
* uint8(payee1_refund_bitcoin_address_size)
* string(payee1_refund_bitcoin_address)
* uint8(payee2_refund_bitcoin_address_size)
* string(payee2_refund_bitcoin_address)
* ...
* ]
* @param _additionals array to increase the ExpectedAmount for payees
* @param _expirationDate timestamp after that the signed request cannot be broadcasted
* @param _signature ECDSA signature in bytes
*
* @return Returns the id of the request
*/
function broadcastSignedRequestAsPayerAction(
bytes _requestData, // gather data to avoid "stack too deep"
bytes _payeesPaymentAddress,
bytes _payerRefundAddress,
uint256[] _additionals,
uint256 _expirationDate,
bytes _signature)
external
payable
whenNotPaused
returns(bytes32 requestId)
{
// check expiration date
require(_expirationDate >= block.timestamp);
// check the signature
require(checkRequestSignature(_requestData, _payeesPaymentAddress, _expirationDate, _signature));
return createAcceptAndAdditionalsFromBytes(_requestData, _payeesPaymentAddress, _payerRefundAddress, _additionals);
}
/*
* @dev Internal function to create, accept and add additionals to a request as Payer
*
* @dev msg.sender must be _payer
*
* @param _requestData nasty bytes containing : creator, payer, payees|expectedAmounts, data
* @param _payeesPaymentAddress array of payees bitcoin address for payment
* @param _payerRefundAddress payer bitcoin address for refund
* @param _additionals Will increase the ExpectedAmount of the request right after its creation by adding additionals
*
* @return Returns the id of the request
*/
function createAcceptAndAdditionalsFromBytes(
bytes _requestData,
bytes _payeesPaymentAddress,
bytes _payerRefundAddress,
uint256[] _additionals)
internal
returns(bytes32 requestId)
{
// extract main payee
address mainPayee = extractAddress(_requestData, 41);
require(msg.sender != mainPayee && mainPayee != 0);
// creator must be the main payee
require(extractAddress(_requestData, 0) == mainPayee);
// extract the number of payees
uint8 payeesCount = uint8(_requestData[40]);
int256 totalExpectedAmounts = 0;
for(uint8 i = 0; i < payeesCount; i++) {
// extract the expectedAmount for the payee[i]
int256 expectedAmountTemp = int256(extractBytes32(_requestData, uint256(i).mul(52).add(61)));
// compute the total expected amount of the request
totalExpectedAmounts = totalExpectedAmounts.add(expectedAmountTemp);
// all expected amount must be positive
require(expectedAmountTemp>0);
}
// compute and send fees
uint256 fees = collectEstimation(totalExpectedAmounts);
// check fees has been well received
require(fees == msg.value && collectForREQBurning(fees));
// insert the msg.sender as the payer in the bytes
updateBytes20inBytes(_requestData, 20, bytes20(msg.sender));
// store request in the core
requestId = requestCore.createRequestFromBytes(_requestData);
// set bitcoin addresses
extractAndStoreBitcoinAddresses(requestId, payeesCount, _payeesPaymentAddress, _payerRefundAddress);
// accept and pay the request with the value remaining after the fee collect
acceptAndAdditionals(requestId, _additionals);
return requestId;
}
/*
* @dev Internal function to accept and add additionals to a request as Payer
*
* @param _requestId id of the request
* @param _additionals Will increase the ExpectedAmounts of payees
*
*/
function acceptAndAdditionals(
bytes32 _requestId,
uint256[] _additionals)
internal
{
acceptAction(_requestId);
additionalAction(_requestId, _additionals);
}
// -----------------------------------------------------------------------------
/*
* @dev Check the validity of a signed request & the expiration date
* @param _data bytes containing all the data packed :
address(creator)
address(payer)
uint8(number_of_payees)
[
address(main_payee_address)
int256(main_payee_expected_amount)
address(second_payee_address)
int256(second_payee_expected_amount)
...
]
uint8(data_string_size)
size(data)
* @param _payeesPaymentAddress array of payees payment addresses (the index 0 will be the payee the others are subPayees)
* @param _expirationDate timestamp after that the signed request cannot be broadcasted
* @param _signature ECDSA signature containing v, r and s as bytes
*
* @return Validity of order signature.
*/
function checkRequestSignature(
bytes _requestData,
bytes _payeesPaymentAddress,
uint256 _expirationDate,
bytes _signature)
public
view
returns (bool)
{
bytes32 hash = getRequestHash(_requestData, _payeesPaymentAddress, _expirationDate);
// extract "v, r, s" from the signature
uint8 v = uint8(_signature[64]);
v = v < 27 ? v.add(27) : v;
bytes32 r = extractBytes32(_signature, 0);
bytes32 s = extractBytes32(_signature, 32);
// check signature of the hash with the creator address
return isValidSignature(extractAddress(_requestData, 0), hash, v, r, s);
}
/*
* @dev Function internal to calculate Keccak-256 hash of a request with specified parameters
*
* @param _data bytes containing all the data packed
* @param _payeesPaymentAddress array of payees payment addresses
* @param _expirationDate timestamp after what the signed request cannot be broadcasted
*
* @return Keccak-256 hash of (this,_requestData, _payeesPaymentAddress, _expirationDate)
*/
function getRequestHash(
bytes _requestData,
bytes _payeesPaymentAddress,
uint256 _expirationDate)
internal
view
returns(bytes32)
{
return keccak256(this,_requestData, _payeesPaymentAddress, _expirationDate);
}
/*
* @dev Verifies that a hash signature is valid. 0x style
* @param signer address of signer.
* @param hash Signed Keccak-256 hash.
* @param v ECDSA signature parameter v.
* @param r ECDSA signature parameters r.
* @param s ECDSA signature parameters s.
* @return Validity of order signature.
*/
function isValidSignature(
address signer,
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s)
public
pure
returns (bool)
{
return signer == ecrecover(
keccak256("\x19Ethereum Signed Message:\n32", hash),
v,
r,
s
);
}
/*
* @dev extract an address in a bytes
* @param data bytes from where the address will be extract
* @param offset position of the first byte of the address
* @return address
*/
function extractAddress(bytes _data, uint offset)
internal
pure
returns (address m)
{
require(offset >=0 && offset + 20 <= _data.length);
assembly {
m := and( mload(add(_data, add(20, offset))),
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
}
}
/*
* @dev extract a bytes32 from a bytes
* @param data bytes from where the bytes32 will be extract
* @param offset position of the first byte of the bytes32
* @return address
*/
function extractBytes32(bytes _data, uint offset)
public
pure
returns (bytes32 bs)
{
require(offset >=0 && offset + 32 <= _data.length);
assembly {
bs := mload(add(_data, add(32, offset)))
}
}
/*
* @dev modify 20 bytes in a bytes
* @param data bytes to modify
* @param offset position of the first byte to modify
* @param b bytes20 to insert
* @return address
*/
function updateBytes20inBytes(bytes data, uint offset, bytes20 b)
internal
pure
{
require(offset >=0 && offset + 20 <= data.length);
assembly {
let m := mload(add(data, add(20, offset)))
m := and(m, 0xFFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000)
m := or(m, div(b, 0x1000000000000000000000000))
mstore(add(data, add(20, offset)), m)
}
}
/*
* @dev extract a string from a bytes. Extracts a sub-part from tha bytes and convert it to string
* @param data bytes from where the string will be extracted
* @param size string size to extract
* @param _offset position of the first byte of the string in bytes
* @return string
*/
function extractString(bytes data, uint8 size, uint _offset)
internal
pure
returns (string)
{
bytes memory bytesString = new bytes(size);
for (uint j = 0; j < size; j++) {
bytesString[j] = data[_offset+j];
}
return string(bytesString);
}
} | @dev Get total expectedAmount of a request @param _requestId Request id @return balance/ | function getExpectedAmount(bytes32 _requestId)
public
constant
returns(int256)
{
int256 expectedAmount = requests[_requestId].payee.expectedAmount;
for (uint8 i = 0; subPayees[_requestId][i].addr != address(0); i = i.add(1))
{
expectedAmount = expectedAmount.add(subPayees[_requestId][i].expectedAmount);
}
return expectedAmount;
}
| 2,225,341 | [
1,
967,
2078,
2665,
6275,
434,
279,
590,
225,
389,
2293,
548,
1567,
612,
327,
11013,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
336,
6861,
6275,
12,
3890,
1578,
389,
2293,
548,
13,
203,
3639,
1071,
203,
3639,
5381,
203,
3639,
1135,
12,
474,
5034,
13,
203,
565,
288,
203,
3639,
509,
5034,
2665,
6275,
273,
3285,
63,
67,
2293,
548,
8009,
10239,
1340,
18,
3825,
6275,
31,
203,
203,
3639,
364,
261,
11890,
28,
277,
273,
374,
31,
720,
9148,
25521,
63,
67,
2293,
548,
6362,
77,
8009,
4793,
480,
1758,
12,
20,
1769,
277,
273,
277,
18,
1289,
12,
21,
3719,
203,
3639,
288,
203,
5411,
2665,
6275,
273,
2665,
6275,
18,
1289,
12,
1717,
9148,
25521,
63,
67,
2293,
548,
6362,
77,
8009,
3825,
6275,
1769,
203,
3639,
289,
203,
203,
3639,
327,
2665,
6275,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/4/0xB309FeA3F22e249C29f7565e35E9a096110a1C10/sources/browser/WerewolfAsset.sol | bytes4(keccak256("Error(string)")) solhint-disable func-name-mixedcase | library LibRichErrorsV06 {
bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0;
function StandardError(string memory message)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
| 660,475 | [
1,
3890,
24,
12,
79,
24410,
581,
5034,
2932,
668,
12,
1080,
2225,
3719,
3704,
11317,
17,
8394,
1326,
17,
529,
17,
19562,
3593,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
12083,
10560,
22591,
4229,
58,
7677,
288,
203,
203,
565,
1731,
24,
2713,
5381,
23255,
67,
3589,
67,
4803,
916,
273,
374,
92,
6840,
71,
6418,
29,
69,
20,
31,
203,
203,
565,
445,
31160,
12,
1080,
3778,
883,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
3890,
3778,
13,
203,
203,
203,
203,
565,
288,
203,
3639,
327,
24126,
18,
3015,
1190,
4320,
12,
203,
5411,
23255,
67,
3589,
67,
4803,
916,
16,
203,
5411,
1731,
12,
2150,
13,
203,
3639,
11272,
203,
565,
289,
203,
203,
565,
445,
436,
266,
1097,
12,
3890,
3778,
555,
751,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
565,
288,
203,
3639,
19931,
288,
203,
5411,
15226,
12,
1289,
12,
1636,
751,
16,
374,
92,
3462,
3631,
312,
945,
12,
1636,
751,
3719,
203,
3639,
289,
203,
565,
289,
203,
565,
445,
436,
266,
1097,
12,
3890,
3778,
555,
751,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
565,
288,
203,
3639,
19931,
288,
203,
5411,
15226,
12,
1289,
12,
1636,
751,
16,
374,
92,
3462,
3631,
312,
945,
12,
1636,
751,
3719,
203,
3639,
289,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
contract owned {
function owned() { owner = msg.sender; }
address owner;
}
// Use "is" to derive from another contract. Derived contracts can access all members
// including private functions and storage variables.
contract mortal is owned {
function kill() { if (msg.sender == owner) suicide(owner); }
}
// These are only provided to make the interface known to the compiler.
contract Config { function lookup(uint id) returns (address adr) {} }
contract NameReg { function register(string32 name) {} function unregister() {} }
// Multiple inheritance is possible. Note that "owned" is also a base class of
// "mortal", yet there is only a single instance of "owned" (as for virtual
// inheritance in C++).
contract named is owned, mortal {
function named(string32 name) {
address ConfigAddress = 0xd5f9d8d94886e70b06e474c3fb14fd43e2f23970;
NameReg(Config(ConfigAddress).lookup(1)).register(name);
}
// Functions can be overridden, both local and message-based function calls take
// these overrides into account.
function kill() {
if (msg.sender == owner) {
address ConfigAddress = 0xd5f9d8d94886e70b06e474c3fb14fd43e2f23970;
NameReg(Config(ConfigAddress).lookup(1)).unregister();
// It is still possible to call a specific overridden function.
mortal.kill();
}
}
}
// If a constructor takes an argument, it needs to be provided in the header.
contract PriceFeed is owned, mortal, named("GoldFeed") {
function updateInfo(uint newInfo) {
if (msg.sender == owner) info = newInfo;
}
function get() constant returns(uint r) { return info; }
uint info;
} | Use "is" to derive from another contract. Derived contracts can access all members including private functions and storage variables. | contract mortal is owned {
function kill() { if (msg.sender == owner) suicide(owner); }
}
| 6,381,338 | [
1,
3727,
315,
291,
6,
358,
14763,
628,
4042,
6835,
18,
14969,
2950,
20092,
848,
2006,
777,
4833,
6508,
3238,
4186,
471,
2502,
3152,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
312,
499,
287,
353,
16199,
288,
203,
565,
445,
8673,
1435,
288,
309,
261,
3576,
18,
15330,
422,
3410,
13,
1597,
335,
831,
12,
8443,
1769,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// Sources flattened with hardhat v2.8.3 https://hardhat.org
// File contracts/Interfaces/IBorrowerOperations.sol
// SPDX-License-Identifier:
pragma solidity 0.6.11;
// Common interface for the Trove Manager.
interface IBorrowerOperations {
// --- Events ---
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _activePoolAddress);
event DefaultPoolAddressChanged(address _defaultPoolAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event LUSDTokenAddressChanged(address _lusdTokenAddress);
event LQTYStakingAddressChanged(address _lqtyStakingAddress);
event TroveCreated(address indexed _borrower, uint arrayIndex);
event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation);
event LUSDBorrowingFeePaid(address indexed _borrower, uint _LUSDFee);
// --- Functions ---
function setAddresses(
address _troveManagerAddress,
address _activePoolAddress,
address _defaultPoolAddress,
address _stabilityPoolAddress,
address _gasPoolAddress,
address _collSurplusPoolAddress,
address _priceFeedAddress,
address _sortedTrovesAddress,
address _lusdTokenAddress,
address _lqtyStakingAddress
) external;
function openTrove(uint _maxFee, uint _LUSDAmount, address _upperHint, address _lowerHint) external payable;
function addColl(address _upperHint, address _lowerHint) external payable;
function moveETHGainToTrove(address _user, address _upperHint, address _lowerHint) external payable;
function withdrawColl(uint _amount, address _upperHint, address _lowerHint) external;
function withdrawLUSD(uint _maxFee, uint _amount, address _upperHint, address _lowerHint) external;
function repayLUSD(uint _amount, address _upperHint, address _lowerHint) external;
function closeTrove() external;
function adjustTrove(uint _maxFee, uint _collWithdrawal, uint _debtChange, bool isDebtIncrease, address _upperHint, address _lowerHint) external payable;
function claimCollateral() external;
function getCompositeDebt(uint _debt) external pure returns (uint);
}
// File contracts/Interfaces/IStabilityPool.sol
// MIT
pragma solidity 0.6.11;
/*
* The Stability Pool holds LUSD tokens deposited by Stability Pool depositors.
*
* When a trove is liquidated, then depending on system conditions, some of its LUSD debt gets offset with
* LUSD in the Stability Pool: that is, the offset debt evaporates, and an equal amount of LUSD tokens in the Stability Pool is burned.
*
* Thus, a liquidation causes each depositor to receive a LUSD loss, in proportion to their deposit as a share of total deposits.
* They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors,
* in the same proportion.
*
* When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40%
* of the total LUSD in the Stability Pool, depletes 40% of each deposit.
*
* A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit,
* multiplying it by some factor in range ]0,1[
*
* Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations:
* https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf
*
* --- LQTY ISSUANCE TO STABILITY POOL DEPOSITORS ---
*
* An LQTY issuance event occurs at every deposit operation, and every liquidation.
*
* Each deposit is tagged with the address of the front end through which it was made.
*
* All deposits earn a share of the issued LQTY in proportion to the deposit as a share of total deposits. The LQTY earned
* by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate.
*
* Please see the system Readme for an overview:
* https://github.com/liquity/dev/blob/main/README.md#lqty-issuance-to-stability-providers
*/
interface IStabilityPool {
// --- Events ---
event StabilityPoolETHBalanceUpdated(uint _newBalance);
event StabilityPoolLUSDBalanceUpdated(uint _newBalance);
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _newActivePoolAddress);
event DefaultPoolAddressChanged(address _newDefaultPoolAddress);
event LUSDTokenAddressChanged(address _newLUSDTokenAddress);
event SortedTrovesAddressChanged(address _newSortedTrovesAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress);
event P_Updated(uint _P);
event S_Updated(uint _S, uint128 _epoch, uint128 _scale);
event G_Updated(uint _G, uint128 _epoch, uint128 _scale);
event EpochUpdated(uint128 _currentEpoch);
event ScaleUpdated(uint128 _currentScale);
event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate);
event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd);
event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G);
event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G);
event UserDepositChanged(address indexed _depositor, uint _newDeposit);
event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor);
event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _LUSDLoss);
event LQTYPaidToDepositor(address indexed _depositor, uint _LQTY);
event LQTYPaidToFrontEnd(address indexed _frontEnd, uint _LQTY);
event EtherSent(address _to, uint _amount);
// --- Functions ---
/*
* Called only once on init, to set addresses of other Liquity contracts
* Callable only by owner, renounces ownership at the end
*/
function setAddresses(
address _borrowerOperationsAddress,
address _troveManagerAddress,
address _activePoolAddress,
address _lusdTokenAddress,
address _sortedTrovesAddress,
address _priceFeedAddress,
address _communityIssuanceAddress
) external;
/*
* Initial checks:
* - Frontend is registered or zero address
* - Sender is not a registered frontend
* - _amount is not zero
* ---
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Tags the deposit with the provided front end tag param, if it's a new deposit
* - Sends depositor's accumulated gains (LQTY, ETH) to depositor
* - Sends the tagged front end's accumulated LQTY gains to the tagged front end
* - Increases deposit and tagged front end's stake, and takes new snapshots for each.
*/
function provideToSP(uint _amount, address _frontEndTag) external;
/*
* Initial checks:
* - _amount is zero or there are no under collateralized troves left in the system
* - User has a non zero deposit
* ---
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Removes the deposit's front end tag if it is a full withdrawal
* - Sends all depositor's accumulated gains (LQTY, ETH) to depositor
* - Sends the tagged front end's accumulated LQTY gains to the tagged front end
* - Decreases deposit and tagged front end's stake, and takes new snapshots for each.
*
* If _amount > userDeposit, the user withdraws all of their compounded deposit.
*/
function withdrawFromSP(uint _amount) external;
/*
* Initial checks:
* - User has a non zero deposit
* - User has an open trove
* - User has some ETH gain
* ---
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Sends all depositor's LQTY gain to depositor
* - Sends all tagged front end's LQTY gain to the tagged front end
* - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove
* - Leaves their compounded deposit in the Stability Pool
* - Updates snapshots for deposit and tagged front end stake
*/
function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external;
/*
* Initial checks:
* - Frontend (sender) not already registered
* - User (sender) has no deposit
* - _kickbackRate is in the range [0, 100%]
* ---
* Front end makes a one-time selection of kickback rate upon registering
*/
function registerFrontEnd(uint _kickbackRate) external;
/*
* Initial checks:
* - Caller is TroveManager
* ---
* Cancels out the specified debt against the LUSD contained in the Stability Pool (as far as possible)
* and transfers the Trove's ETH collateral from ActivePool to StabilityPool.
* Only called by liquidation functions in the TroveManager.
*/
function offset(uint _debt, uint _coll) external;
/*
* Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`,
* to exclude edge cases like ETH received from a self-destruct.
*/
function getETH() external view returns (uint);
/*
* Returns LUSD held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset.
*/
function getTotalLUSDDeposits() external view returns (uint);
/*
* Calculates the ETH gain earned by the deposit since its last snapshots were taken.
*/
function getDepositorETHGain(address _depositor) external view returns (uint);
/*
* Calculate the LQTY gain earned by a deposit since its last snapshots were taken.
* If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned.
* Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through
* which they made their deposit.
*/
function getDepositorLQTYGain(address _depositor) external view returns (uint);
/*
* Return the LQTY gain earned by the front end.
*/
function getFrontEndLQTYGain(address _frontEnd) external view returns (uint);
/*
* Return the user's compounded deposit.
*/
function getCompoundedLUSDDeposit(address _depositor) external view returns (uint);
/*
* Return the front end's compounded stake.
*
* The front end's compounded stake is equal to the sum of its depositors' compounded deposits.
*/
function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint);
/*
* Fallback function
* Only callable by Active Pool, it just accounts for ETH received
* receive() external payable;
*/
}
// File contracts/Interfaces/IPriceFeed.sol
// MIT
pragma solidity 0.6.11;
interface IPriceFeed {
// --- Events ---
event LastGoodPriceUpdated(uint _lastGoodPrice);
// --- Function ---
function fetchPrice() external returns (uint);
}
// File contracts/Interfaces/ILiquityBase.sol
// MIT
pragma solidity 0.6.11;
interface ILiquityBase {
function priceFeed() external view returns (IPriceFeed);
}
// File contracts/Dependencies/IERC20.sol
// MIT
pragma solidity 0.6.11;
/**
* Based on the OpenZeppelin IER20 interface:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol
*
* @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);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/Dependencies/IERC2612.sol
// MIT
pragma solidity 0.6.11;
/**
* @dev Interface of the ERC2612 standard as defined in the EIP.
*
* Adds the {permit} method, which can be used to change one's
* {IERC20-allowance} without having to send a transaction, by signing a
* message. This allows users to spend tokens without having to hold Ether.
*
* See https://eips.ethereum.org/EIPS/eip-2612.
*
* Code adapted from https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2237/
*/
interface IERC2612 {
/**
* @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 amount,
uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current ERC2612 nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases `owner`'s nonce by one. This
* prevents a signature from being used multiple times.
*
* `owner` can limit the time a Permit is valid for by setting `deadline` to
* a value in the near future. The deadline argument can be set to uint(-1) to
* create Permits that effectively never expire.
*/
function nonces(address owner) external view returns (uint256);
function version() external view returns (string memory);
function permitTypeHash() external view returns (bytes32);
function domainSeparator() external view returns (bytes32);
}
// File contracts/Interfaces/ILUSDToken.sol
// MIT
pragma solidity 0.6.11;
interface ILUSDToken is IERC20, IERC2612 {
// --- Events ---
event TroveManagerAddressChanged(address _troveManagerAddress);
event StabilityPoolAddressChanged(address _newStabilityPoolAddress);
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event LUSDTokenBalanceUpdated(address _user, uint _amount);
// --- Functions ---
function mint(address _account, uint256 _amount) external;
function burn(address _account, uint256 _amount) external;
function sendToPool(address _sender, address poolAddress, uint256 _amount) external;
function returnFromPool(address poolAddress, address user, uint256 _amount ) external;
}
// File contracts/Interfaces/ILQTYToken.sol
// MIT
pragma solidity 0.6.11;
interface ILQTYToken is IERC20, IERC2612 {
// --- Events ---
event CommunityIssuanceAddressSet(address _communityIssuanceAddress);
event LQTYStakingAddressSet(address _lqtyStakingAddress);
event LockupContractFactoryAddressSet(address _lockupContractFactoryAddress);
// --- Functions ---
function sendToLQTYStaking(address _sender, uint256 _amount) external;
function getDeploymentStartTime() external view returns (uint256);
function getLpRewardsEntitlement() external view returns (uint256);
}
// File contracts/Interfaces/ILQTYStaking.sol
// MIT
pragma solidity 0.6.11;
interface ILQTYStaking {
// --- Events --
event LQTYTokenAddressSet(address _lqtyTokenAddress);
event LUSDTokenAddressSet(address _lusdTokenAddress);
event TroveManagerAddressSet(address _troveManager);
event BorrowerOperationsAddressSet(address _borrowerOperationsAddress);
event ActivePoolAddressSet(address _activePoolAddress);
event StakeChanged(address indexed staker, uint newStake);
event StakingGainsWithdrawn(address indexed staker, uint LUSDGain, uint ETHGain);
event F_ETHUpdated(uint _F_ETH);
event F_LUSDUpdated(uint _F_LUSD);
event TotalLQTYStakedUpdated(uint _totalLQTYStaked);
event EtherSent(address _account, uint _amount);
event StakerSnapshotsUpdated(address _staker, uint _F_ETH, uint _F_LUSD);
// --- Functions ---
function setAddresses
(
address _lqtyTokenAddress,
address _lusdTokenAddress,
address _troveManagerAddress,
address _borrowerOperationsAddress,
address _activePoolAddress
) external;
function stake(uint _LQTYamount) external;
function unstake(uint _LQTYamount) external;
function increaseF_ETH(uint _ETHFee) external;
function increaseF_LUSD(uint _LQTYFee) external;
function getPendingETHGain(address _user) external view returns (uint);
function getPendingLUSDGain(address _user) external view returns (uint);
}
// File contracts/Interfaces/ITroveManager.sol
// MIT
pragma solidity 0.6.11;
// Common interface for the Trove Manager.
interface ITroveManager is ILiquityBase {
// --- Events ---
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event LUSDTokenAddressChanged(address _newLUSDTokenAddress);
event ActivePoolAddressChanged(address _activePoolAddress);
event DefaultPoolAddressChanged(address _defaultPoolAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event LQTYTokenAddressChanged(address _lqtyTokenAddress);
event LQTYStakingAddressChanged(address _lqtyStakingAddress);
event Liquidation(uint _liquidatedDebt, uint _liquidatedColl, uint _collGasCompensation, uint _LUSDGasCompensation);
event Redemption(uint _attemptedLUSDAmount, uint _actualLUSDAmount, uint _ETHSent, uint _ETHFee);
event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation);
event TroveLiquidated(address indexed _borrower, uint _debt, uint _coll, uint8 operation);
event BaseRateUpdated(uint _baseRate);
event LastFeeOpTimeUpdated(uint _lastFeeOpTime);
event TotalStakesUpdated(uint _newTotalStakes);
event SystemSnapshotsUpdated(uint _totalStakesSnapshot, uint _totalCollateralSnapshot);
event LTermsUpdated(uint _L_ETH, uint _L_LUSDDebt);
event TroveSnapshotsUpdated(uint _L_ETH, uint _L_LUSDDebt);
event TroveIndexUpdated(address _borrower, uint _newIndex);
// --- Functions ---
function setAddresses(
address _borrowerOperationsAddress,
address _activePoolAddress,
address _defaultPoolAddress,
address _stabilityPoolAddress,
address _gasPoolAddress,
address _collSurplusPoolAddress,
address _priceFeedAddress,
address _lusdTokenAddress,
address _sortedTrovesAddress,
address _lqtyTokenAddress,
address _lqtyStakingAddress
) external;
function stabilityPool() external view returns (IStabilityPool);
function lusdToken() external view returns (ILUSDToken);
function lqtyToken() external view returns (ILQTYToken);
function lqtyStaking() external view returns (ILQTYStaking);
function getTroveOwnersCount() external view returns (uint);
function getTroveFromTroveOwnersArray(uint _index) external view returns (address);
function getNominalICR(address _borrower) external view returns (uint);
function getCurrentICR(address _borrower, uint _price) external view returns (uint);
function liquidate(address _borrower) external;
function liquidateTroves(uint _n) external;
function batchLiquidateTroves(address[] calldata _troveArray) external;
function redeemCollateral(
uint _LUSDAmount,
address _firstRedemptionHint,
address _upperPartialRedemptionHint,
address _lowerPartialRedemptionHint,
uint _partialRedemptionHintNICR,
uint _maxIterations,
uint _maxFee
) external;
function updateStakeAndTotalStakes(address _borrower) external returns (uint);
function updateTroveRewardSnapshots(address _borrower) external;
function addTroveOwnerToArray(address _borrower) external returns (uint index);
function applyPendingRewards(address _borrower) external;
function getPendingETHReward(address _borrower) external view returns (uint);
function getPendingLUSDDebtReward(address _borrower) external view returns (uint);
function hasPendingRewards(address _borrower) external view returns (bool);
function getEntireDebtAndColl(address _borrower) external view returns (
uint debt,
uint coll,
uint pendingLUSDDebtReward,
uint pendingETHReward
);
function closeTrove(address _borrower) external;
function removeStake(address _borrower) external;
function getRedemptionRate() external view returns (uint);
function getRedemptionRateWithDecay() external view returns (uint);
function getRedemptionFeeWithDecay(uint _ETHDrawn) external view returns (uint);
function getBorrowingRate() external view returns (uint);
function getBorrowingRateWithDecay() external view returns (uint);
function getBorrowingFee(uint LUSDDebt) external view returns (uint);
function getBorrowingFeeWithDecay(uint _LUSDDebt) external view returns (uint);
function decayBaseRateFromBorrowing() external;
function getTroveStatus(address _borrower) external view returns (uint);
function getTroveStake(address _borrower) external view returns (uint);
function getTroveDebt(address _borrower) external view returns (uint);
function getTroveColl(address _borrower) external view returns (uint);
function setTroveStatus(address _borrower, uint num) external;
function increaseTroveColl(address _borrower, uint _collIncrease) external returns (uint);
function decreaseTroveColl(address _borrower, uint _collDecrease) external returns (uint);
function increaseTroveDebt(address _borrower, uint _debtIncrease) external returns (uint);
function decreaseTroveDebt(address _borrower, uint _collDecrease) external returns (uint);
function getTCR(uint _price) external view returns (uint);
function checkRecoveryMode(uint _price) external view returns (bool);
}
// File contracts/Interfaces/ISortedTroves.sol
// MIT
pragma solidity 0.6.11;
// Common interface for the SortedTroves Doubly Linked List.
interface ISortedTroves {
// --- Events ---
event SortedTrovesAddressChanged(address _sortedDoublyLLAddress);
event BorrowerOperationsAddressChanged(address _borrowerOperationsAddress);
event NodeAdded(address _id, uint _NICR);
event NodeRemoved(address _id);
// --- Functions ---
function setParams(uint256 _size, address _TroveManagerAddress, address _borrowerOperationsAddress) external;
function insert(address _id, uint256 _ICR, address _prevId, address _nextId) external;
function remove(address _id) external;
function reInsert(address _id, uint256 _newICR, address _prevId, address _nextId) external;
function contains(address _id) external view returns (bool);
function isFull() external view returns (bool);
function isEmpty() external view returns (bool);
function getSize() external view returns (uint256);
function getMaxSize() external view returns (uint256);
function getFirst() external view returns (address);
function getLast() external view returns (address);
function getNext(address _id) external view returns (address);
function getPrev(address _id) external view returns (address);
function validInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (bool);
function findInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (address, address);
}
// File contracts/Interfaces/ICommunityIssuance.sol
// MIT
pragma solidity 0.6.11;
interface ICommunityIssuance {
// --- Events ---
event LQTYTokenAddressSet(address _lqtyTokenAddress);
event StabilityPoolAddressSet(address _stabilityPoolAddress);
event TotalLQTYIssuedUpdated(uint _totalLQTYIssued);
// --- Functions ---
function setAddresses(address _lqtyTokenAddress, address _stabilityPoolAddress) external;
function issueLQTY() external returns (uint);
function sendLQTY(address _account, uint _LQTYamount) external;
}
// File contracts/Dependencies/BaseMath.sol
// MIT
pragma solidity 0.6.11;
contract BaseMath {
uint constant public DECIMAL_PRECISION = 1e18;
}
// File contracts/Dependencies/SafeMath.sol
// MIT
pragma solidity 0.6.11;
/**
* Based on OpenZeppelin's SafeMath:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol
*
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File contracts/Dependencies/console.sol
// MIT
pragma solidity 0.6.11;
// Buidler's helper contract for console logging
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function log() internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log()"));
ignored;
} function logInt(int p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(int)", p0));
ignored;
}
function logUint(uint p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint)", p0));
ignored;
}
function logString(string memory p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string)", p0));
ignored;
}
function logBool(bool p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool)", p0));
ignored;
}
function logAddress(address p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address)", p0));
ignored;
}
function logBytes(bytes memory p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes)", p0));
ignored;
}
function logByte(byte p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(byte)", p0));
ignored;
}
function logBytes1(bytes1 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes1)", p0));
ignored;
}
function logBytes2(bytes2 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes2)", p0));
ignored;
}
function logBytes3(bytes3 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes3)", p0));
ignored;
}
function logBytes4(bytes4 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes4)", p0));
ignored;
}
function logBytes5(bytes5 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes5)", p0));
ignored;
}
function logBytes6(bytes6 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes6)", p0));
ignored;
}
function logBytes7(bytes7 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes7)", p0));
ignored;
}
function logBytes8(bytes8 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes8)", p0));
ignored;
}
function logBytes9(bytes9 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes9)", p0));
ignored;
}
function logBytes10(bytes10 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes10)", p0));
ignored;
}
function logBytes11(bytes11 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes11)", p0));
ignored;
}
function logBytes12(bytes12 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes12)", p0));
ignored;
}
function logBytes13(bytes13 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes13)", p0));
ignored;
}
function logBytes14(bytes14 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes14)", p0));
ignored;
}
function logBytes15(bytes15 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes15)", p0));
ignored;
}
function logBytes16(bytes16 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes16)", p0));
ignored;
}
function logBytes17(bytes17 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes17)", p0));
ignored;
}
function logBytes18(bytes18 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes18)", p0));
ignored;
}
function logBytes19(bytes19 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes19)", p0));
ignored;
}
function logBytes20(bytes20 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes20)", p0));
ignored;
}
function logBytes21(bytes21 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes21)", p0));
ignored;
}
function logBytes22(bytes22 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes22)", p0));
ignored;
}
function logBytes23(bytes23 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes23)", p0));
ignored;
}
function logBytes24(bytes24 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes24)", p0));
ignored;
}
function logBytes25(bytes25 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes25)", p0));
ignored;
}
function logBytes26(bytes26 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes26)", p0));
ignored;
}
function logBytes27(bytes27 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes27)", p0));
ignored;
}
function logBytes28(bytes28 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes28)", p0));
ignored;
}
function logBytes29(bytes29 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes29)", p0));
ignored;
}
function logBytes30(bytes30 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes30)", p0));
ignored;
}
function logBytes31(bytes31 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes31)", p0));
ignored;
}
function logBytes32(bytes32 p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bytes32)", p0));
ignored;
}
function log(uint p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint)", p0));
ignored;
}
function log(string memory p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string)", p0));
ignored;
}
function log(bool p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool)", p0));
ignored;
}
function log(address p0) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address)", p0));
ignored;
}
function log(uint p0, uint p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint)", p0, p1));
ignored;
}
function log(uint p0, string memory p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string)", p0, p1));
ignored;
}
function log(uint p0, bool p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool)", p0, p1));
ignored;
}
function log(uint p0, address p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address)", p0, p1));
ignored;
}
function log(string memory p0, uint p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint)", p0, p1));
ignored;
}
function log(string memory p0, string memory p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string)", p0, p1));
ignored;
}
function log(string memory p0, bool p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool)", p0, p1));
ignored;
}
function log(string memory p0, address p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address)", p0, p1));
ignored;
}
function log(bool p0, uint p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint)", p0, p1));
ignored;
}
function log(bool p0, string memory p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string)", p0, p1));
ignored;
}
function log(bool p0, bool p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool)", p0, p1));
ignored;
}
function log(bool p0, address p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address)", p0, p1));
ignored;
}
function log(address p0, uint p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint)", p0, p1));
ignored;
}
function log(address p0, string memory p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string)", p0, p1));
ignored;
}
function log(address p0, bool p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool)", p0, p1));
ignored;
}
function log(address p0, address p1) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address)", p0, p1));
ignored;
}
function log(uint p0, uint p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
ignored;
}
function log(uint p0, uint p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
ignored;
}
function log(uint p0, uint p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
ignored;
}
function log(uint p0, uint p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
ignored;
}
function log(uint p0, string memory p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
ignored;
}
function log(uint p0, string memory p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
ignored;
}
function log(uint p0, string memory p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
ignored;
}
function log(uint p0, string memory p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
ignored;
}
function log(uint p0, bool p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
ignored;
}
function log(uint p0, bool p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
ignored;
}
function log(uint p0, bool p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
ignored;
}
function log(uint p0, bool p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
ignored;
}
function log(uint p0, address p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
ignored;
}
function log(uint p0, address p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
ignored;
}
function log(uint p0, address p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
ignored;
}
function log(uint p0, address p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
ignored;
}
function log(string memory p0, uint p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
ignored;
}
function log(string memory p0, uint p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
ignored;
}
function log(string memory p0, uint p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
ignored;
}
function log(string memory p0, uint p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
ignored;
}
function log(string memory p0, string memory p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
ignored;
}
function log(string memory p0, string memory p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
ignored;
}
function log(string memory p0, string memory p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
ignored;
}
function log(string memory p0, string memory p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
ignored;
}
function log(string memory p0, bool p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
ignored;
}
function log(string memory p0, bool p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
ignored;
}
function log(string memory p0, bool p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
ignored;
}
function log(string memory p0, bool p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
ignored;
}
function log(string memory p0, address p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
ignored;
}
function log(string memory p0, address p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
ignored;
}
function log(string memory p0, address p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
ignored;
}
function log(string memory p0, address p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
ignored;
}
function log(bool p0, uint p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
ignored;
}
function log(bool p0, uint p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
ignored;
}
function log(bool p0, uint p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
ignored;
}
function log(bool p0, uint p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
ignored;
}
function log(bool p0, string memory p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
ignored;
}
function log(bool p0, string memory p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
ignored;
}
function log(bool p0, string memory p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
ignored;
}
function log(bool p0, string memory p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
ignored;
}
function log(bool p0, bool p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
ignored;
}
function log(bool p0, bool p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
ignored;
}
function log(bool p0, bool p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
ignored;
}
function log(bool p0, bool p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
ignored;
}
function log(bool p0, address p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
ignored;
}
function log(bool p0, address p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
ignored;
}
function log(bool p0, address p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
ignored;
}
function log(bool p0, address p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
ignored;
}
function log(address p0, uint p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
ignored;
}
function log(address p0, uint p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
ignored;
}
function log(address p0, uint p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
ignored;
}
function log(address p0, uint p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
ignored;
}
function log(address p0, string memory p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
ignored;
}
function log(address p0, string memory p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
ignored;
}
function log(address p0, string memory p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
ignored;
}
function log(address p0, string memory p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
ignored;
}
function log(address p0, bool p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
ignored;
}
function log(address p0, bool p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
ignored;
}
function log(address p0, bool p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
ignored;
}
function log(address p0, bool p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
ignored;
}
function log(address p0, address p1, uint p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
ignored;
}
function log(address p0, address p1, string memory p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
ignored;
}
function log(address p0, address p1, bool p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
ignored;
}
function log(address p0, address p1, address p2) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
ignored;
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, uint p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, bool p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(uint p0, address p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(string memory p0, address p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, uint p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, bool p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(bool p0, address p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, uint p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, string memory p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, bool p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, uint p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, uint p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, uint p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, string memory p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, bool p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, bool p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, bool p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, address p2, uint p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, address p2, string memory p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, address p2, bool p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
ignored;
}
function log(address p0, address p1, address p2, address p3) internal view {
(bool ignored, ) = CONSOLE_ADDRESS.staticcall(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
ignored;
}
}
// File contracts/Dependencies/LiquityMath.sol
// MIT
pragma solidity 0.6.11;
library LiquityMath {
using SafeMath for uint;
uint internal constant DECIMAL_PRECISION = 1e18;
/* Precision for Nominal ICR (independent of price). Rationale for the value:
*
* - Making it “too high” could lead to overflows.
* - Making it “too low” could lead to an ICR equal to zero, due to truncation from Solidity floor division.
*
* This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39 ETH,
* and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator.
*
*/
uint internal constant NICR_PRECISION = 1e20;
function _min(uint _a, uint _b) internal pure returns (uint) {
return (_a < _b) ? _a : _b;
}
function _max(uint _a, uint _b) internal pure returns (uint) {
return (_a >= _b) ? _a : _b;
}
/*
* Multiply two decimal numbers and use normal rounding rules:
* -round product up if 19'th mantissa digit >= 5
* -round product down if 19'th mantissa digit < 5
*
* Used only inside the exponentiation, _decPow().
*/
function decMul(uint x, uint y) internal pure returns (uint decProd) {
uint prod_xy = x.mul(y);
decProd = prod_xy.add(DECIMAL_PRECISION / 2).div(DECIMAL_PRECISION);
}
/*
* _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n.
*
* Uses the efficient "exponentiation by squaring" algorithm. O(log(n)) complexity.
*
* Called by two functions that represent time in units of minutes:
* 1) TroveManager._calcDecayedBaseRate
* 2) CommunityIssuance._getCumulativeIssuanceFraction
*
* The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals
* "minutes in 1000 years": 60 * 24 * 365 * 1000
*
* If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be
* negligibly different from just passing the cap, since:
*
* In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years
* In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible
*/
function _decPow(uint _base, uint _minutes) internal pure returns (uint) {
if (_minutes > 525600000) {_minutes = 525600000;} // cap to avoid overflow
if (_minutes == 0) {return DECIMAL_PRECISION;}
uint y = DECIMAL_PRECISION;
uint x = _base;
uint n = _minutes;
// Exponentiation-by-squaring
while (n > 1) {
if (n % 2 == 0) {
x = decMul(x, x);
n = n.div(2);
} else { // if (n % 2 != 0)
y = decMul(x, y);
x = decMul(x, x);
n = (n.sub(1)).div(2);
}
}
return decMul(x, y);
}
function _getAbsoluteDifference(uint _a, uint _b) internal pure returns (uint) {
return (_a >= _b) ? _a.sub(_b) : _b.sub(_a);
}
function _computeNominalCR(uint _coll, uint _debt) internal pure returns (uint) {
if (_debt > 0) {
return _coll.mul(NICR_PRECISION).div(_debt);
}
// Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR.
else { // if (_debt == 0)
return 2**256 - 1;
}
}
function _computeCR(uint _coll, uint _debt, uint _price) internal pure returns (uint) {
if (_debt > 0) {
uint newCollRatio = _coll.mul(_price).div(_debt);
return newCollRatio;
}
// Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR.
else { // if (_debt == 0)
return 2**256 - 1;
}
}
}
// File contracts/Interfaces/IPool.sol
// MIT
pragma solidity 0.6.11;
// Common interface for the Pools.
interface IPool {
// --- Events ---
event ETHBalanceUpdated(uint _newBalance);
event LUSDBalanceUpdated(uint _newBalance);
event ActivePoolAddressChanged(address _newActivePoolAddress);
event DefaultPoolAddressChanged(address _newDefaultPoolAddress);
event StabilityPoolAddressChanged(address _newStabilityPoolAddress);
event EtherSent(address _to, uint _amount);
// --- Functions ---
function getETH() external view returns (uint);
function getLUSDDebt() external view returns (uint);
function increaseLUSDDebt(uint _amount) external;
function decreaseLUSDDebt(uint _amount) external;
}
// File contracts/Interfaces/IActivePool.sol
// MIT
pragma solidity 0.6.11;
interface IActivePool is IPool {
// --- Events ---
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolLUSDDebtUpdated(uint _LUSDDebt);
event ActivePoolETHBalanceUpdated(uint _ETH);
// --- Functions ---
function sendETH(address _account, uint _amount) external;
}
// File contracts/Interfaces/IDefaultPool.sol
// MIT
pragma solidity 0.6.11;
interface IDefaultPool is IPool {
// --- Events ---
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event DefaultPoolLUSDDebtUpdated(uint _LUSDDebt);
event DefaultPoolETHBalanceUpdated(uint _ETH);
// --- Functions ---
function sendETHToActivePool(uint _amount) external;
}
// File contracts/Dependencies/LiquityBase.sol
// MIT
pragma solidity 0.6.11;
/*
* Base contract for TroveManager, BorrowerOperations and StabilityPool. Contains global system constants and
* common functions.
*/
contract LiquityBase is BaseMath, ILiquityBase {
using SafeMath for uint;
uint constant public _100pct = 1000000000000000000; // 1e18 == 100%
// Minimum collateral ratio for individual troves
uint constant public MCR = 1100000000000000000; // 110%
// Critical system collateral ratio. If the system's total collateral ratio (TCR) falls below the CCR, Recovery Mode is triggered.
uint constant public CCR = 1500000000000000000; // 150%
// Amount of LUSD to be locked in gas pool on opening troves
uint constant public LUSD_GAS_COMPENSATION = 200e18;
// Minimum amount of net LUSD debt a trove must have
uint constant public MIN_NET_DEBT = 1800e18;
// uint constant public MIN_NET_DEBT = 0;
uint constant public PERCENT_DIVISOR = 200; // dividing by 200 yields 0.5%
uint constant public BORROWING_FEE_FLOOR = DECIMAL_PRECISION / 1000 * 5; // 0.5%
IActivePool public activePool;
IDefaultPool public defaultPool;
IPriceFeed public override priceFeed;
// --- Gas compensation functions ---
// Returns the composite debt (drawn debt + gas compensation) of a trove, for the purpose of ICR calculation
function _getCompositeDebt(uint _debt) internal pure returns (uint) {
return _debt.add(LUSD_GAS_COMPENSATION);
}
function _getNetDebt(uint _debt) internal pure returns (uint) {
return _debt.sub(LUSD_GAS_COMPENSATION);
}
// Return the amount of ETH to be drawn from a trove's collateral and sent as gas compensation.
function _getCollGasCompensation(uint _entireColl) internal pure returns (uint) {
return _entireColl / PERCENT_DIVISOR;
}
function getEntireSystemColl() public view returns (uint entireSystemColl) {
uint activeColl = activePool.getETH();
uint liquidatedColl = defaultPool.getETH();
return activeColl.add(liquidatedColl);
}
function getEntireSystemDebt() public view returns (uint entireSystemDebt) {
uint activeDebt = activePool.getLUSDDebt();
uint closedDebt = defaultPool.getLUSDDebt();
return activeDebt.add(closedDebt);
}
function _getTCR(uint _price) internal view returns (uint TCR) {
uint entireSystemColl = getEntireSystemColl();
uint entireSystemDebt = getEntireSystemDebt();
TCR = LiquityMath._computeCR(entireSystemColl, entireSystemDebt, _price);
return TCR;
}
function _checkRecoveryMode(uint _price) internal view returns (bool) {
uint TCR = _getTCR(_price);
return TCR < CCR;
}
function _requireUserAcceptsFee(uint _fee, uint _amount, uint _maxFeePercentage) internal pure {
uint feePercentage = _fee.mul(DECIMAL_PRECISION).div(_amount);
require(feePercentage <= _maxFeePercentage, "Fee exceeded provided maximum");
}
}
// File contracts/Dependencies/LiquitySafeMath128.sol
// MIT
pragma solidity 0.6.11;
// uint128 addition and subtraction, with overflow protection.
library LiquitySafeMath128 {
function add(uint128 a, uint128 b) internal pure returns (uint128) {
uint128 c = a + b;
require(c >= a, "LiquitySafeMath128: addition overflow");
return c;
}
function sub(uint128 a, uint128 b) internal pure returns (uint128) {
require(b <= a, "LiquitySafeMath128: subtraction overflow");
uint128 c = a - b;
return c;
}
}
// File contracts/Dependencies/Ownable.sol
// MIT
pragma solidity 0.6.11;
/**
* Based on OpenZeppelin's Ownable contract:
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol
*
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*
* NOTE: This function is not safe, as it doesn’t check owner is calling it.
* Make sure you check it before calling it.
*/
function _renounceOwnership() internal {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
}
// File contracts/Dependencies/CheckContract.sol
// MIT
pragma solidity 0.6.11;
contract CheckContract {
/**
* Check that the account is an already deployed non-destroyed contract.
* See: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol#L12
*/
function checkContract(address _account) internal view {
require(_account != address(0), "Account cannot be zero address");
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(_account) }
require(size > 0, "Account code size cannot be zero");
}
}
// File contracts/StabilityPool.sol
// MIT
pragma solidity 0.6.11;
/*
* The Stability Pool holds LUSD tokens deposited by Stability Pool depositors.
*
* When a trove is liquidated, then depending on system conditions, some of its LUSD debt gets offset with
* LUSD in the Stability Pool: that is, the offset debt evaporates, and an equal amount of LUSD tokens in the Stability Pool is burned.
*
* Thus, a liquidation causes each depositor to receive a LUSD loss, in proportion to their deposit as a share of total deposits.
* They also receive an ETH gain, as the ETH collateral of the liquidated trove is distributed among Stability depositors,
* in the same proportion.
*
* When a liquidation occurs, it depletes every deposit by the same fraction: for example, a liquidation that depletes 40%
* of the total LUSD in the Stability Pool, depletes 40% of each deposit.
*
* A deposit that has experienced a series of liquidations is termed a "compounded deposit": each liquidation depletes the deposit,
* multiplying it by some factor in range ]0,1[
*
*
* --- IMPLEMENTATION ---
*
* We use a highly scalable method of tracking deposits and ETH gains that has O(1) complexity.
*
* When a liquidation occurs, rather than updating each depositor's deposit and ETH gain, we simply update two state variables:
* a product P, and a sum S.
*
* A mathematical manipulation allows us to factor out the initial deposit, and accurately track all depositors' compounded deposits
* and accumulated ETH gains over time, as liquidations occur, using just these two variables P and S. When depositors join the
* Stability Pool, they get a snapshot of the latest P and S: P_t and S_t, respectively.
*
* The formula for a depositor's accumulated ETH gain is derived here:
* https://github.com/liquity/dev/blob/main/packages/contracts/mathProofs/Scalable%20Compounding%20Stability%20Pool%20Deposits.pdf
*
* For a given deposit d_t, the ratio P/P_t tells us the factor by which a deposit has decreased since it joined the Stability Pool,
* and the term d_t * (S - S_t)/P_t gives us the deposit's total accumulated ETH gain.
*
* Each liquidation updates the product P and sum S. After a series of liquidations, a compounded deposit and corresponding ETH gain
* can be calculated using the initial deposit, the depositor’s snapshots of P and S, and the latest values of P and S.
*
* Any time a depositor updates their deposit (withdrawal, top-up) their accumulated ETH gain is paid out, their new deposit is recorded
* (based on their latest compounded deposit and modified by the withdrawal/top-up), and they receive new snapshots of the latest P and S.
* Essentially, they make a fresh deposit that overwrites the old one.
*
*
* --- SCALE FACTOR ---
*
* Since P is a running product in range ]0,1] that is always-decreasing, it should never reach 0 when multiplied by a number in range ]0,1[.
* Unfortunately, Solidity floor division always reaches 0, sooner or later.
*
* A series of liquidations that nearly empty the Pool (and thus each multiply P by a very small number in range ]0,1[ ) may push P
* to its 18 digit decimal limit, and round it to 0, when in fact the Pool hasn't been emptied: this would break deposit tracking.
*
* So, to track P accurately, we use a scale factor: if a liquidation would cause P to decrease to <1e-9 (and be rounded to 0 by Solidity),
* we first multiply P by 1e9, and increment a currentScale factor by 1.
*
* The added benefit of using 1e9 for the scale factor (rather than 1e18) is that it ensures negligible precision loss close to the
* scale boundary: when P is at its minimum value of 1e9, the relative precision loss in P due to floor division is only on the
* order of 1e-9.
*
* --- EPOCHS ---
*
* Whenever a liquidation fully empties the Stability Pool, all deposits should become 0. However, setting P to 0 would make P be 0
* forever, and break all future reward calculations.
*
* So, every time the Stability Pool is emptied by a liquidation, we reset P = 1 and currentScale = 0, and increment the currentEpoch by 1.
*
* --- TRACKING DEPOSIT OVER SCALE CHANGES AND EPOCHS ---
*
* When a deposit is made, it gets snapshots of the currentEpoch and the currentScale.
*
* When calculating a compounded deposit, we compare the current epoch to the deposit's epoch snapshot. If the current epoch is newer,
* then the deposit was present during a pool-emptying liquidation, and necessarily has been depleted to 0.
*
* Otherwise, we then compare the current scale to the deposit's scale snapshot. If they're equal, the compounded deposit is given by d_t * P/P_t.
* If it spans one scale change, it is given by d_t * P/(P_t * 1e9). If it spans more than one scale change, we define the compounded deposit
* as 0, since it is now less than 1e-9'th of its initial value (e.g. a deposit of 1 billion LUSD has depleted to < 1 LUSD).
*
*
* --- TRACKING DEPOSITOR'S ETH GAIN OVER SCALE CHANGES AND EPOCHS ---
*
* In the current epoch, the latest value of S is stored upon each scale change, and the mapping (scale -> S) is stored for each epoch.
*
* This allows us to calculate a deposit's accumulated ETH gain, during the epoch in which the deposit was non-zero and earned ETH.
*
* We calculate the depositor's accumulated ETH gain for the scale at which they made the deposit, using the ETH gain formula:
* e_1 = d_t * (S - S_t) / P_t
*
* and also for scale after, taking care to divide the latter by a factor of 1e9:
* e_2 = d_t * S / (P_t * 1e9)
*
* The gain in the second scale will be full, as the starting point was in the previous scale, thus no need to subtract anything.
* The deposit therefore was present for reward events from the beginning of that second scale.
*
* S_i-S_t + S_{i+1}
* .<--------.------------>
* . .
* . S_i . S_{i+1}
* <--.-------->.<----------->
* S_t. .
* <->. .
* t .
* |---+---------|-------------|-----...
* i i+1
*
* The sum of (e_1 + e_2) captures the depositor's total accumulated ETH gain, handling the case where their
* deposit spanned one scale change. We only care about gains across one scale change, since the compounded
* deposit is defined as being 0 once it has spanned more than one scale change.
*
*
* --- UPDATING P WHEN A LIQUIDATION OCCURS ---
*
* Please see the implementation spec in the proof document, which closely follows on from the compounded deposit / ETH gain derivations:
* https://github.com/liquity/liquity/blob/master/papers/Scalable_Reward_Distribution_with_Compounding_Stakes.pdf
*
*
* --- LQTY ISSUANCE TO STABILITY POOL DEPOSITORS ---
*
* An LQTY issuance event occurs at every deposit operation, and every liquidation.
*
* Each deposit is tagged with the address of the front end through which it was made.
*
* All deposits earn a share of the issued LQTY in proportion to the deposit as a share of total deposits. The LQTY earned
* by a given deposit, is split between the depositor and the front end through which the deposit was made, based on the front end's kickbackRate.
*
* Please see the system Readme for an overview:
* https://github.com/liquity/dev/blob/main/README.md#lqty-issuance-to-stability-providers
*
* We use the same mathematical product-sum approach to track LQTY gains for depositors, where 'G' is the sum corresponding to LQTY gains.
* The product P (and snapshot P_t) is re-used, as the ratio P/P_t tracks a deposit's depletion due to liquidations.
*
*/
contract StabilityPool is LiquityBase, Ownable, CheckContract, IStabilityPool {
using LiquitySafeMath128 for uint128;
string constant public NAME = "StabilityPool";
IBorrowerOperations public borrowerOperations;
ITroveManager public troveManager;
ILUSDToken public lusdToken;
// Needed to check if there are pending liquidations
ISortedTroves public sortedTroves;
ICommunityIssuance public communityIssuance;
uint256 internal ETH; // deposited ether tracker
// Tracker for LUSD held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset.
uint256 internal totalLUSDDeposits;
// --- Data structures ---
struct FrontEnd {
uint kickbackRate;
bool registered;
}
struct Deposit {
uint initialValue;
address frontEndTag;
}
struct Snapshots {
uint S;
uint P;
uint G;
uint128 scale;
uint128 epoch;
}
mapping (address => Deposit) public deposits; // depositor address -> Deposit struct
mapping (address => Snapshots) public depositSnapshots; // depositor address -> snapshots struct
mapping (address => FrontEnd) public frontEnds; // front end address -> FrontEnd struct
mapping (address => uint) public frontEndStakes; // front end address -> last recorded total deposits, tagged with that front end
mapping (address => Snapshots) public frontEndSnapshots; // front end address -> snapshots struct
/* Product 'P': Running product by which to multiply an initial deposit, in order to find the current compounded deposit,
* after a series of liquidations have occurred, each of which cancel some LUSD debt with the deposit.
*
* During its lifetime, a deposit's value evolves from d_t to d_t * P / P_t , where P_t
* is the snapshot of P taken at the instant the deposit was made. 18-digit decimal.
*/
uint public P = DECIMAL_PRECISION;
uint public constant SCALE_FACTOR = 1e9;
// Each time the scale of P shifts by SCALE_FACTOR, the scale is incremented by 1
uint128 public currentScale;
// With each offset that fully empties the Pool, the epoch is incremented by 1
uint128 public currentEpoch;
/* ETH Gain sum 'S': During its lifetime, each deposit d_t earns an ETH gain of ( d_t * [S - S_t] )/P_t, where S_t
* is the depositor's snapshot of S taken at the time t when the deposit was made.
*
* The 'S' sums are stored in a nested mapping (epoch => scale => sum):
*
* - The inner mapping records the sum S at different scales
* - The outer mapping records the (scale => sum) mappings, for different epochs.
*/
mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToSum;
/*
* Similarly, the sum 'G' is used to calculate LQTY gains. During it's lifetime, each deposit d_t earns a LQTY gain of
* ( d_t * [G - G_t] )/P_t, where G_t is the depositor's snapshot of G taken at time t when the deposit was made.
*
* LQTY reward events occur are triggered by depositor operations (new deposit, topup, withdrawal), and liquidations.
* In each case, the LQTY reward is issued (i.e. G is updated), before other state changes are made.
*/
mapping (uint128 => mapping(uint128 => uint)) public epochToScaleToG;
// Error tracker for the error correction in the LQTY issuance calculation
uint public lastLQTYError;
// Error trackers for the error correction in the offset calculation
uint public lastETHError_Offset;
uint public lastLUSDLossError_Offset;
// --- Events ---
event StabilityPoolETHBalanceUpdated(uint _newBalance);
event StabilityPoolLUSDBalanceUpdated(uint _newBalance);
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _newActivePoolAddress);
event DefaultPoolAddressChanged(address _newDefaultPoolAddress);
event LUSDTokenAddressChanged(address _newLUSDTokenAddress);
event SortedTrovesAddressChanged(address _newSortedTrovesAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress);
event P_Updated(uint _P);
event S_Updated(uint _S, uint128 _epoch, uint128 _scale);
event G_Updated(uint _G, uint128 _epoch, uint128 _scale);
event EpochUpdated(uint128 _currentEpoch);
event ScaleUpdated(uint128 _currentScale);
event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate);
event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd);
event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G);
event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G);
event UserDepositChanged(address indexed _depositor, uint _newDeposit);
event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor);
event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _LUSDLoss);
event LQTYPaidToDepositor(address indexed _depositor, uint _LQTY);
event LQTYPaidToFrontEnd(address indexed _frontEnd, uint _LQTY);
event EtherSent(address _to, uint _amount);
// --- Contract setters ---
function setAddresses(
address _borrowerOperationsAddress,
address _troveManagerAddress,
address _activePoolAddress,
address _lusdTokenAddress,
address _sortedTrovesAddress,
address _priceFeedAddress,
address _communityIssuanceAddress
)
external
override
onlyOwner
{
checkContract(_borrowerOperationsAddress);
checkContract(_troveManagerAddress);
checkContract(_activePoolAddress);
checkContract(_lusdTokenAddress);
checkContract(_sortedTrovesAddress);
checkContract(_priceFeedAddress);
checkContract(_communityIssuanceAddress);
borrowerOperations = IBorrowerOperations(_borrowerOperationsAddress);
troveManager = ITroveManager(_troveManagerAddress);
activePool = IActivePool(_activePoolAddress);
lusdToken = ILUSDToken(_lusdTokenAddress);
sortedTroves = ISortedTroves(_sortedTrovesAddress);
priceFeed = IPriceFeed(_priceFeedAddress);
communityIssuance = ICommunityIssuance(_communityIssuanceAddress);
emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress);
emit TroveManagerAddressChanged(_troveManagerAddress);
emit ActivePoolAddressChanged(_activePoolAddress);
emit LUSDTokenAddressChanged(_lusdTokenAddress);
emit SortedTrovesAddressChanged(_sortedTrovesAddress);
emit PriceFeedAddressChanged(_priceFeedAddress);
emit CommunityIssuanceAddressChanged(_communityIssuanceAddress);
_renounceOwnership();
}
// --- Getters for public variables. Required by IPool interface ---
function getETH() external view override returns (uint) {
return ETH;
}
function getTotalLUSDDeposits() external view override returns (uint) {
return totalLUSDDeposits;
}
// --- External Depositor Functions ---
/* provideToSP():
*
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Tags the deposit with the provided front end tag param, if it's a new deposit
* - Sends depositor's accumulated gains (LQTY, ETH) to depositor
* - Sends the tagged front end's accumulated LQTY gains to the tagged front end
* - Increases deposit and tagged front end's stake, and takes new snapshots for each.
*/
function provideToSP(uint _amount, address _frontEndTag) external override {
_requireFrontEndIsRegisteredOrZero(_frontEndTag);
_requireFrontEndNotRegistered(msg.sender);
_requireNonZeroAmount(_amount);
uint initialDeposit = deposits[msg.sender].initialValue;
ICommunityIssuance communityIssuanceCached = communityIssuance;
_triggerLQTYIssuance(communityIssuanceCached);
if (initialDeposit == 0) {_setFrontEndTag(msg.sender, _frontEndTag);}
uint depositorETHGain = getDepositorETHGain(msg.sender);
uint compoundedLUSDDeposit = getCompoundedLUSDDeposit(msg.sender);
uint LUSDLoss = initialDeposit.sub(compoundedLUSDDeposit); // Needed only for event log
// First pay out any LQTY gains
address frontEnd = deposits[msg.sender].frontEndTag;
_payOutLQTYGains(communityIssuanceCached, msg.sender, frontEnd);
// Update front end stake
uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd);
uint newFrontEndStake = compoundedFrontEndStake.add(_amount);
_updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake);
emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender);
_sendLUSDtoStabilityPool(msg.sender, _amount);
uint newDeposit = compoundedLUSDDeposit.add(_amount);
_updateDepositAndSnapshots(msg.sender, newDeposit);
emit UserDepositChanged(msg.sender, newDeposit);
emit ETHGainWithdrawn(msg.sender, depositorETHGain, LUSDLoss); // LUSD Loss required for event log
_sendETHGainToDepositor(depositorETHGain);
}
/* withdrawFromSP():
*
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Removes the deposit's front end tag if it is a full withdrawal
* - Sends all depositor's accumulated gains (LQTY, ETH) to depositor
* - Sends the tagged front end's accumulated LQTY gains to the tagged front end
* - Decreases deposit and tagged front end's stake, and takes new snapshots for each.
*
* If _amount > userDeposit, the user withdraws all of their compounded deposit.
*/
function withdrawFromSP(uint _amount) external override {
if (_amount !=0) {_requireNoUnderCollateralizedTroves();}
uint initialDeposit = deposits[msg.sender].initialValue;
_requireUserHasDeposit(initialDeposit);
ICommunityIssuance communityIssuanceCached = communityIssuance;
_triggerLQTYIssuance(communityIssuanceCached);
uint depositorETHGain = getDepositorETHGain(msg.sender);
uint compoundedLUSDDeposit = getCompoundedLUSDDeposit(msg.sender);
uint LUSDtoWithdraw = LiquityMath._min(_amount, compoundedLUSDDeposit);
uint LUSDLoss = initialDeposit.sub(compoundedLUSDDeposit); // Needed only for event log
// First pay out any LQTY gains
address frontEnd = deposits[msg.sender].frontEndTag;
_payOutLQTYGains(communityIssuanceCached, msg.sender, frontEnd);
// Update front end stake
uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd);
uint newFrontEndStake = compoundedFrontEndStake.sub(LUSDtoWithdraw);
_updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake);
emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender);
_sendLUSDToDepositor(msg.sender, LUSDtoWithdraw);
// Update deposit
uint newDeposit = compoundedLUSDDeposit.sub(LUSDtoWithdraw);
_updateDepositAndSnapshots(msg.sender, newDeposit);
emit UserDepositChanged(msg.sender, newDeposit);
emit ETHGainWithdrawn(msg.sender, depositorETHGain, LUSDLoss); // LUSD Loss required for event log
_sendETHGainToDepositor(depositorETHGain);
}
/* withdrawETHGainToTrove:
* - Triggers a LQTY issuance, based on time passed since the last issuance. The LQTY issuance is shared between *all* depositors and front ends
* - Sends all depositor's LQTY gain to depositor
* - Sends all tagged front end's LQTY gain to the tagged front end
* - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove
* - Leaves their compounded deposit in the Stability Pool
* - Updates snapshots for deposit and tagged front end stake */
function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external override {
uint initialDeposit = deposits[msg.sender].initialValue;
_requireUserHasDeposit(initialDeposit);
_requireUserHasTrove(msg.sender);
_requireUserHasETHGain(msg.sender);
ICommunityIssuance communityIssuanceCached = communityIssuance;
_triggerLQTYIssuance(communityIssuanceCached);
uint depositorETHGain = getDepositorETHGain(msg.sender);
uint compoundedLUSDDeposit = getCompoundedLUSDDeposit(msg.sender);
uint LUSDLoss = initialDeposit.sub(compoundedLUSDDeposit); // Needed only for event log
// First pay out any LQTY gains
address frontEnd = deposits[msg.sender].frontEndTag;
_payOutLQTYGains(communityIssuanceCached, msg.sender, frontEnd);
// Update front end stake
uint compoundedFrontEndStake = getCompoundedFrontEndStake(frontEnd);
uint newFrontEndStake = compoundedFrontEndStake;
_updateFrontEndStakeAndSnapshots(frontEnd, newFrontEndStake);
emit FrontEndStakeChanged(frontEnd, newFrontEndStake, msg.sender);
_updateDepositAndSnapshots(msg.sender, compoundedLUSDDeposit);
/* Emit events before transferring ETH gain to Trove.
This lets the event log make more sense (i.e. so it appears that first the ETH gain is withdrawn
and then it is deposited into the Trove, not the other way around). */
emit ETHGainWithdrawn(msg.sender, depositorETHGain, LUSDLoss);
emit UserDepositChanged(msg.sender, compoundedLUSDDeposit);
ETH = ETH.sub(depositorETHGain);
emit StabilityPoolETHBalanceUpdated(ETH);
emit EtherSent(msg.sender, depositorETHGain);
borrowerOperations.moveETHGainToTrove{ value: depositorETHGain }(msg.sender, _upperHint, _lowerHint);
}
// --- LQTY issuance functions ---
function _triggerLQTYIssuance(ICommunityIssuance _communityIssuance) internal {
uint LQTYIssuance = _communityIssuance.issueLQTY();
_updateG(LQTYIssuance);
}
function _updateG(uint _LQTYIssuance) internal {
uint totalLUSD = totalLUSDDeposits; // cached to save an SLOAD
/*
* When total deposits is 0, G is not updated. In this case, the LQTY issued can not be obtained by later
* depositors - it is missed out on, and remains in the balanceof the CommunityIssuance contract.
*
*/
if (totalLUSD == 0 || _LQTYIssuance == 0) {return;}
uint LQTYPerUnitStaked;
LQTYPerUnitStaked =_computeLQTYPerUnitStaked(_LQTYIssuance, totalLUSD);
uint marginalLQTYGain = LQTYPerUnitStaked.mul(P);
epochToScaleToG[currentEpoch][currentScale] = epochToScaleToG[currentEpoch][currentScale].add(marginalLQTYGain);
emit G_Updated(epochToScaleToG[currentEpoch][currentScale], currentEpoch, currentScale);
}
function _computeLQTYPerUnitStaked(uint _LQTYIssuance, uint _totalLUSDDeposits) internal returns (uint) {
/*
* Calculate the LQTY-per-unit staked. Division uses a "feedback" error correction, to keep the
* cumulative error low in the running total G:
*
* 1) Form a numerator which compensates for the floor division error that occurred the last time this
* function was called.
* 2) Calculate "per-unit-staked" ratio.
* 3) Multiply the ratio back by its denominator, to reveal the current floor division error.
* 4) Store this error for use in the next correction when this function is called.
* 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended.
*/
uint LQTYNumerator = _LQTYIssuance.mul(DECIMAL_PRECISION).add(lastLQTYError);
uint LQTYPerUnitStaked = LQTYNumerator.div(_totalLUSDDeposits);
lastLQTYError = LQTYNumerator.sub(LQTYPerUnitStaked.mul(_totalLUSDDeposits));
return LQTYPerUnitStaked;
}
// --- Liquidation functions ---
/*
* Cancels out the specified debt against the LUSD contained in the Stability Pool (as far as possible)
* and transfers the Trove's ETH collateral from ActivePool to StabilityPool.
* Only called by liquidation functions in the TroveManager.
*/
function offset(uint _debtToOffset, uint _collToAdd) external override {
_requireCallerIsTroveManager();
uint totalLUSD = totalLUSDDeposits; // cached to save an SLOAD
if (totalLUSD == 0 || _debtToOffset == 0) { return; }
_triggerLQTYIssuance(communityIssuance);
(uint ETHGainPerUnitStaked,
uint LUSDLossPerUnitStaked) = _computeRewardsPerUnitStaked(_collToAdd, _debtToOffset, totalLUSD);
_updateRewardSumAndProduct(ETHGainPerUnitStaked, LUSDLossPerUnitStaked); // updates S and P
_moveOffsetCollAndDebt(_collToAdd, _debtToOffset);
}
// --- Offset helper functions ---
function _computeRewardsPerUnitStaked(
uint _collToAdd,
uint _debtToOffset,
uint _totalLUSDDeposits
)
internal
returns (uint ETHGainPerUnitStaked, uint LUSDLossPerUnitStaked)
{
/*
* Compute the LUSD and ETH rewards. Uses a "feedback" error correction, to keep
* the cumulative error in the P and S state variables low:
*
* 1) Form numerators which compensate for the floor division errors that occurred the last time this
* function was called.
* 2) Calculate "per-unit-staked" ratios.
* 3) Multiply each ratio back by its denominator, to reveal the current floor division error.
* 4) Store these errors for use in the next correction when this function is called.
* 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended.
*/
uint ETHNumerator = _collToAdd.mul(DECIMAL_PRECISION).add(lastETHError_Offset);
assert(_debtToOffset <= _totalLUSDDeposits);
if (_debtToOffset == _totalLUSDDeposits) {
LUSDLossPerUnitStaked = DECIMAL_PRECISION; // When the Pool depletes to 0, so does each deposit
lastLUSDLossError_Offset = 0;
} else {
uint LUSDLossNumerator = _debtToOffset.mul(DECIMAL_PRECISION).sub(lastLUSDLossError_Offset);
/*
* Add 1 to make error in quotient positive. We want "slightly too much" LUSD loss,
* which ensures the error in any given compoundedLUSDDeposit favors the Stability Pool.
*/
LUSDLossPerUnitStaked = (LUSDLossNumerator.div(_totalLUSDDeposits)).add(1);
lastLUSDLossError_Offset = (LUSDLossPerUnitStaked.mul(_totalLUSDDeposits)).sub(LUSDLossNumerator);
}
ETHGainPerUnitStaked = ETHNumerator.div(_totalLUSDDeposits);
lastETHError_Offset = ETHNumerator.sub(ETHGainPerUnitStaked.mul(_totalLUSDDeposits));
return (ETHGainPerUnitStaked, LUSDLossPerUnitStaked);
}
// Update the Stability Pool reward sum S and product P
function _updateRewardSumAndProduct(uint _ETHGainPerUnitStaked, uint _LUSDLossPerUnitStaked) internal {
uint currentP = P;
uint newP;
assert(_LUSDLossPerUnitStaked <= DECIMAL_PRECISION);
/*
* The newProductFactor is the factor by which to change all deposits, due to the depletion of Stability Pool LUSD in the liquidation.
* We make the product factor 0 if there was a pool-emptying. Otherwise, it is (1 - LUSDLossPerUnitStaked)
*/
uint newProductFactor = uint(DECIMAL_PRECISION).sub(_LUSDLossPerUnitStaked);
uint128 currentScaleCached = currentScale;
uint128 currentEpochCached = currentEpoch;
uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached];
/*
* Calculate the new S first, before we update P.
* The ETH gain for any given depositor from a liquidation depends on the value of their deposit
* (and the value of totalDeposits) prior to the Stability being depleted by the debt in the liquidation.
*
* Since S corresponds to ETH gain, and P to deposit loss, we update S first.
*/
uint marginalETHGain = _ETHGainPerUnitStaked.mul(currentP);
uint newS = currentS.add(marginalETHGain);
epochToScaleToSum[currentEpochCached][currentScaleCached] = newS;
emit S_Updated(newS, currentEpochCached, currentScaleCached);
// If the Stability Pool was emptied, increment the epoch, and reset the scale and product P
if (newProductFactor == 0) {
currentEpoch = currentEpochCached.add(1);
emit EpochUpdated(currentEpoch);
currentScale = 0;
emit ScaleUpdated(currentScale);
newP = DECIMAL_PRECISION;
// If multiplying P by a non-zero product factor would reduce P below the scale boundary, increment the scale
} else if (currentP.mul(newProductFactor).div(DECIMAL_PRECISION) < SCALE_FACTOR) {
newP = currentP.mul(newProductFactor).mul(SCALE_FACTOR).div(DECIMAL_PRECISION);
currentScale = currentScaleCached.add(1);
emit ScaleUpdated(currentScale);
} else {
newP = currentP.mul(newProductFactor).div(DECIMAL_PRECISION);
}
assert(newP > 0);
P = newP;
emit P_Updated(newP);
}
function _moveOffsetCollAndDebt(uint _collToAdd, uint _debtToOffset) internal {
IActivePool activePoolCached = activePool;
// Cancel the liquidated LUSD debt with the LUSD in the stability pool
activePoolCached.decreaseLUSDDebt(_debtToOffset);
_decreaseLUSD(_debtToOffset);
// Burn the debt that was successfully offset
lusdToken.burn(address(this), _debtToOffset);
activePoolCached.sendETH(address(this), _collToAdd);
}
function _decreaseLUSD(uint _amount) internal {
uint newTotalLUSDDeposits = totalLUSDDeposits.sub(_amount);
totalLUSDDeposits = newTotalLUSDDeposits;
emit StabilityPoolLUSDBalanceUpdated(newTotalLUSDDeposits);
}
// --- Reward calculator functions for depositor and front end ---
/* Calculates the ETH gain earned by the deposit since its last snapshots were taken.
* Given by the formula: E = d0 * (S - S(0))/P(0)
* where S(0) and P(0) are the depositor's snapshots of the sum S and product P, respectively.
* d0 is the last recorded deposit value.
*/
function getDepositorETHGain(address _depositor) public view override returns (uint) {
uint initialDeposit = deposits[_depositor].initialValue;
if (initialDeposit == 0) { return 0; }
Snapshots memory snapshots = depositSnapshots[_depositor];
uint ETHGain = _getETHGainFromSnapshots(initialDeposit, snapshots);
return ETHGain;
}
function _getETHGainFromSnapshots(uint initialDeposit, Snapshots memory snapshots) internal view returns (uint) {
/*
* Grab the sum 'S' from the epoch at which the stake was made. The ETH gain may span up to one scale change.
* If it does, the second portion of the ETH gain is scaled by 1e9.
* If the gain spans no scale change, the second portion will be 0.
*/
uint128 epochSnapshot = snapshots.epoch;
uint128 scaleSnapshot = snapshots.scale;
uint S_Snapshot = snapshots.S;
uint P_Snapshot = snapshots.P;
uint firstPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot].sub(S_Snapshot);
uint secondPortion = epochToScaleToSum[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR);
uint ETHGain = initialDeposit.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION);
return ETHGain;
}
/*
* Calculate the LQTY gain earned by a deposit since its last snapshots were taken.
* Given by the formula: LQTY = d0 * (G - G(0))/P(0)
* where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively.
* d0 is the last recorded deposit value.
*/
function getDepositorLQTYGain(address _depositor) public view override returns (uint) {
uint initialDeposit = deposits[_depositor].initialValue;
if (initialDeposit == 0) {return 0;}
address frontEndTag = deposits[_depositor].frontEndTag;
/*
* If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned.
* Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through
* which they made their deposit.
*/
uint kickbackRate = frontEndTag == address(0) ? DECIMAL_PRECISION : frontEnds[frontEndTag].kickbackRate;
Snapshots memory snapshots = depositSnapshots[_depositor];
uint LQTYGain = kickbackRate.mul(_getLQTYGainFromSnapshots(initialDeposit, snapshots)).div(DECIMAL_PRECISION);
return LQTYGain;
}
/*
* Return the LQTY gain earned by the front end. Given by the formula: E = D0 * (G - G(0))/P(0)
* where G(0) and P(0) are the depositor's snapshots of the sum G and product P, respectively.
*
* D0 is the last recorded value of the front end's total tagged deposits.
*/
function getFrontEndLQTYGain(address _frontEnd) public view override returns (uint) {
uint frontEndStake = frontEndStakes[_frontEnd];
if (frontEndStake == 0) { return 0; }
uint kickbackRate = frontEnds[_frontEnd].kickbackRate;
uint frontEndShare = uint(DECIMAL_PRECISION).sub(kickbackRate);
Snapshots memory snapshots = frontEndSnapshots[_frontEnd];
uint LQTYGain = frontEndShare.mul(_getLQTYGainFromSnapshots(frontEndStake, snapshots)).div(DECIMAL_PRECISION);
return LQTYGain;
}
function _getLQTYGainFromSnapshots(uint initialStake, Snapshots memory snapshots) internal view returns (uint) {
/*
* Grab the sum 'G' from the epoch at which the stake was made. The LQTY gain may span up to one scale change.
* If it does, the second portion of the LQTY gain is scaled by 1e9.
* If the gain spans no scale change, the second portion will be 0.
*/
uint128 epochSnapshot = snapshots.epoch;
uint128 scaleSnapshot = snapshots.scale;
uint G_Snapshot = snapshots.G;
uint P_Snapshot = snapshots.P;
uint firstPortion = epochToScaleToG[epochSnapshot][scaleSnapshot].sub(G_Snapshot);
uint secondPortion = epochToScaleToG[epochSnapshot][scaleSnapshot.add(1)].div(SCALE_FACTOR);
uint LQTYGain = initialStake.mul(firstPortion.add(secondPortion)).div(P_Snapshot).div(DECIMAL_PRECISION);
return LQTYGain;
}
// --- Compounded deposit and compounded front end stake ---
/*
* Return the user's compounded deposit. Given by the formula: d = d0 * P/P(0)
* where P(0) is the depositor's snapshot of the product P, taken when they last updated their deposit.
*/
function getCompoundedLUSDDeposit(address _depositor) public view override returns (uint) {
uint initialDeposit = deposits[_depositor].initialValue;
if (initialDeposit == 0) { return 0; }
Snapshots memory snapshots = depositSnapshots[_depositor];
uint compoundedDeposit = _getCompoundedStakeFromSnapshots(initialDeposit, snapshots);
return compoundedDeposit;
}
/*
* Return the front end's compounded stake. Given by the formula: D = D0 * P/P(0)
* where P(0) is the depositor's snapshot of the product P, taken at the last time
* when one of the front end's tagged deposits updated their deposit.
*
* The front end's compounded stake is equal to the sum of its depositors' compounded deposits.
*/
function getCompoundedFrontEndStake(address _frontEnd) public view override returns (uint) {
uint frontEndStake = frontEndStakes[_frontEnd];
if (frontEndStake == 0) { return 0; }
Snapshots memory snapshots = frontEndSnapshots[_frontEnd];
uint compoundedFrontEndStake = _getCompoundedStakeFromSnapshots(frontEndStake, snapshots);
return compoundedFrontEndStake;
}
// Internal function, used to calculcate compounded deposits and compounded front end stakes.
function _getCompoundedStakeFromSnapshots(
uint initialStake,
Snapshots memory snapshots
)
internal
view
returns (uint)
{
uint snapshot_P = snapshots.P;
uint128 scaleSnapshot = snapshots.scale;
uint128 epochSnapshot = snapshots.epoch;
// If stake was made before a pool-emptying event, then it has been fully cancelled with debt -- so, return 0
if (epochSnapshot < currentEpoch) { return 0; }
uint compoundedStake;
uint128 scaleDiff = currentScale.sub(scaleSnapshot);
/* Compute the compounded stake. If a scale change in P was made during the stake's lifetime,
* account for it. If more than one scale change was made, then the stake has decreased by a factor of
* at least 1e-9 -- so return 0.
*/
if (scaleDiff == 0) {
compoundedStake = initialStake.mul(P).div(snapshot_P);
} else if (scaleDiff == 1) {
compoundedStake = initialStake.mul(P).div(snapshot_P).div(SCALE_FACTOR);
} else { // if scaleDiff >= 2
compoundedStake = 0;
}
/*
* If compounded deposit is less than a billionth of the initial deposit, return 0.
*
* NOTE: originally, this line was in place to stop rounding errors making the deposit too large. However, the error
* corrections should ensure the error in P "favors the Pool", i.e. any given compounded deposit should slightly less
* than it's theoretical value.
*
* Thus it's unclear whether this line is still really needed.
*/
if (compoundedStake < initialStake.div(1e9)) {return 0;}
return compoundedStake;
}
// --- Sender functions for LUSD deposit, ETH gains and LQTY gains ---
// Transfer the LUSD tokens from the user to the Stability Pool's address, and update its recorded LUSD
function _sendLUSDtoStabilityPool(address _address, uint _amount) internal {
lusdToken.sendToPool(_address, address(this), _amount);
uint newTotalLUSDDeposits = totalLUSDDeposits.add(_amount);
totalLUSDDeposits = newTotalLUSDDeposits;
emit StabilityPoolLUSDBalanceUpdated(newTotalLUSDDeposits);
}
function _sendETHGainToDepositor(uint _amount) internal {
if (_amount == 0) {return;}
uint newETH = ETH.sub(_amount);
ETH = newETH;
emit StabilityPoolETHBalanceUpdated(newETH);
emit EtherSent(msg.sender, _amount);
(bool success, ) = msg.sender.call{ value: _amount }("");
require(success, "StabilityPool: sending ETH failed");
}
// Send LUSD to user and decrease LUSD in Pool
function _sendLUSDToDepositor(address _depositor, uint LUSDWithdrawal) internal {
if (LUSDWithdrawal == 0) {return;}
lusdToken.returnFromPool(address(this), _depositor, LUSDWithdrawal);
_decreaseLUSD(LUSDWithdrawal);
}
// --- External Front End functions ---
// Front end makes a one-time selection of kickback rate upon registering
function registerFrontEnd(uint _kickbackRate) external override {
_requireFrontEndNotRegistered(msg.sender);
_requireUserHasNoDeposit(msg.sender);
_requireValidKickbackRate(_kickbackRate);
frontEnds[msg.sender].kickbackRate = _kickbackRate;
frontEnds[msg.sender].registered = true;
emit FrontEndRegistered(msg.sender, _kickbackRate);
}
// --- Stability Pool Deposit Functionality ---
function _setFrontEndTag(address _depositor, address _frontEndTag) internal {
deposits[_depositor].frontEndTag = _frontEndTag;
emit FrontEndTagSet(_depositor, _frontEndTag);
}
function _updateDepositAndSnapshots(address _depositor, uint _newValue) internal {
deposits[_depositor].initialValue = _newValue;
if (_newValue == 0) {
delete deposits[_depositor].frontEndTag;
delete depositSnapshots[_depositor];
emit DepositSnapshotUpdated(_depositor, 0, 0, 0);
return;
}
uint128 currentScaleCached = currentScale;
uint128 currentEpochCached = currentEpoch;
uint currentP = P;
// Get S and G for the current epoch and current scale
uint currentS = epochToScaleToSum[currentEpochCached][currentScaleCached];
uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached];
// Record new snapshots of the latest running product P, sum S, and sum G, for the depositor
depositSnapshots[_depositor].P = currentP;
depositSnapshots[_depositor].S = currentS;
depositSnapshots[_depositor].G = currentG;
depositSnapshots[_depositor].scale = currentScaleCached;
depositSnapshots[_depositor].epoch = currentEpochCached;
emit DepositSnapshotUpdated(_depositor, currentP, currentS, currentG);
}
function _updateFrontEndStakeAndSnapshots(address _frontEnd, uint _newValue) internal {
frontEndStakes[_frontEnd] = _newValue;
if (_newValue == 0) {
delete frontEndSnapshots[_frontEnd];
emit FrontEndSnapshotUpdated(_frontEnd, 0, 0);
return;
}
uint128 currentScaleCached = currentScale;
uint128 currentEpochCached = currentEpoch;
uint currentP = P;
// Get G for the current epoch and current scale
uint currentG = epochToScaleToG[currentEpochCached][currentScaleCached];
// Record new snapshots of the latest running product P and sum G for the front end
frontEndSnapshots[_frontEnd].P = currentP;
frontEndSnapshots[_frontEnd].G = currentG;
frontEndSnapshots[_frontEnd].scale = currentScaleCached;
frontEndSnapshots[_frontEnd].epoch = currentEpochCached;
emit FrontEndSnapshotUpdated(_frontEnd, currentP, currentG);
}
function _payOutLQTYGains(ICommunityIssuance _communityIssuance, address _depositor, address _frontEnd) internal {
// Pay out front end's LQTY gain
if (_frontEnd != address(0)) {
uint frontEndLQTYGain = getFrontEndLQTYGain(_frontEnd);
_communityIssuance.sendLQTY(_frontEnd, frontEndLQTYGain);
emit LQTYPaidToFrontEnd(_frontEnd, frontEndLQTYGain);
}
// Pay out depositor's LQTY gain
uint depositorLQTYGain = getDepositorLQTYGain(_depositor);
_communityIssuance.sendLQTY(_depositor, depositorLQTYGain);
emit LQTYPaidToDepositor(_depositor, depositorLQTYGain);
}
// --- 'require' functions ---
function _requireCallerIsActivePool() internal view {
require( msg.sender == address(activePool), "StabilityPool: Caller is not ActivePool");
}
function _requireCallerIsTroveManager() internal view {
require(msg.sender == address(troveManager), "StabilityPool: Caller is not TroveManager");
}
function _requireNoUnderCollateralizedTroves() internal {
uint price = priceFeed.fetchPrice();
address lowestTrove = sortedTroves.getLast();
uint ICR = troveManager.getCurrentICR(lowestTrove, price);
require(ICR >= MCR, "StabilityPool: Cannot withdraw while there are troves with ICR < MCR");
}
function _requireUserHasDeposit(uint _initialDeposit) internal pure {
require(_initialDeposit > 0, 'StabilityPool: User must have a non-zero deposit');
}
function _requireUserHasNoDeposit(address _address) internal view {
uint initialDeposit = deposits[_address].initialValue;
require(initialDeposit == 0, 'StabilityPool: User must have no deposit');
}
function _requireNonZeroAmount(uint _amount) internal pure {
require(_amount > 0, 'StabilityPool: Amount must be non-zero');
}
function _requireUserHasTrove(address _depositor) internal view {
require(troveManager.getTroveStatus(_depositor) == 1, "StabilityPool: caller must have an active trove to withdraw ETHGain to");
}
function _requireUserHasETHGain(address _depositor) internal view {
uint ETHGain = getDepositorETHGain(_depositor);
require(ETHGain > 0, "StabilityPool: caller must have non-zero ETH Gain");
}
function _requireFrontEndNotRegistered(address _address) internal view {
require(!frontEnds[_address].registered, "StabilityPool: must not already be a registered front end");
}
function _requireFrontEndIsRegisteredOrZero(address _address) internal view {
require(frontEnds[_address].registered || _address == address(0),
"StabilityPool: Tag must be a registered front end, or the zero address");
}
function _requireValidKickbackRate(uint _kickbackRate) internal pure {
require (_kickbackRate <= DECIMAL_PRECISION, "StabilityPool: Kickback rate must be in range [0,1]");
}
// --- Fallback function ---
receive() external payable {
_requireCallerIsActivePool();
ETH = ETH.add(msg.value);
StabilityPoolETHBalanceUpdated(ETH);
}
}
// File contracts/B.Protocol/crop.sol
// AGPL-3.0-or-later
// Copyright (C) 2021 Dai Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pragma solidity 0.6.11;
interface VatLike {
function urns(bytes32, address) external view returns (uint256, uint256);
function gem(bytes32, address) external view returns (uint256);
function slip(bytes32, address, int256) external;
}
interface ERC20 {
function balanceOf(address owner) external view returns (uint256);
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(address src, address dst, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function decimals() external returns (uint8);
}
// receives tokens and shares them among holders
contract CropJoin {
VatLike public immutable vat; // cdp engine
bytes32 public immutable ilk; // collateral type
ERC20 public immutable gem; // collateral token
uint256 public immutable dec; // gem decimals
ERC20 public immutable bonus; // rewards token
uint256 public share; // crops per gem [ray]
uint256 public total; // total gems [wad]
uint256 public stock; // crop balance [wad]
mapping (address => uint256) public crops; // crops per user [wad]
mapping (address => uint256) public stake; // gems per user [wad]
uint256 immutable internal to18ConversionFactor;
uint256 immutable internal toGemConversionFactor;
// --- Events ---
event Join(uint256 val);
event Exit(uint256 val);
event Flee();
event Tack(address indexed src, address indexed dst, uint256 wad);
constructor(address vat_, bytes32 ilk_, address gem_, address bonus_) public {
vat = VatLike(vat_);
ilk = ilk_;
gem = ERC20(gem_);
uint256 dec_ = ERC20(gem_).decimals();
require(dec_ <= 18);
dec = dec_;
to18ConversionFactor = 10 ** (18 - dec_);
toGemConversionFactor = 10 ** dec_;
bonus = ERC20(bonus_);
}
function add(uint256 x, uint256 y) public pure returns (uint256 z) {
require((z = x + y) >= x, "ds-math-add-overflow");
}
function sub(uint256 x, uint256 y) public pure returns (uint256 z) {
require((z = x - y) <= x, "ds-math-sub-underflow");
}
function mul(uint256 x, uint256 y) public pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow");
}
function divup(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(x, sub(y, 1)) / y;
}
uint256 constant WAD = 10 ** 18;
function wmul(uint256 x, uint256 y) public pure returns (uint256 z) {
z = mul(x, y) / WAD;
}
function wdiv(uint256 x, uint256 y) public pure returns (uint256 z) {
z = mul(x, WAD) / y;
}
function wdivup(uint256 x, uint256 y) public pure returns (uint256 z) {
z = divup(mul(x, WAD), y);
}
uint256 constant RAY = 10 ** 27;
function rmul(uint256 x, uint256 y) public pure returns (uint256 z) {
z = mul(x, y) / RAY;
}
function rmulup(uint256 x, uint256 y) public pure returns (uint256 z) {
z = divup(mul(x, y), RAY);
}
function rdiv(uint256 x, uint256 y) public pure returns (uint256 z) {
z = mul(x, RAY) / y;
}
// Net Asset Valuation [wad]
function nav() public virtual returns (uint256) {
uint256 _nav = gem.balanceOf(address(this));
return mul(_nav, to18ConversionFactor);
}
// Net Assets per Share [wad]
function nps() public returns (uint256) {
if (total == 0) return WAD;
else return wdiv(nav(), total);
}
function crop() internal virtual returns (uint256) {
return sub(bonus.balanceOf(address(this)), stock);
}
function harvest(address from, address to) internal {
if (total > 0) share = add(share, rdiv(crop(), total));
uint256 last = crops[from];
uint256 curr = rmul(stake[from], share);
if (curr > last) require(bonus.transfer(to, curr - last));
stock = bonus.balanceOf(address(this));
}
function join(address urn, uint256 val) internal virtual {
harvest(urn, urn);
if (val > 0) {
uint256 wad = wdiv(mul(val, to18ConversionFactor), nps());
// Overflow check for int256(wad) cast below
// Also enforces a non-zero wad
require(int256(wad) > 0);
require(gem.transferFrom(msg.sender, address(this), val));
vat.slip(ilk, urn, int256(wad));
total = add(total, wad);
stake[urn] = add(stake[urn], wad);
}
crops[urn] = rmulup(stake[urn], share);
emit Join(val);
}
function exit(address guy, uint256 val) internal virtual {
harvest(msg.sender, guy);
if (val > 0) {
uint256 wad = wdivup(mul(val, to18ConversionFactor), nps());
// Overflow check for int256(wad) cast below
// Also enforces a non-zero wad
require(int256(wad) > 0);
require(gem.transfer(guy, val));
vat.slip(ilk, msg.sender, -int256(wad));
total = sub(total, wad);
stake[msg.sender] = sub(stake[msg.sender], wad);
}
crops[msg.sender] = rmulup(stake[msg.sender], share);
emit Exit(val);
}
}
// File contracts/B.Protocol/CropJoinAdapter.sol
// MIT
pragma solidity 0.6.11;
// NOTE! - this is not an ERC20 token. transfer is not supported.
contract CropJoinAdapter is CropJoin {
string constant public name = "B.AMM LUSD-ETH";
string constant public symbol = "LUSDETH";
uint constant public decimals = 18;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
constructor(address _lqty) public
CropJoin(address(new Dummy()), "B.AMM", address(new DummyGem()), _lqty)
{
}
// adapter to cropjoin
function nav() public override returns (uint256) {
return total;
}
function totalSupply() public view returns (uint256) {
return total;
}
function balanceOf(address owner) public view returns (uint256 balance) {
balance = stake[owner];
}
function mint(address to, uint value) virtual internal {
join(to, value);
emit Transfer(address(0), to, value);
}
function burn(address owner, uint value) virtual internal {
exit(owner, value);
emit Transfer(owner, address(0), value);
}
}
contract Dummy {
fallback() external {}
}
contract DummyGem is Dummy {
function transfer(address, uint) external pure returns(bool) {
return true;
}
function transferFrom(address, address, uint) external pure returns(bool) {
return true;
}
function decimals() external pure returns(uint) {
return 18;
}
}
// File contracts/B.Protocol/PriceFormula.sol
// MIT
pragma solidity 0.6.11;
contract PriceFormula {
using SafeMath for uint256;
function getSumFixedPoint(uint x, uint y, uint A) public pure returns(uint) {
if(x == 0 && y == 0) return 0;
uint sum = x.add(y);
for(uint i = 0 ; i < 255 ; i++) {
uint dP = sum;
dP = dP.mul(sum) / (x.mul(2)).add(1);
dP = dP.mul(sum) / (y.mul(2)).add(1);
uint prevSum = sum;
uint n = (A.mul(2).mul(x.add(y)).add(dP.mul(2))).mul(sum);
uint d = (A.mul(2).sub(1).mul(sum));
sum = n / d.add(dP.mul(3));
if(sum <= prevSum.add(1) && prevSum <= sum.add(1)) break;
}
return sum;
}
function getReturn(uint xQty, uint xBalance, uint yBalance, uint A) public pure returns(uint) {
uint sum = getSumFixedPoint(xBalance, yBalance, A);
uint c = sum.mul(sum) / (xQty.add(xBalance)).mul(2);
c = c.mul(sum) / A.mul(4);
uint b = (xQty.add(xBalance)).add(sum / A.mul(2));
uint yPrev = 0;
uint y = sum;
for(uint i = 0 ; i < 255 ; i++) {
yPrev = y;
uint n = (y.mul(y)).add(c);
uint d = y.mul(2).add(b).sub(sum);
y = n / d;
if(y <= yPrev.add(1) && yPrev <= y.add(1)) break;
}
return yBalance.sub(y).sub(1);
}
}
// File contracts/Dependencies/AggregatorV3Interface.sol
// MIT
// Code from https://github.com/smartcontractkit/chainlink/blob/master/evm-contracts/src/v0.6/interfaces/AggregatorV3Interface.sol
pragma solidity 0.6.11;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// File contracts/B.Protocol/BAMM.sol
// MIT
pragma solidity 0.6.11;
contract BAMM is CropJoinAdapter, PriceFormula, Ownable {
using SafeMath for uint256;
AggregatorV3Interface public immutable priceAggregator;
AggregatorV3Interface public immutable lusd2UsdPriceAggregator;
IERC20 public immutable LUSD;
StabilityPool immutable public SP;
address payable public immutable feePool;
uint public constant MAX_FEE = 100; // 1%
uint public fee = 0; // fee in bps
uint public A = 20;
uint public constant MIN_A = 20;
uint public constant MAX_A = 200;
uint public immutable maxDiscount; // max discount in bips
address public immutable frontEndTag;
uint constant public PRECISION = 1e18;
event ParamsSet(uint A, uint fee);
event UserDeposit(address indexed user, uint lusdAmount, uint numShares);
event UserWithdraw(address indexed user, uint lusdAmount, uint ethAmount, uint numShares);
event RebalanceSwap(address indexed user, uint lusdAmount, uint ethAmount, uint timestamp);
constructor(
address _priceAggregator,
address _lusd2UsdPriceAggregator,
address payable _SP,
address _LUSD,
address _LQTY,
uint _maxDiscount,
address payable _feePool,
address _fronEndTag)
public
CropJoinAdapter(_LQTY)
{
priceAggregator = AggregatorV3Interface(_priceAggregator);
lusd2UsdPriceAggregator = AggregatorV3Interface(_lusd2UsdPriceAggregator);
LUSD = IERC20(_LUSD);
SP = StabilityPool(_SP);
feePool = _feePool;
maxDiscount = _maxDiscount;
frontEndTag = _fronEndTag;
}
function setParams(uint _A, uint _fee) external onlyOwner {
require(_fee <= MAX_FEE, "setParams: fee is too big");
require(_A >= MIN_A, "setParams: A too small");
require(_A <= MAX_A, "setParams: A too big");
fee = _fee;
A = _A;
emit ParamsSet(_A, _fee);
}
function fetchPrice() public view returns(uint) {
uint chainlinkDecimals;
uint chainlinkLatestAnswer;
uint chainlinkTimestamp;
// First, try to get current decimal precision:
try priceAggregator.decimals() returns (uint8 decimals) {
// If call to Chainlink succeeds, record the current decimal precision
chainlinkDecimals = decimals;
} catch {
// If call to Chainlink aggregator reverts, return a zero response with success = false
return 0;
}
// Secondly, try to get latest price data:
try priceAggregator.latestRoundData() returns
(
uint80 /* roundId */,
int256 answer,
uint256 /* startedAt */,
uint256 timestamp,
uint80 /* answeredInRound */
)
{
// If call to Chainlink succeeds, return the response and success = true
chainlinkLatestAnswer = uint(answer);
chainlinkTimestamp = timestamp;
} catch {
// If call to Chainlink aggregator reverts, return a zero response with success = false
return 0;
}
if(chainlinkTimestamp + 1 hours < now) return 0; // price is down
uint chainlinkFactor = 10 ** chainlinkDecimals;
return chainlinkLatestAnswer.mul(PRECISION) / chainlinkFactor;
}
function deposit(uint lusdAmount) external {
// update share
uint lusdValue = SP.getCompoundedLUSDDeposit(address(this));
uint ethValue = SP.getDepositorETHGain(address(this)).add(address(this).balance);
uint price = fetchPrice();
require(ethValue == 0 || price > 0, "deposit: chainlink is down");
uint totalValue = lusdValue.add(ethValue.mul(price) / PRECISION);
// this is in theory not reachable. if it is, better halt deposits
// the condition is equivalent to: (totalValue = 0) ==> (total = 0)
require(totalValue > 0 || total == 0, "deposit: system is rekt");
uint newShare = PRECISION;
if(total > 0) newShare = total.mul(lusdAmount) / totalValue;
// deposit
require(LUSD.transferFrom(msg.sender, address(this), lusdAmount), "deposit: transferFrom failed");
SP.provideToSP(lusdAmount, frontEndTag);
// update LP token
mint(msg.sender, newShare);
emit UserDeposit(msg.sender, lusdAmount, newShare);
}
function withdraw(uint numShares) external {
uint lusdValue = SP.getCompoundedLUSDDeposit(address(this));
uint ethValue = SP.getDepositorETHGain(address(this)).add(address(this).balance);
uint lusdAmount = lusdValue.mul(numShares).div(total);
uint ethAmount = ethValue.mul(numShares).div(total);
// this withdraws lusd, lqty, and eth
SP.withdrawFromSP(lusdAmount);
// update LP token
burn(msg.sender, numShares);
// send lusd and eth
if(lusdAmount > 0) LUSD.transfer(msg.sender, lusdAmount);
if(ethAmount > 0) {
(bool success, ) = msg.sender.call{ value: ethAmount }(""); // re-entry is fine here
require(success, "withdraw: sending ETH failed");
}
emit UserWithdraw(msg.sender, lusdAmount, ethAmount, numShares);
}
function addBps(uint n, int bps) internal pure returns(uint) {
require(bps <= 10000, "reduceBps: bps exceeds max");
require(bps >= -10000, "reduceBps: bps exceeds min");
return n.mul(uint(10000 + bps)) / 10000;
}
function compensateForLusdDeviation(uint ethAmount) public view returns(uint newEthAmount) {
uint chainlinkDecimals;
uint chainlinkLatestAnswer;
// get current decimal precision:
chainlinkDecimals = lusd2UsdPriceAggregator.decimals();
// Secondly, try to get latest price data:
(,int256 answer,,,) = lusd2UsdPriceAggregator.latestRoundData();
chainlinkLatestAnswer = uint(answer);
// adjust only if 1 LUSD > 1 USDC. If LUSD < USD, then we give a discount, and rebalance will happen anw
if(chainlinkLatestAnswer > 10 ** chainlinkDecimals ) {
newEthAmount = ethAmount.mul(chainlinkLatestAnswer) / (10 ** chainlinkDecimals);
}
else newEthAmount = ethAmount;
}
function getSwapEthAmount(uint lusdQty) public view returns(uint ethAmount, uint feeLusdAmount) {
uint lusdBalance = SP.getCompoundedLUSDDeposit(address(this));
uint ethBalance = SP.getDepositorETHGain(address(this)).add(address(this).balance);
uint eth2usdPrice = fetchPrice();
if(eth2usdPrice == 0) return (0, 0); // chainlink is down
uint ethUsdValue = ethBalance.mul(eth2usdPrice) / PRECISION;
uint maxReturn = addBps(lusdQty.mul(PRECISION) / eth2usdPrice, int(maxDiscount));
uint xQty = lusdQty;
uint xBalance = lusdBalance;
uint yBalance = lusdBalance.add(ethUsdValue.mul(2));
uint usdReturn = getReturn(xQty, xBalance, yBalance, A);
uint basicEthReturn = usdReturn.mul(PRECISION) / eth2usdPrice;
basicEthReturn = compensateForLusdDeviation(basicEthReturn);
if(ethBalance < basicEthReturn) basicEthReturn = ethBalance; // cannot give more than balance
if(maxReturn < basicEthReturn) basicEthReturn = maxReturn;
ethAmount = basicEthReturn;
feeLusdAmount = addBps(lusdQty, int(fee)).sub(lusdQty);
}
// get ETH in return to LUSD
function swap(uint lusdAmount, uint minEthReturn, address payable dest) public returns(uint) {
(uint ethAmount, uint feeAmount) = getSwapEthAmount(lusdAmount);
require(ethAmount >= minEthReturn, "swap: low return");
LUSD.transferFrom(msg.sender, address(this), lusdAmount);
SP.provideToSP(lusdAmount.sub(feeAmount), frontEndTag);
if(feeAmount > 0) LUSD.transfer(feePool, feeAmount);
(bool success, ) = dest.call{ value: ethAmount }(""); // re-entry is fine here
require(success, "swap: sending ETH failed");
emit RebalanceSwap(msg.sender, lusdAmount, ethAmount, now);
return ethAmount;
}
// kyber network reserve compatible function
function trade(
IERC20 /* srcToken */,
uint256 srcAmount,
IERC20 /* destToken */,
address payable destAddress,
uint256 /* conversionRate */,
bool /* validate */
) external payable returns (bool) {
return swap(srcAmount, 0, destAddress) > 0;
}
function getConversionRate(
IERC20 /* src */,
IERC20 /* dest */,
uint256 srcQty,
uint256 /* blockNumber */
) external view returns (uint256) {
(uint ethQty, ) = getSwapEthAmount(srcQty);
return ethQty.mul(PRECISION) / srcQty;
}
receive() external payable {}
}
// File @openzeppelin/contracts/utils/[email protected]
// MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File contracts/B.Protocol/KeeperRebate.sol
// MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface FeePoolVaultLike {
function op(address target, bytes calldata data, uint value) external;
function transferOwnership(address newOwner) external;
}
contract KeeperRebate is Ownable {
using EnumerableSet for EnumerableSet.AddressSet;
address immutable public feePool;
BAMM immutable public bamm;
IERC20 immutable public lusd;
IERC20 constant public ETH = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
EnumerableSet.AddressSet keepers;
address public keeperLister;
struct TokensData {
IERC20 inToken;
IERC20[] outTokens;
IERC20[] rebateTokens;
}
event SwapSummary(address indexed keeper, IERC20 tokenIn, uint inAmount, IERC20 tokenOut, uint outAmount, uint rebateAmount);
event NewLister(address lister);
event KeeperListing(address keeper, bool list);
constructor(BAMM _bamm) public {
bamm = _bamm;
lusd = _bamm.LUSD();
feePool = _bamm.feePool();
IERC20(_bamm.LUSD()).approve(address(_bamm), uint(-1));
}
function getReturnedSwapAmount(IERC20 tokenIn, uint inAmount, IERC20 tokenOut)
public
view
returns(uint outAmount, IERC20 rebateToken, uint rebateAmount) {
if(tokenIn == lusd && tokenOut == ETH) {
(outAmount, rebateAmount) = bamm.getSwapEthAmount(inAmount);
}
rebateToken = lusd;
}
function swap(IERC20 tokenIn, uint inAmount, IERC20 tokenOut, uint minOutAmount, uint maxRebate, address payable dest)
public
payable
returns(uint outAmount, uint rebateAmount)
{
require(tokenIn == lusd, "swap: invalid tokenIn");
require(tokenOut == ETH, "swap: invalid tokenOut");
(outAmount, rebateAmount) = swapWithRebate(inAmount, minOutAmount, maxRebate, dest);
emit SwapSummary(msg.sender, tokenIn, inAmount, tokenOut, outAmount, rebateAmount);
}
function getTokens() public view returns(TokensData[] memory tokens) {
tokens = new TokensData[](1);
tokens[0].inToken = lusd;
tokens[0].outTokens = new IERC20[](1);
tokens[0].rebateTokens = new IERC20[](1);
tokens[0].outTokens[0] = ETH;
tokens[0].rebateTokens[0] = lusd;
}
function transferFeePoolOwnership(address newOwner) public onlyOwner {
FeePoolVaultLike(feePool).transferOwnership(newOwner);
}
function setKeeperLister(address lister) public onlyOwner {
keeperLister = lister;
emit NewLister(lister);
}
function listKeeper(address keeper, bool list) public {
require(msg.sender == keeperLister, "listKeeper: !lister");
if(list) require(keepers.add(keeper), "listKeeper: keepers.add failed");
else require(keepers.remove(keeper), "listKeeper: keepers.remove failed");
KeeperListing(keeper, list);
}
function swapWithRebate(uint lusdAmount, uint minEthReturn, uint maxLusdRebate, address payable dest)
internal
returns(uint ethAmount, uint lusdRebate)
{
require(keepers.contains(msg.sender), "swapWithRebate: !keeper");
lusd.transferFrom(msg.sender, address(this), lusdAmount);
uint feeBps = bamm.fee();
// if lusd amount is 0 it will revert, but this is fine
require(feeBps * lusdAmount / lusdAmount == feeBps, "swapWithRebate: overflow");
lusdRebate = feeBps * lusdAmount / 10000;
// adjust rebate to max fee
if(lusdRebate > maxLusdRebate) lusdRebate = maxLusdRebate;
ethAmount = bamm.swap(lusdAmount, minEthReturn, dest);
rebate(dest, lusdRebate);
}
function rebate(address payable dest, uint amount) internal {
bytes memory data = abi.encodeWithSignature("transfer(address,uint256)", dest, amount);
FeePoolVaultLike(feePool).op(address(lusd), data, 0);
}
} | kyber network reserve compatible function | function trade(
IERC20 /* srcToken */,
uint256 srcAmount,
IERC20 /* destToken */,
address payable destAddress,
uint256 /* conversionRate */,
bool /* validate */
) external payable returns (bool) {
return swap(srcAmount, 0, destAddress) > 0;
}
| 504,068 | [
1,
18465,
744,
2483,
20501,
7318,
445,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
18542,
12,
203,
3639,
467,
654,
39,
3462,
1748,
1705,
1345,
1195,
16,
203,
3639,
2254,
5034,
1705,
6275,
16,
203,
3639,
467,
654,
39,
3462,
1748,
1570,
1345,
1195,
16,
203,
3639,
1758,
8843,
429,
1570,
1887,
16,
203,
3639,
2254,
5034,
1748,
4105,
4727,
1195,
16,
203,
3639,
1426,
1748,
1954,
1195,
203,
565,
262,
3903,
8843,
429,
1135,
261,
6430,
13,
288,
203,
3639,
327,
7720,
12,
4816,
6275,
16,
374,
16,
1570,
1887,
13,
405,
374,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0xB6Fc6E2385d55CCb83e297Bd92E2Bd89795B47A3/sources/PonyCore.sol | @dev PonyId의 소유권 이전을 승인하는 Internal Method@param _tokenId 포니의 아이디@Param _approved 이전할 소유자의 주소 | function _approve(uint256 _tokenId, address _approved)
internal
{
ponyIndexToApproved[_tokenId] = _approved;
}
| 4,123,327 | [
1,
52,
6598,
548,
173,
256,
251,
225,
173,
233,
239,
173,
255,
259,
171,
119,
239,
225,
173,
256,
117,
173,
259,
231,
173,
256,
231,
225,
173,
237,
122,
173,
256,
121,
174,
248,
251,
172,
237,
247,
3186,
2985,
389,
2316,
548,
225,
174,
242,
110,
172,
238,
235,
173,
256,
251,
225,
173,
248,
231,
173,
256,
117,
172,
247,
247,
36,
786,
389,
25990,
225,
173,
256,
117,
173,
259,
231,
174,
248,
259,
225,
173,
233,
239,
173,
255,
259,
173,
257,
243,
173,
256,
251,
225,
173,
101,
125,
173,
233,
239,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
12908,
537,
12,
11890,
5034,
389,
2316,
548,
16,
1758,
389,
25990,
13,
203,
565,
2713,
203,
565,
288,
203,
3639,
293,
6598,
1016,
774,
31639,
63,
67,
2316,
548,
65,
273,
389,
25990,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x2B81d60dc40f6Ca230be5Abf5641D4c2E38dba01/sources/src/vaults/VaultGovernance.sol | @notice Set Delayed Strategy Params @param nft Nft of the vault @param params New params | function _stageDelayedStrategyParams(uint256 nft, bytes memory params) internal {
_requireAtLeastStrategy(nft);
_stagedDelayedStrategyParams[nft] = params;
uint256 delayFactor = _delayedStrategyParams[nft].length == 0 ? 0 : 1;
_delayedStrategyParamsTimestamp[nft] =
block.timestamp +
_internalParams.protocolGovernance.governanceDelay() *
delayFactor;
}
| 8,327,315 | [
1,
694,
20165,
329,
19736,
8861,
225,
290,
1222,
423,
1222,
434,
326,
9229,
225,
859,
1166,
859,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
12869,
29527,
4525,
1370,
12,
11890,
5034,
290,
1222,
16,
1731,
3778,
859,
13,
2713,
288,
203,
3639,
389,
6528,
25070,
4525,
12,
82,
1222,
1769,
203,
3639,
389,
334,
11349,
29527,
4525,
1370,
63,
82,
1222,
65,
273,
859,
31,
203,
3639,
2254,
5034,
4624,
6837,
273,
389,
10790,
329,
4525,
1370,
63,
82,
1222,
8009,
2469,
422,
374,
692,
374,
294,
404,
31,
203,
3639,
389,
10790,
329,
4525,
1370,
4921,
63,
82,
1222,
65,
273,
203,
5411,
1203,
18,
5508,
397,
203,
5411,
389,
7236,
1370,
18,
8373,
43,
1643,
82,
1359,
18,
75,
1643,
82,
1359,
6763,
1435,
380,
203,
5411,
4624,
6837,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.11;
import "@openzeppelin/contracts/access/Ownable.sol";
contract Snapper is Ownable {
/**
* @dev `lastSnapshotBlock_` must be equal to `_latestSnapshotBlock` in `takeSnapshot` method
*/
error InvalidLastSnapshotBlock(uint256 last, uint256 latest);
/**
* @dev `snapshotBlock_` must be greater than `_latestSnapshotBlock` in `takeSnapshot` method
*/
error InvalidSnapshotBlock(uint256 target, uint256 latest);
/**
* @notice snapshot info
* @param block the block number snapshotted for The Space.
* @param cid IPFS CID of the snapshot file.
*/
event Snapshot(uint256 indexed block, string cid);
/**
* @notice delta info
* @param block delta end at this block number, inclusive
* @param cid IPFS CID of the delta file.
*/
event Delta(uint256 indexed block, string cid);
/**
* @dev store latest snapshot info.
*/
uint256 private _latestSnapshotBlock;
string private _latestSnapshotCid;
/**
* @notice create Snapper contract with initial snapshot.
* @dev Emits {Snapshot} event.
* @param theSpaceCreationBlock_ the Contract Creation block number of The Space contract.
* @param snapshotCid_ the initial pixels picture IPFS CID of The Space.
*/
constructor(uint256 theSpaceCreationBlock_, string memory snapshotCid_) {
_latestSnapshotBlock = theSpaceCreationBlock_;
_latestSnapshotCid = snapshotCid_;
emit Snapshot(_latestSnapshotBlock, snapshotCid_);
}
/**
* @dev Emits {Snapshot} and {Delta} events.
* @param lastSnapshotBlock_ last block number snapshotted for The Space. use to validate precondition.
* @param snapshotBlock_ the block number snapshotted for The Space this time.
*/
function takeSnapshot(
uint256 lastSnapshotBlock_,
uint256 snapshotBlock_,
string calldata snapshotCid_,
string calldata deltaCid_
) external onlyOwner {
if (lastSnapshotBlock_ != _latestSnapshotBlock)
revert InvalidLastSnapshotBlock(lastSnapshotBlock_, _latestSnapshotBlock);
if (snapshotBlock_ <= _latestSnapshotBlock) revert InvalidSnapshotBlock(snapshotBlock_, _latestSnapshotBlock);
_latestSnapshotBlock = snapshotBlock_;
_latestSnapshotCid = snapshotCid_;
emit Snapshot(snapshotBlock_, snapshotCid_);
emit Delta(snapshotBlock_, deltaCid_);
}
/**
* @dev get the lastest snapshot info.
*/
function latestSnapshotInfo() external view returns (uint256 latestSnapshotBlock, string memory latestSnapshotCid) {
return (_latestSnapshotBlock, _latestSnapshotCid);
}
}
| * @dev `lastSnapshotBlock_` must be equal to `_latestSnapshotBlock` in `takeSnapshot` method/* @dev `snapshotBlock_` must be greater than `_latestSnapshotBlock` in `takeSnapshot` method/* @notice snapshot info @param block the block number snapshotted for The Space. @param cid IPFS CID of the snapshot file./* @notice delta info @param block delta end at this block number, inclusive @param cid IPFS CID of the delta file./* @dev store latest snapshot info./* @notice create Snapper contract with initial snapshot. @dev Emits {Snapshot} event. @param theSpaceCreationBlock_ the Contract Creation block number of The Space contract. @param snapshotCid_ the initial pixels picture IPFS CID of The Space./ | constructor(uint256 theSpaceCreationBlock_, string memory snapshotCid_) {
_latestSnapshotBlock = theSpaceCreationBlock_;
_latestSnapshotCid = snapshotCid_;
emit Snapshot(_latestSnapshotBlock, snapshotCid_);
}
| 12,877,588 | [
1,
68,
2722,
4568,
1768,
67,
68,
1297,
506,
3959,
358,
1375,
67,
13550,
4568,
1768,
68,
316,
1375,
22188,
4568,
68,
707,
19,
225,
1375,
11171,
1768,
67,
68,
1297,
506,
6802,
2353,
1375,
67,
13550,
4568,
1768,
68,
316,
1375,
22188,
4568,
68,
707,
19,
225,
4439,
1123,
225,
1203,
326,
1203,
1300,
4439,
2344,
364,
1021,
14059,
18,
225,
7504,
2971,
4931,
385,
734,
434,
326,
4439,
585,
18,
19,
225,
3622,
1123,
225,
1203,
3622,
679,
622,
333,
1203,
1300,
16,
13562,
225,
7504,
2971,
4931,
385,
734,
434,
326,
3622,
585,
18,
19,
225,
1707,
4891,
4439,
1123,
18,
19,
225,
752,
348,
2322,
457,
6835,
598,
2172,
4439,
18,
225,
7377,
1282,
288,
4568,
97,
871,
18,
225,
326,
3819,
9906,
1768,
67,
326,
13456,
18199,
1203,
1300,
434,
1021,
14059,
6835,
18,
225,
4439,
19844,
67,
326,
2172,
8948,
15406,
2971,
4931,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
565,
3885,
12,
11890,
5034,
326,
3819,
9906,
1768,
67,
16,
533,
3778,
4439,
19844,
67,
13,
288,
203,
3639,
389,
13550,
4568,
1768,
273,
326,
3819,
9906,
1768,
67,
31,
203,
3639,
389,
13550,
4568,
19844,
273,
4439,
19844,
67,
31,
203,
203,
3639,
3626,
10030,
24899,
13550,
4568,
1768,
16,
4439,
19844,
67,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//SPDX-License-Identifier: UNLICENSED
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
pragma solidity 0.6.12;
// ApplePieToken with Governance.
contract ApplePieToken is ERC20, Ownable {
uint256 private _cap=0;
constructor( string memory name,string memory symbol) public ERC20(name, symbol) {
}
function mint(address _to, uint256 _amount) public onlyOwner {
require(_cap ==0 || totalSupply().add(_amount) <= _cap, "cap exceeded");
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
function setCap(uint256 cap) public onlyOwner{
require(_cap ==0 && cap>0, "cap is already set"); // cap can be set only once, cannot be reset
_cap = cap;
}
function cap() public view returns (uint256) {
return _cap;
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
mapping (address => bool) public frozenAccount;
event FundsFrozen(address target, bool frozen);
event AccountFrozenError();
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "APPLE::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "APPLE::delegateBySig: invalid nonce");
require(now <= expiry, "APPLE::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "APPLE::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying APPLEs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "APPLE::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
// freeze accounts
function freeze(address target, bool f) public onlyOwner {
frozenAccount[target] = f;
emit FundsFrozen(target, f);
}
function isFrozen(address target) public view returns (bool) {
return frozenAccount[target];
}
/**
* @dev Transfer token for a specified address when not paused
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public override returns (bool) {
// source account should not be frozen if contract is in not open state
if (frozenAccount[msg.sender]) {
emit AccountFrozenError();
return false;
}
// transfer fund first if sender is not frozen
require(super.transfer(_to, _value), "Transfer failed.");
_moveDelegates(delegates[msg.sender], delegates[_to], _value);
return true;
}
/**
* @dev Transfer tokens from one address to another when not paused
* @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) {
// source account should not be frozen if contract is in not open state
if (frozenAccount[_from] ) {
emit AccountFrozenError();
return false;
}
// transfer funds
require(super.transferFrom(_from, _to, _value), "Transfer failed.");
_moveDelegates(delegates[_from], delegates[_to], _value);
return true;
}
} | * @dev Transfer tokens from one address to another when not paused @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/ source account should not be frozen if contract is in not open state | function transferFrom(address _from, address _to, uint256 _value) public override returns (bool) {
if (frozenAccount[_from] ) {
emit AccountFrozenError();
return false;
}
_moveDelegates(delegates[_from], delegates[_to], _value);
return true;
}
| 5,427,871 | [
1,
5912,
2430,
628,
1245,
1758,
358,
4042,
1347,
486,
17781,
225,
389,
2080,
1758,
1021,
1758,
1492,
1846,
2545,
358,
1366,
2430,
628,
225,
389,
869,
1758,
1021,
1758,
1492,
1846,
2545,
358,
7412,
358,
225,
389,
1132,
2254,
5034,
326,
3844,
434,
2430,
358,
506,
906,
4193,
19,
1084,
2236,
1410,
486,
506,
12810,
309,
6835,
353,
316,
486,
1696,
919,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7412,
1265,
12,
2867,
389,
2080,
16,
1758,
389,
869,
16,
2254,
5034,
389,
1132,
13,
1071,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
309,
261,
28138,
3032,
63,
67,
2080,
65,
262,
288,
203,
5411,
3626,
6590,
42,
9808,
668,
5621,
203,
5411,
327,
629,
31,
203,
3639,
289,
203,
203,
3639,
389,
8501,
15608,
815,
12,
3771,
1332,
815,
63,
67,
2080,
6487,
22310,
63,
67,
869,
6487,
389,
1132,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// 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: UNLICENSED
/*
* @title Solidity Bytes Arrays Utils
* @author Gonçalo Sá <[email protected]>
*
* @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity.
* The library lets you concatenate, slice and type cast bytes arrays both in memory and storage.
*/
pragma solidity 0.8.11;
library BytesLib {
function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) {
require(_bytes.length >= _start + 20, 'toAddress_outOfBounds');
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) {
require(_bytes.length >= _start + 3, 'toUint24_outOfBounds');
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) {
require(_bytes.length >= _start + 1 , "toUint8_outOfBounds");
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "../../../external/@openzeppelin/token/ERC20/IERC20.sol";
interface IHarvestPool {
function rewardToken() external view returns (address);
function lpToken() external view returns (address);
function duration() external view returns (uint256);
function periodFinish() external view returns (uint256);
function rewardRate() external view returns (uint256);
function rewardPerTokenStored() external view returns (uint256);
function stake(uint256 amountWei) external;
// `balanceOf` would give the amount staked.
// As this is 1 to 1, this is also the holder's share
function balanceOf(address holder) external view returns (uint256);
// total shares & total lpTokens staked
function totalSupply() external view returns (uint256);
function withdraw(uint256 amountWei) external;
function exit() external;
// get claimed rewards
function earned(address holder) external view returns (uint256);
// claim rewards
function getReward() external;
// notify
function notifyRewardAmount(uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface IHarvestVault {
function underlyingBalanceInVault() external view returns (uint256);
function underlyingBalanceWithInvestment() external view returns (uint256);
// function store() external view returns (address);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function strategy() external view returns (address);
function setStrategy(address _strategy) external;
function setVaultFractionToInvest(uint256 numerator, uint256 denominator) external;
function deposit(uint256 amountWei) external;
function depositFor(uint256 amountWei, address holder) external;
function withdrawAll() external;
function withdraw(uint256 numberOfShares) external;
function getPricePerFullShare() external view returns (uint256);
function underlyingBalanceWithInvestmentForHolder(address holder) external view returns (uint256);
// hard work should be callable only by the controller (by the hard worker) or by governance
function doHardWork() external;
function totalSupply() external view returns (uint256);
function balanceOf(address user) external view returns (uint256);
function approve(address user, uint256 amount) external returns (bool);
function underlyingUnit() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
import './IV2SwapRouter.sol';
import './IV3SwapRouter.sol';
/// @title Router token swapping functionality
interface ISwapRouter02 is IV2SwapRouter, IV3SwapRouter {
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V2
interface IV2SwapRouter {
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
/// and swap the entire amount, enabling contracts to send tokens before calling this function.
/// @param amountIn The amount of token to swap
/// @param amountOutMin The minimum amount of output that must be received
/// @param path The ordered list of tokens to swap through
/// @param to The recipient address
/// @return amountOut The amount of the received token
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to
) external payable returns (uint256 amountOut);
/// @notice Swaps as little as possible of one token for an exact amount of another token
/// @param amountOut The amount of token to swap for
/// @param amountInMax The maximum amount of input that the caller will pay
/// @param path The ordered list of tokens to swap through
/// @param to The recipient address
/// @return amountIn The amount of token to pay
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to
) external payable returns (uint256 amountIn);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface IV3SwapRouter{
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
/// and swap the entire amount, enabling contracts to send tokens before calling this function.
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
/// and swap the entire amount, enabling contracts to send tokens before calling this function.
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// that may remain in the router after the swap.
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// that may remain in the router after the swap.
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
// 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;
/**
* @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: 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 "../external/GNSPS-solidity-bytes-utils/BytesLib.sol";
import "../external/@openzeppelin/token/ERC20/utils/SafeERC20.sol";
import "../external/uniswap/interfaces/ISwapRouter02.sol";
import "../interfaces/ISwapData.sol";
/// @notice Denotes swap action mode
enum SwapAction {
NONE,
UNI_V2_DIRECT,
UNI_V2_WETH,
UNI_V2,
UNI_V3_DIRECT,
UNI_V3_WETH,
UNI_V3
}
/// @title Contains logic facilitating swapping using Uniswap
abstract contract SwapHelper {
using BytesLib for bytes;
using SafeERC20 for IERC20;
/// @dev The length of the bytes encoded swap action
uint256 private constant ACTION_SIZE = 1;
/// @dev The length of the bytes encoded address
uint256 private constant ADDR_SIZE = 20;
/// @dev The length of the bytes encoded fee
uint256 private constant FEE_SIZE = 3;
/// @dev The offset of a single token address and pool fee
uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE;
/// @dev Maximum V2 path length (4 swaps)
uint256 private constant MAX_V2_PATH = ADDR_SIZE * 3;
/// @dev V3 WETH path length
uint256 private constant WETH_V3_PATH_SIZE = FEE_SIZE + FEE_SIZE;
/// @dev Minimum V3 custom path length (2 swaps)
uint256 private constant MIN_V3_PATH = FEE_SIZE + NEXT_OFFSET;
/// @dev Maximum V3 path length (4 swaps)
uint256 private constant MAX_V3_PATH = FEE_SIZE + NEXT_OFFSET * 3;
/// @notice Uniswap router supporting Uniswap V2 and V3
ISwapRouter02 internal immutable uniswapRouter;
/// @notice Address of WETH token
address private immutable WETH;
/**
* @notice Sets initial values
* @param _uniswapRouter Uniswap router address
* @param _WETH WETH token address
*/
constructor(ISwapRouter02 _uniswapRouter, address _WETH) {
uniswapRouter = _uniswapRouter;
WETH = _WETH;
}
/**
* @notice Approve reward token and swap the `amount` to a strategy underlying asset
* @param from Token to swap from
* @param to Token to swap to
* @param amount Amount of tokens to swap
* @param swapData Swap details showing the path of the swap
* @return result Amount of underlying (`to`) tokens recieved
*/
function _approveAndSwap(
IERC20 from,
IERC20 to,
uint256 amount,
SwapData calldata swapData
) internal virtual returns (uint256) {
// if there is nothing to swap, return
if(amount == 0)
return 0;
// if amount is not uint256 max approve unswap router to spend tokens
// otherwise rewards were already sent to the router
if(amount < type(uint256).max) {
from.safeApprove(address(uniswapRouter), amount);
} else {
amount = 0;
}
// get swap action from first byte
SwapAction action = SwapAction(swapData.path.toUint8(0));
uint256 result;
if (action == SwapAction.UNI_V2_DIRECT) { // V2 Direct
address[] memory path = new address[](2);
result = _swapV2(from, to, amount, swapData.slippage, path);
} else if (action == SwapAction.UNI_V2_WETH) { // V2 WETH
address[] memory path = new address[](3);
path[1] = WETH;
result = _swapV2(from, to, amount, swapData.slippage, path);
} else if (action == SwapAction.UNI_V2) { // V2 Custom
address[] memory path = _getV2Path(swapData.path);
result = _swapV2(from, to, amount, swapData.slippage, path);
} else if (action == SwapAction.UNI_V3_DIRECT) { // V3 Direct
result = _swapDirectV3(from, to, amount, swapData.slippage, swapData.path);
} else if (action == SwapAction.UNI_V3_WETH) { // V3 WETH
bytes memory wethPath = _getV3WethPath(swapData.path);
result = _swapV3(from, to, amount, swapData.slippage, wethPath);
} else if (action == SwapAction.UNI_V3) { // V3 Custom
require(swapData.path.length > MIN_V3_PATH, "SwapHelper::_approveAndSwap: Path too short");
uint256 actualpathSize = swapData.path.length - ACTION_SIZE;
require((actualpathSize - FEE_SIZE) % NEXT_OFFSET == 0 &&
actualpathSize <= MAX_V3_PATH,
"SwapHelper::_approveAndSwap: Bad V3 path");
result = _swapV3(from, to, amount, swapData.slippage, swapData.path[ACTION_SIZE:]);
} else {
revert("SwapHelper::_approveAndSwap: No action");
}
if (from.allowance(address(this), address(uniswapRouter)) > 0) {
from.safeApprove(address(uniswapRouter), 0);
}
return result;
}
/**
* @notice Swaps tokens using Uniswap V2
* @param from Token to swap from
* @param to Token to swap to
* @param amount Amount of tokens to swap
* @param slippage Allowed slippage
* @param path Steps to complete the swap
* @return result Amount of underlying (`to`) tokens recieved
*/
function _swapV2(
IERC20 from,
IERC20 to,
uint256 amount,
uint256 slippage,
address[] memory path
) internal virtual returns (uint256) {
path[0] = address(from);
path[path.length - 1] = address(to);
return uniswapRouter.swapExactTokensForTokens(
amount,
slippage,
path,
address(this)
);
}
/**
* @notice Swaps tokens using Uniswap V3
* @param from Token to swap from
* @param to Token to swap to
* @param amount Amount of tokens to swap
* @param slippage Allowed slippage
* @param path Steps to complete the swap
* @return result Amount of underlying (`to`) tokens recieved
*/
function _swapV3(
IERC20 from,
IERC20 to,
uint256 amount,
uint256 slippage,
bytes memory path
) internal virtual returns (uint256) {
IV3SwapRouter.ExactInputParams memory params =
IV3SwapRouter.ExactInputParams({
path: abi.encodePacked(address(from), path, address(to)),
recipient: address(this),
amountIn: amount,
amountOutMinimum: slippage
});
// Executes the swap.
uint received = uniswapRouter.exactInput(params);
return received;
}
/**
* @notice Does a direct swap from `from` address to the `to` address using Uniswap V3
* @param from Token to swap from
* @param to Token to swap to
* @param amount Amount of tokens to swap
* @param slippage Allowed slippage
* @param fee V3 direct fee configuration
* @return result Amount of underlying (`to`) tokens recieved
*/
function _swapDirectV3(
IERC20 from,
IERC20 to,
uint256 amount,
uint256 slippage,
bytes memory fee
) internal virtual returns (uint256) {
require(fee.length == FEE_SIZE + ACTION_SIZE, "SwapHelper::_swapDirectV3: Bad V3 direct fee");
IV3SwapRouter.ExactInputSingleParams memory params = IV3SwapRouter.ExactInputSingleParams(
address(from),
address(to),
// ignore first byte
fee.toUint24(ACTION_SIZE),
address(this),
amount,
slippage,
0
);
return uniswapRouter.exactInputSingle(params);
}
/**
* @notice Converts passed bytes to V2 path
* @param pathBytes Swap path in bytes, converted to addresses
* @return path list of addresses in the swap path (skipping first and last element)
*/
function _getV2Path(bytes calldata pathBytes) internal pure returns(address[] memory) {
require(pathBytes.length > ACTION_SIZE, "SwapHelper::_getV2Path: No path provided");
uint256 actualpathSize = pathBytes.length - ACTION_SIZE;
require(actualpathSize % ADDR_SIZE == 0 && actualpathSize <= MAX_V2_PATH, "SwapHelper::_getV2Path: Bad V2 path");
uint256 pathLength = actualpathSize / ADDR_SIZE;
address[] memory path = new address[](pathLength + 2);
// ignore first byte
path[1] = pathBytes.toAddress(ACTION_SIZE);
for (uint256 i = 1; i < pathLength; i++) {
path[i + 1] = pathBytes.toAddress(i * ADDR_SIZE + ACTION_SIZE);
}
return path;
}
/**
* @notice Get Unswap V3 path to swap tokens via WETH LP pool
* @param pathBytes Swap path in bytes
* @return wethPath Unswap V3 path routing via WETH pool
*/
function _getV3WethPath(bytes calldata pathBytes) internal view returns(bytes memory) {
require(pathBytes.length == WETH_V3_PATH_SIZE + ACTION_SIZE, "SwapHelper::_getV3WethPath: Bad V3 WETH path");
// ignore first byte as it's used for swap action
return abi.encodePacked(pathBytes[ACTION_SIZE:4], WETH, pathBytes[4:]);
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "./SwapHelper.sol";
/// @title Swap helper implementation with SwapRouter02 on Mainnet
contract SwapHelperMainnet is SwapHelper {
constructor()
SwapHelper(ISwapRouter02(0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45), 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2)
{}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "../interfaces/IBaseStrategy.sol";
import "../shared/BaseStorage.sol";
import "../shared/Constants.sol";
import "../external/@openzeppelin/token/ERC20/utils/SafeERC20.sol";
import "../libraries/Math.sol";
import "../libraries/Max/128Bit.sol";
/**
* @notice Implementation of the {IBaseStrategy} interface.
*
* @dev
* This implementation of the {IBaseStrategy} is meant to operate
* on single-collateral strategies and uses a delta system to calculate
* whether a withdrawal or deposit needs to be performed for a particular
* strategy.
*/
abstract contract BaseStrategy is IBaseStrategy, BaseStorage, BaseConstants {
using SafeERC20 for IERC20;
using Max128Bit for uint128;
/* ========== CONSTANTS ========== */
/// @notice minimum shares size to avoid loss of share due to computation precision
uint128 private constant MIN_SHARES = 10**8;
/* ========== STATE VARIABLES ========== */
/// @notice The total slippage slots the strategy supports, used for validation of provided slippage
uint256 internal immutable rewardSlippageSlots;
/// @notice Slots for processing
uint256 internal immutable processSlippageSlots;
/// @notice Slots for reallocation
uint256 internal immutable reallocationSlippageSlots;
/// @notice Slots for deposit
uint256 internal immutable depositSlippageSlots;
/**
* @notice do force claim of rewards.
*
* @dev
* Some strategies auto claim on deposit/withdraw,
* so execute the claim actions to store the reward amounts.
*/
bool internal immutable forceClaim;
/// @notice flag to force balance validation before running process strategy
/// @dev this is done so noone can manipulate the strategies before we interact with them and cause harm to the system
bool internal immutable doValidateBalance;
/// @notice The self address, set at initialization to allow proper share accounting
address internal immutable self;
/// @notice The underlying asset of the strategy
IERC20 public immutable override underlying;
/* ========== CONSTRUCTOR ========== */
/**
* @notice Initializes the base strategy values.
*
* @dev
* It performs certain pre-conditional validations to ensure the contract
* has been initialized properly, such as that the address argument of the
* underlying asset is valid.
*
* Slippage slots for certain strategies may be zero if there is no compounding
* work to be done.
*
* @param _underlying token used for deposits
* @param _rewardSlippageSlots slots for rewards
* @param _processSlippageSlots slots for processing
* @param _reallocationSlippageSlots slots for reallocation
* @param _depositSlippageSlots slots for deposits
* @param _forceClaim force claim of rewards
* @param _doValidateBalance force balance validation
*/
constructor(
IERC20 _underlying,
uint256 _rewardSlippageSlots,
uint256 _processSlippageSlots,
uint256 _reallocationSlippageSlots,
uint256 _depositSlippageSlots,
bool _forceClaim,
bool _doValidateBalance
) {
require(
_underlying != IERC20(address(0)),
"BaseStrategy::constructor: Underlying address cannot be 0"
);
self = address(this);
underlying = _underlying;
rewardSlippageSlots = _rewardSlippageSlots;
processSlippageSlots = _processSlippageSlots;
reallocationSlippageSlots = _reallocationSlippageSlots;
depositSlippageSlots = _depositSlippageSlots;
forceClaim = _forceClaim;
doValidateBalance = _doValidateBalance;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Process the latest pending action of the strategy
*
* @dev
* it yields amount of funds processed as well as the reward buffer of the strategy.
* The function will auto-compound rewards if requested and supported.
*
* Requirements:
*
* - the slippages provided must be valid in length
* - if the redeposit flag is set to true, the strategy must support
* compounding of rewards
*
* @param slippages slippages to process
* @param redeposit if redepositing is to occur
* @param swapData swap data for processing
*/
function process(uint256[] calldata slippages, bool redeposit, SwapData[] calldata swapData) external override
{
slippages = _validateStrategyBalance(slippages);
if (forceClaim || redeposit) {
_validateRewardsSlippage(swapData);
_processRewards(swapData);
}
if (processSlippageSlots != 0)
_validateProcessSlippage(slippages);
_process(slippages, 0);
}
/**
* @notice Process first part of the reallocation DHW
* @dev Withdraws for reallocation, depositn and withdraww for a user
*
* @param slippages Parameters to apply when performing a deposit or a withdraw
* @param processReallocationData Data containing amuont of optimized and not optimized shares to withdraw
* @return withdrawnReallocationReceived actual amount recieveed from peforming withdraw
*/
function processReallocation(uint256[] calldata slippages, ProcessReallocationData calldata processReallocationData) external override returns(uint128)
{
slippages = _validateStrategyBalance(slippages);
if (reallocationSlippageSlots != 0)
_validateReallocationSlippage(slippages);
_process(slippages, processReallocationData.sharesToWithdraw);
uint128 withdrawnReallocationReceived = _updateReallocationWithdraw(processReallocationData);
return withdrawnReallocationReceived;
}
/**
* @dev Update reallocation batch storage for index after withdrawing reallocated shares
* @param processReallocationData Data containing amount of optimized and not optimized shares to withdraw
* @return Withdrawn reallocation received
*/
function _updateReallocationWithdraw(ProcessReallocationData calldata processReallocationData) internal virtual returns(uint128) {
Strategy storage strategy = strategies[self];
uint24 stratIndex = _getProcessingIndex();
BatchReallocation storage batch = strategy.reallocationBatches[stratIndex];
// save actual withdrawn amount, without optimized one
uint128 withdrawnReallocationReceived = batch.withdrawnReallocationReceived;
strategy.optimizedSharesWithdrawn += processReallocationData.optimizedShares;
batch.withdrawnReallocationReceived += processReallocationData.optimizedWithdrawnAmount;
batch.withdrawnReallocationShares = processReallocationData.optimizedShares + processReallocationData.sharesToWithdraw;
return withdrawnReallocationReceived;
}
/**
* @notice Process deposit
* @param slippages Array of slippage parameters to apply when depositing
*/
function processDeposit(uint256[] calldata slippages)
external
override
{
slippages = _validateStrategyBalance(slippages);
if (depositSlippageSlots != 0)
_validateDepositSlippage(slippages);
_processDeposit(slippages);
}
/**
* @notice Returns total starategy balance includign pending rewards
* @return strategyBalance total starategy balance includign pending rewards
*/
function getStrategyUnderlyingWithRewards() public view override returns(uint128)
{
return _getStrategyUnderlyingWithRewards();
}
/**
* @notice Fast withdraw
* @param shares Shares to fast withdraw
* @param slippages Array of slippage parameters to apply when withdrawing
* @param swapData Swap slippage and path array
* @return Withdrawn amount withdawn
*/
function fastWithdraw(uint128 shares, uint256[] calldata slippages, SwapData[] calldata swapData) external override returns(uint128)
{
slippages = _validateStrategyBalance(slippages);
_validateRewardsSlippage(swapData);
if (processSlippageSlots != 0)
_validateProcessSlippage(slippages);
uint128 withdrawnAmount = _processFastWithdraw(shares, slippages, swapData);
strategies[self].totalShares -= shares;
return withdrawnAmount;
}
/**
* @notice Claims and possibly compounds strategy rewards.
*
* @param swapData swap data for processing
*/
function claimRewards(SwapData[] calldata swapData) external override
{
_validateRewardsSlippage(swapData);
_processRewards(swapData);
}
/**
* @notice Withdraws all actively deployed funds in the strategy, liquifying them in the process.
*
* @param recipient recipient of the withdrawn funds
* @param data data necessary execute the emergency withdraw
*/
function emergencyWithdraw(address recipient, uint256[] calldata data) external virtual override {
uint256 balanceBefore = underlying.balanceOf(address(this));
_emergencyWithdraw(recipient, data);
uint256 balanceAfter = underlying.balanceOf(address(this));
uint256 withdrawnAmount = 0;
if (balanceAfter > balanceBefore) {
withdrawnAmount = balanceAfter - balanceBefore;
}
Strategy storage strategy = strategies[self];
if (strategy.emergencyPending > 0) {
withdrawnAmount += strategy.emergencyPending;
strategy.emergencyPending = 0;
}
// also withdraw all unprocessed deposit for a strategy
if (strategy.pendingUser.deposit.get() > 0) {
withdrawnAmount += strategy.pendingUser.deposit.get();
strategy.pendingUser.deposit = 0;
}
if (strategy.pendingUserNext.deposit.get() > 0) {
withdrawnAmount += strategy.pendingUserNext.deposit.get();
strategy.pendingUserNext.deposit = 0;
}
// if strategy was already processed in the current index that hasn't finished yet,
// transfer the withdrawn amount
// reset total underlying to 0
if (strategy.index == globalIndex && doHardWorksLeft > 0) {
uint256 withdrawnReceived = strategy.batches[strategy.index].withdrawnReceived;
withdrawnAmount += withdrawnReceived;
strategy.batches[strategy.index].withdrawnReceived = 0;
strategy.totalUnderlying[strategy.index].amount = 0;
}
if (withdrawnAmount > 0) {
// check if the balance is high enough to withdraw the total withdrawnAmount
if (balanceAfter < withdrawnAmount) {
// if not withdraw the current balance
withdrawnAmount = balanceAfter;
}
underlying.safeTransfer(recipient, withdrawnAmount);
}
}
/**
* @notice Initialize a strategy.
* @dev Execute strategy specific one-time actions if needed.
*/
function initialize() external virtual override {}
/**
* @notice Disables a strategy.
* @dev Cleans strategy specific values if needed.
*/
function disable() external virtual override {}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @dev Validate strategy balance
* @param slippages Check if the strategy balance is within defined min and max values
* @return slippages Same array without first 2 slippages
*/
function _validateStrategyBalance(uint256[] calldata slippages) internal virtual returns(uint256[] calldata) {
if (doValidateBalance) {
require(slippages.length >= 2, "BaseStrategy:: _validateStrategyBalance: Invalid number of slippages");
uint128 strategyBalance = getStrategyBalance();
require(
slippages[0] <= strategyBalance &&
slippages[1] >= strategyBalance,
"BaseStrategy::_validateStrategyBalance: Bad strategy balance"
);
return slippages[2:];
}
return slippages;
}
/**
* @dev Validate reards slippage
* @param swapData Swap slippage and path array
*/
function _validateRewardsSlippage(SwapData[] calldata swapData) internal view virtual {
if (swapData.length > 0) {
require(
swapData.length == _getRewardSlippageSlots(),
"BaseStrategy::_validateSlippage: Invalid Number of reward slippages Defined"
);
}
}
/**
* @dev Retrieve reward slippage slots
* @return Reward slippage slots
*/
function _getRewardSlippageSlots() internal view virtual returns(uint256) {
return rewardSlippageSlots;
}
/**
* @dev Validate process slippage
* @param slippages parameters to verify validity of the strategy state
*/
function _validateProcessSlippage(uint256[] calldata slippages) internal view virtual {
_validateSlippage(slippages.length, processSlippageSlots);
}
/**
* @dev Validate reallocation slippage
* @param slippages parameters to verify validity of the strategy state
*/
function _validateReallocationSlippage(uint256[] calldata slippages) internal view virtual {
_validateSlippage(slippages.length, reallocationSlippageSlots);
}
/**
* @dev Validate deposit slippage
* @param slippages parameters to verify validity of the strategy state
*/
function _validateDepositSlippage(uint256[] calldata slippages) internal view virtual {
_validateSlippage(slippages.length, depositSlippageSlots);
}
/**
* @dev Validates the provided slippage in length.
* @param currentLength actual slippage array length
* @param shouldBeLength expected slippages array length
*/
function _validateSlippage(uint256 currentLength, uint256 shouldBeLength)
internal
view
virtual
{
require(
currentLength == shouldBeLength,
"BaseStrategy::_validateSlippage: Invalid Number of Slippages Defined"
);
}
/**
* @dev Retrieve processing index
* @return Processing index
*/
function _getProcessingIndex() internal view returns(uint24) {
return strategies[self].index + 1;
}
/**
* @dev Calculates shares before they are added to the total shares
* @param strategyTotalShares Total shares for strategy
* @param stratTotalUnderlying Total underlying for strategy
* @return newShares New shares calculated
*/
function _getNewSharesAfterWithdraw(uint128 strategyTotalShares, uint128 stratTotalUnderlying, uint128 depositAmount) internal pure returns(uint128 newShares){
uint128 oldUnderlying;
if (stratTotalUnderlying > depositAmount) {
oldUnderlying = stratTotalUnderlying - depositAmount;
}
if (strategyTotalShares == 0 || oldUnderlying == 0) {
// Enforce minimum shares size to avoid loss of share due to computation precision
newShares = (0 < depositAmount && depositAmount < MIN_SHARES) ? MIN_SHARES : depositAmount;
} else {
newShares = Math.getProportion128(depositAmount, strategyTotalShares, oldUnderlying);
}
}
/**
* @dev Calculates shares when they are already part of the total shares
*
* @param strategyTotalShares Total shares
* @param stratTotalUnderlying Total underlying
* @return newShares New shares calculated
*/
function _getNewShares(uint128 strategyTotalShares, uint128 stratTotalUnderlying, uint128 depositAmount) internal pure returns(uint128 newShares){
if (strategyTotalShares == 0 || stratTotalUnderlying == 0) {
// Enforce minimum shares size to avoid loss of share due to computation precision
newShares = (0 < depositAmount && depositAmount < MIN_SHARES) ? MIN_SHARES : depositAmount;
} else {
newShares = Math.getProportion128(depositAmount, strategyTotalShares, stratTotalUnderlying);
}
}
/**
* @dev Reset allowance to zero if previously set to a higher value.
* @param token Asset
* @param spender Spender address
*/
function _resetAllowance(IERC20 token, address spender) internal {
if (token.allowance(address(this), spender) > 0) {
token.safeApprove(spender, 0);
}
}
/* ========== VIRTUAL FUNCTIONS ========== */
function getStrategyBalance()
public
view
virtual
override
returns (uint128);
function _processRewards(SwapData[] calldata) internal virtual;
function _emergencyWithdraw(address recipient, uint256[] calldata data) internal virtual;
function _process(uint256[] memory, uint128 reallocateSharesToWithdraw) internal virtual;
function _processDeposit(uint256[] memory) internal virtual;
function _getStrategyUnderlyingWithRewards() internal view virtual returns(uint128);
function _processFastWithdraw(uint128, uint256[] memory, SwapData[] calldata) internal virtual returns(uint128);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "./RewardStrategy.sol";
import "../shared/SwapHelperMainnet.sol";
/**
* @notice Claim full single reward strategy logic
*/
abstract contract ClaimFullSingleRewardStrategy is RewardStrategy, SwapHelperMainnet {
/* ========== STATE VARIABLES ========== */
IERC20 internal immutable rewardToken;
/* ========== CONSTRUCTOR ========== */
/**
* @notice Set initial values
* @param _rewardToken Reward token contract
*/
constructor(
IERC20 _rewardToken
) {
require(address(_rewardToken) != address(0), "ClaimFullSingleRewardStrategy::constructor: Token address cannot be 0");
rewardToken = _rewardToken;
}
/* ========== OVERRIDDEN FUNCTIONS ========== */
/**
* @notice Claim rewards
* @param swapData Slippage and path array
* @return Rewards
*/
function _claimRewards(SwapData[] calldata swapData) internal override returns(Reward[] memory) {
return _claimSingleRewards(type(uint128).max, swapData);
}
/**
* @dev Claim fast withdraw rewards
* @param shares Amount of shares
* @param swapData Swap slippage and path
* @return Rewards
*/
function _claimFastWithdrawRewards(uint128 shares, SwapData[] calldata swapData) internal override returns(Reward[] memory) {
return _claimSingleRewards(shares, swapData);
}
/* ========== PRIVATE FUNCTIONS ========== */
/**
* @dev Claim single rewards
* @param shares Amount of shares
* @param swapData Swap slippage and path
* @return rewards Collected reward amounts
*/
function _claimSingleRewards(uint128 shares, SwapData[] calldata swapData) private returns(Reward[] memory rewards) {
if (swapData.length > 0 && swapData[0].slippage > 0) {
uint128 rewardAmount = _claimStrategyReward();
if (rewardAmount > 0) {
Strategy storage strategy = strategies[self];
uint128 claimedAmount = _getRewardClaimAmount(shares, rewardAmount);
rewards = new Reward[](1);
rewards[0] = Reward(claimedAmount, rewardToken);
// if we don't claim all the rewards save the amount left, otherwise reset amount left to 0
if (rewardAmount > claimedAmount) {
uint128 rewardAmountLeft = rewardAmount - claimedAmount;
strategy.pendingRewards[address(rewardToken)] = rewardAmountLeft;
} else if (strategy.pendingRewards[address(rewardToken)] > 0) {
strategy.pendingRewards[address(rewardToken)] = 0;
}
}
}
}
/* ========== VIRTUAL FUNCTIONS ========== */
function _claimStrategyReward() internal virtual returns(uint128);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "./BaseStrategy.sol";
import "../libraries/Max/128Bit.sol";
import "../libraries/Math.sol";
struct ProcessInfo {
uint128 totalWithdrawReceived;
uint128 userDepositReceived;
}
/**
* @notice Process strategy logic
*/
abstract contract ProcessStrategy is BaseStrategy {
using Max128Bit for uint128;
/* ========== OVERRIDDEN FUNCTIONS ========== */
/**
* @notice Process the strategy pending deposits, withdrawals, and collected strategy rewards
* @dev
* Deposit amount amd withdrawal shares are matched between eachother, effecively only one of
* those 2 is called. Shares are converted to the dollar value, based on the current strategy
* total balance. This ensures the minimum amount of assets are moved around to lower the price
* drift and total fees paid to the protocols the strategy is interacting with (if there are any)
*
* @param slippages Strategy slippage values verifying the validity of the strategy state
* @param reallocateSharesToWithdraw Reallocation shares to withdraw (non-zero only if reallocation DHW is in progress, otherwise 0)
*/
function _process(uint256[] memory slippages, uint128 reallocateSharesToWithdraw) internal override virtual {
// PREPARE
Strategy storage strategy = strategies[self];
uint24 processingIndex = _getProcessingIndex();
Batch storage batch = strategy.batches[processingIndex];
uint128 strategyTotalShares = strategy.totalShares;
uint128 pendingSharesToWithdraw = strategy.pendingUser.sharesToWithdraw.get();
uint128 userDeposit = strategy.pendingUser.deposit.get();
// CALCULATE THE ACTION
// if withdrawing for reallocating, add shares to total withdraw shares
if (reallocateSharesToWithdraw > 0) {
pendingSharesToWithdraw += reallocateSharesToWithdraw;
}
// total deposit received from users + compound reward (if there are any)
uint128 totalPendingDeposit = userDeposit;
// add compound reward (pendingDepositReward) to deposit
uint128 withdrawalReward = 0;
if (strategy.pendingDepositReward > 0) {
uint128 pendingDepositReward = strategy.pendingDepositReward;
totalPendingDeposit += pendingDepositReward;
// calculate compound reward (withdrawalReward) for users withdrawing in this batch
if (pendingSharesToWithdraw > 0 && strategyTotalShares > 0) {
withdrawalReward = Math.getProportion128(pendingSharesToWithdraw, pendingDepositReward, strategyTotalShares);
// substract withdrawal reward from total deposit
totalPendingDeposit -= withdrawalReward;
}
// Reset pendingDepositReward
strategy.pendingDepositReward = 0;
}
// if there is no pending deposit or withdrawals, return
if (totalPendingDeposit == 0 && pendingSharesToWithdraw == 0) {
return;
}
uint128 pendingWithdrawalAmount = 0;
if (pendingSharesToWithdraw > 0) {
pendingWithdrawalAmount =
Math.getProportion128(getStrategyBalance(), pendingSharesToWithdraw, strategyTotalShares);
}
// ACTION: DEPOSIT OR WITHDRAW
ProcessInfo memory processInfo;
if (totalPendingDeposit > pendingWithdrawalAmount) { // DEPOSIT
// uint128 amount = totalPendingDeposit - pendingWithdrawalAmount;
uint128 depositReceived = _deposit(totalPendingDeposit - pendingWithdrawalAmount, slippages);
processInfo.totalWithdrawReceived = pendingWithdrawalAmount + withdrawalReward;
// pendingWithdrawalAmount is optimized deposit: totalPendingDeposit - amount;
uint128 totalDepositReceived = depositReceived + pendingWithdrawalAmount;
// calculate user deposit received, excluding compound rewards
processInfo.userDepositReceived = Math.getProportion128(totalDepositReceived, userDeposit, totalPendingDeposit);
} else if (totalPendingDeposit < pendingWithdrawalAmount) { // WITHDRAW
// uint128 amount = pendingWithdrawalAmount - totalPendingDeposit;
uint128 withdrawReceived = _withdraw(
// calculate back the shares from actual withdraw amount
// NOTE: we can do unchecked calculation and casting as
// the multiplier is always smaller than the divisor
Math.getProportion128Unchecked(
(pendingWithdrawalAmount - totalPendingDeposit),
pendingSharesToWithdraw,
pendingWithdrawalAmount
),
slippages
);
// optimized withdraw is total pending deposit: pendingWithdrawalAmount - amount = totalPendingDeposit;
processInfo.totalWithdrawReceived = withdrawReceived + totalPendingDeposit + withdrawalReward;
processInfo.userDepositReceived = userDeposit;
} else {
processInfo.totalWithdrawReceived = pendingWithdrawalAmount + withdrawalReward;
processInfo.userDepositReceived = userDeposit;
}
// UPDATE STORAGE AFTER
{
uint128 stratTotalUnderlying = getStrategyBalance();
// Update withdraw batch
if (pendingSharesToWithdraw > 0) {
batch.withdrawnReceived = processInfo.totalWithdrawReceived;
batch.withdrawnShares = pendingSharesToWithdraw;
strategyTotalShares -= pendingSharesToWithdraw;
// update reallocation batch
if (reallocateSharesToWithdraw > 0) {
BatchReallocation storage reallocationBatch = strategy.reallocationBatches[processingIndex];
uint128 withdrawnReallocationReceived =
Math.getProportion128(processInfo.totalWithdrawReceived, reallocateSharesToWithdraw, pendingSharesToWithdraw);
reallocationBatch.withdrawnReallocationReceived = withdrawnReallocationReceived;
// substract reallocation values from user values
batch.withdrawnReceived -= withdrawnReallocationReceived;
batch.withdrawnShares -= reallocateSharesToWithdraw;
}
}
// Update deposit batch
if (userDeposit > 0) {
uint128 newShares = _getNewSharesAfterWithdraw(strategyTotalShares, stratTotalUnderlying, processInfo.userDepositReceived);
batch.deposited = userDeposit;
batch.depositedReceived = processInfo.userDepositReceived;
batch.depositedSharesReceived = newShares;
strategyTotalShares += newShares;
}
// Update shares
if (strategyTotalShares != strategy.totalShares) {
strategy.totalShares = strategyTotalShares;
}
// Set underlying at index
strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying;
strategy.totalUnderlying[processingIndex].totalShares = strategyTotalShares;
}
}
/**
* @notice Process deposit
* @param slippages Slippages array
*/
function _processDeposit(uint256[] memory slippages) internal override virtual {
Strategy storage strategy = strategies[self];
uint128 depositOptimizedAmount = strategy.pendingReallocateOptimizedDeposit;
uint128 optimizedSharesWithdrawn = strategy.optimizedSharesWithdrawn;
uint128 depositAmount = strategy.pendingReallocateDeposit;
// if a strategy is not part of reallocation return
if (
depositOptimizedAmount == 0 &&
optimizedSharesWithdrawn == 0 &&
depositAmount == 0
) {
return;
}
uint24 processingIndex = _getProcessingIndex();
BatchReallocation storage reallocationBatch = strategy.reallocationBatches[processingIndex];
uint128 strategyTotalShares = strategy.totalShares;
// get shares from optimized deposit
if (depositOptimizedAmount > 0) {
uint128 stratTotalUnderlying = getStrategyBalance();
uint128 newShares = _getNewShares(strategyTotalShares, stratTotalUnderlying, depositOptimizedAmount);
// add new shares
strategyTotalShares += newShares;
// update reallocation batch
reallocationBatch.depositedReallocation = depositOptimizedAmount;
reallocationBatch.depositedReallocationSharesReceived = newShares;
strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying;
// reset
strategy.pendingReallocateOptimizedDeposit = 0;
}
// remove optimized withdraw shares
if (optimizedSharesWithdrawn > 0) {
strategyTotalShares -= optimizedSharesWithdrawn;
// reset
strategy.optimizedSharesWithdrawn = 0;
}
// get shares from actual deposit
if (depositAmount > 0) {
// deposit
uint128 depositReceived = _deposit(depositAmount, slippages);
// NOTE: might return it from _deposit (only certain strategies need it)
uint128 stratTotalUnderlying = getStrategyBalance();
uint128 newShares = _getNewSharesAfterWithdraw(strategyTotalShares, stratTotalUnderlying, depositReceived);
// add new shares
strategyTotalShares += newShares;
// update reallocation batch
reallocationBatch.depositedReallocation += depositReceived;
reallocationBatch.depositedReallocationSharesReceived += newShares;
strategy.totalUnderlying[processingIndex].amount = stratTotalUnderlying;
// reset
strategy.pendingReallocateDeposit = 0;
}
// update share storage
strategy.totalUnderlying[processingIndex].totalShares = strategyTotalShares;
strategy.totalShares = strategyTotalShares;
}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @notice get the value of the strategy shares in the underlying tokens
* @param shares Number of shares
* @return amount Underling amount representing the `share` value of the strategy
*/
function _getSharesToAmount(uint256 shares) internal virtual returns(uint128 amount) {
amount = Math.getProportion128( getStrategyBalance(), shares, strategies[self].totalShares );
}
/**
* @notice get slippage amount, and action type (withdraw/deposit).
* @dev
* Most significant bit represents an action, 0 for a withdrawal and 1 for deposit.
*
* This ensures the slippage will be used for the action intended by the do-hard-worker,
* otherwise the transavtion will revert.
*
* @param slippageAction number containing the slippage action and the actual slippage amount
* @return isDeposit Flag showing if the slippage is for the deposit action
* @return slippage the slippage value cleaned of the most significant bit
*/
function _getSlippageAction(uint256 slippageAction) internal pure returns (bool isDeposit, uint256 slippage) {
// remove most significant bit
slippage = (slippageAction << 1) >> 1;
// if values are not the same (the removed bit was 1) set action to deposit
if (slippageAction != slippage) {
isDeposit = true;
}
}
/* ========== VIRTUAL FUNCTIONS ========== */
function _deposit(uint128 amount, uint256[] memory slippages) internal virtual returns(uint128 depositReceived);
function _withdraw(uint128 shares, uint256[] memory slippages) internal virtual returns(uint128 withdrawReceived);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "./ProcessStrategy.sol";
import "../shared/SwapHelper.sol";
struct Reward {
uint256 amount;
IERC20 token;
}
/**
* @notice Reward strategy logic
*/
abstract contract RewardStrategy is ProcessStrategy, SwapHelper {
/* ========== OVERRIDDEN FUNCTIONS ========== */
/**
* @notice Gey strategy underlying asset with rewards
* @return Total underlying
*/
function _getStrategyUnderlyingWithRewards() internal view override virtual returns(uint128) {
Strategy storage strategy = strategies[self];
uint128 totalUnderlying = getStrategyBalance();
totalUnderlying += strategy.pendingDepositReward;
return totalUnderlying;
}
/**
* @notice Process an instant withdrawal from the protocol per users request.
*
* @param shares Amount of shares
* @param slippages Array of slippages
* @param swapData Data used in processing
* @return Withdrawn amount
*/
function _processFastWithdraw(uint128 shares, uint256[] memory slippages, SwapData[] calldata swapData) internal override virtual returns(uint128) {
uint128 withdrawRewards = _processFastWithdrawalRewards(shares, swapData);
uint128 withdrawReceived = _withdraw(shares, slippages);
return withdrawReceived + withdrawRewards;
}
/**
* @notice Process rewards
* @param swapData Data used in processing
*/
function _processRewards(SwapData[] calldata swapData) internal override virtual {
Strategy storage strategy = strategies[self];
Reward[] memory rewards = _claimRewards(swapData);
uint128 collectedAmount = _sellRewards(rewards, swapData);
if (collectedAmount > 0) {
strategy.pendingDepositReward += collectedAmount;
}
}
/* ========== INTERNAL FUNCTIONS ========== */
/**
* @notice Process fast withdrawal rewards
* @param shares Amount of shares
* @param swapData Values used for swapping the rewards
* @return withdrawalRewards Withdrawal rewards
*/
function _processFastWithdrawalRewards(uint128 shares, SwapData[] calldata swapData) internal virtual returns(uint128 withdrawalRewards) {
Strategy storage strategy = strategies[self];
Reward[] memory rewards = _claimFastWithdrawRewards(shares, swapData);
withdrawalRewards += _sellRewards(rewards, swapData);
if (strategy.pendingDepositReward > 0) {
uint128 fastWithdrawCompound = Math.getProportion128(strategy.pendingDepositReward, shares, strategy.totalShares);
if (fastWithdrawCompound > 0) {
strategy.pendingDepositReward -= fastWithdrawCompound;
withdrawalRewards += fastWithdrawCompound;
}
}
}
/**
* @notice Sell rewards to the underlying token
* @param rewards Rewards to sell
* @param swapData Values used for swapping the rewards
* @return collectedAmount Collected underlying amount
*/
function _sellRewards(Reward[] memory rewards, SwapData[] calldata swapData) internal virtual returns(uint128 collectedAmount) {
for (uint256 i = 0; i < rewards.length; i++) {
// add compound amount from current batch to the fast withdraw
if (rewards[i].amount > 0) {
uint128 compoundAmount = SafeCast.toUint128(
_approveAndSwap(
rewards[i].token,
underlying,
rewards[i].amount,
swapData[i]
)
);
// add to pending reward
collectedAmount += compoundAmount;
}
}
}
/**
* @notice Get reward claim amount for `shares`
* @param shares Amount of shares
* @param rewardAmount Total reward amount
* @return rewardAmount Amount of reward for the shares
*/
function _getRewardClaimAmount(uint128 shares, uint256 rewardAmount) internal virtual view returns(uint128) {
// for do hard work claim everything
if (shares == type(uint128).max) {
return SafeCast.toUint128(rewardAmount);
} else { // for fast withdrawal claim calculate user withdraw amount
return SafeCast.toUint128((rewardAmount * shares) / strategies[self].totalShares);
}
}
/* ========== VIRTUAL FUNCTIONS ========== */
function _claimFastWithdrawRewards(uint128 shares, SwapData[] calldata swapData) internal virtual returns(Reward[] memory rewards);
function _claimRewards(SwapData[] calldata swapData) internal virtual returns(Reward[] memory rewards);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;
import "../ClaimFullSingleRewardStrategy.sol";
import "../../external/interfaces/harvest/Vault/IHarvestVault.sol";
import "../../external/interfaces/harvest/IHarvestPool.sol";
/**
* @notice Harvest strategy implementation
*/
contract HarvestStrategy is ClaimFullSingleRewardStrategy {
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
/// @notice Harvest vault contract
IHarvestVault public immutable vault;
/// @notice Harvest pool contract
IHarvestPool public immutable pool;
/* ========== CONSTRUCTOR ========== */
/**
* @notice Set initial values
* @param _farm Farm contract
* @param _vault Vault contract
* @param _pool Pool contract
* @param _underlying Underlying asset
*/
constructor(
IERC20 _farm,
IHarvestVault _vault,
IHarvestPool _pool,
IERC20 _underlying
)
BaseStrategy(_underlying, 1, 0, 0, 0, false, false)
ClaimFullSingleRewardStrategy(_farm)
{
require(address(_vault) != address(0), "HarvestStrategy::constructor: Vault address cannot be 0");
require(address(_pool) != address(0), "HarvestStrategy::constructor: Pool address cannot be 0");
vault = _vault;
pool = _pool;
}
/* ========== VIEWS ========== */
/**
* @notice Get strategy balance
* @return Strategy balance
*/
function getStrategyBalance() public view override returns(uint128) {
uint256 fTokenBalance = pool.balanceOf(address(this));
return SafeCast.toUint128(_getfTokenValue(fTokenBalance));
}
/* ========== OVERRIDDEN FUNCTIONS ========== */
/**
* @dev Claim strategy reward
* @return Reward amount
*/
function _claimStrategyReward() internal override returns(uint128) {
// claim
uint256 rewardBefore = rewardToken.balanceOf(address(this));
pool.getReward();
uint256 rewardAmount = rewardToken.balanceOf(address(this)) - rewardBefore;
// add already claimed rewards
rewardAmount += strategies[self].pendingRewards[address(rewardToken)];
return SafeCast.toUint128(rewardAmount);
}
/**
* @dev Deposit
* @param amount Amount to deposit
* @return Deposited amount
*/
function _deposit(uint128 amount, uint256[] memory) internal override returns(uint128) {
// deposit underlying
underlying.safeApprove(address(vault), amount);
uint256 fTokenBefore = vault.balanceOf(address(this));
vault.deposit(amount);
uint256 fTokenNew = vault.balanceOf(address(this)) - fTokenBefore;
_resetAllowance(underlying, address(vault));
// stake fTokens
vault.approve(address(pool), fTokenNew);
pool.stake(fTokenNew);
return SafeCast.toUint128(_getfTokenValue(fTokenNew));
}
/**
* @dev Withdraw
* @param shares Shares to withdraw
* @return Withdrawn amount
*/
function _withdraw(uint128 shares, uint256[] memory) internal override returns(uint128) {
uint256 fTokensTotal = pool.balanceOf(address(this));
uint256 fWithdrawAmount = (fTokensTotal * shares) / strategies[self].totalShares;
// withdraw staked fTokens from pool
pool.withdraw(fWithdrawAmount);
// withdraw fTokens from vault
uint256 undelyingBefore = underlying.balanceOf(address(this));
vault.withdraw(fWithdrawAmount);
uint256 undelyingWithdrawn = underlying.balanceOf(address(this)) - undelyingBefore;
return SafeCast.toUint128(undelyingWithdrawn);
}
/**
* @dev Emergency withdraw
*/
function _emergencyWithdraw(address, uint256[] calldata) internal override {
pool.exit();
vault.withdraw(vault.balanceOf(address(this)));
}
/* ========== PRIVATE FUNCTIONS ========== */
/**
* @dev Return value of fTokens in the underlying asset
* @param fTokenAmount Amount of fTokens
* @return value in the underlying asset
*/
function _getfTokenValue(uint256 fTokenAmount) private view returns(uint256) {
if (fTokenAmount == 0)
return 0;
uint256 vaultTotal = vault.underlyingBalanceWithInvestment();
return (vaultTotal * fTokenAmount) / vault.totalSupply();
}
} | * @notice Process deposit @param slippages Array of slippage parameters to apply when depositing/ | function processDeposit(uint256[] calldata slippages)
external
override
{
slippages = _validateStrategyBalance(slippages);
if (depositSlippageSlots != 0)
_validateDepositSlippage(slippages);
_processDeposit(slippages);
}
| 18,123 | [
1,
2227,
443,
1724,
225,
272,
3169,
7267,
1510,
434,
272,
3169,
2433,
1472,
358,
2230,
1347,
443,
1724,
310,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1207,
758,
1724,
12,
11890,
5034,
8526,
745,
892,
272,
3169,
7267,
13,
203,
3639,
3903,
203,
3639,
3849,
203,
565,
288,
203,
3639,
272,
3169,
7267,
273,
389,
5662,
4525,
13937,
12,
87,
3169,
7267,
1769,
203,
203,
3639,
309,
261,
323,
1724,
55,
3169,
2433,
16266,
480,
374,
13,
203,
5411,
389,
5662,
758,
1724,
55,
3169,
2433,
12,
87,
3169,
7267,
1769,
203,
203,
3639,
389,
2567,
758,
1724,
12,
87,
3169,
7267,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.6.12;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
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;
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library 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");
}
}
}
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);
}
}
}
}
interface IHegicStaking is IERC20 {
function claimProfit() external returns (uint profit);
function buy(uint amount) external;
function sell(uint amount) external;
function profitOf(address account) external view returns (uint profit);
}
interface IHegicStakingETH is IHegicStaking {
function sendProfit() external payable;
}
interface IHegicStakingERC20 is IHegicStaking {
function sendProfit(uint amount) external;
}
contract Migrations {
address public owner = msg.sender;
uint public last_completed_migration;
modifier restricted() {
require(
msg.sender == owner,
"This function is restricted to the contract's owner"
);
_;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
abstract contract HegicPooledStaking is Ownable, ERC20{
using SafeMath for uint;
using SafeERC20 for IERC20;
// HEGIC token
IERC20 public immutable HEGIC;
// Hegic Protocol Staking Contract
IHegicStaking public staking;
// Parameters
uint public LOCK_UP_PERIOD = 24 hours;
uint public STAKING_LOT_PRICE = 888_000e18;
uint public ACCURACY = 1e30;
address payable public FALLBACK_RECIPIENT;
address payable public FEE_RECIPIENT;
uint public FEE;
// Monitoring variables
uint public numberOfStakingLots;
uint public totalBalance;
uint public lockedBalance;
uint public totalProfitPerToken;
bool public emergencyUnlockState;
bool public depositsAllowed;
// Staking lots mappings
mapping(uint => mapping(address => uint)) stakingLotShares;
mapping(uint => address[]) stakingLotOwners;
mapping(uint => uint) stakingLotUnlockTime;
mapping(uint => bool) stakingLotActive;
mapping(uint => uint) startProfit;
// Owners mappings
mapping(address => uint[]) ownedStakingLots;
mapping(address => uint) savedProfit;
mapping(address => uint) lastProfit;
mapping(address => uint) ownerPerformanceFee;
// Events
event Deposit(address account, uint amount);
event Withdraw(address account, uint amount);
event AddLiquidity(address account, uint amount, uint lotId);
event BuyLot(address account, uint lotId);
event SellLot(address account, uint lotId);
event PayProfit(address account, uint profit, uint fee);
constructor(IERC20 _token, IHegicStaking _staking, string memory name, string memory symbol) public ERC20(name, symbol){
HEGIC = _token;
staking = _staking;
totalBalance = 0;
lockedBalance = 0;
numberOfStakingLots = 0;
totalProfitPerToken = 0;
FALLBACK_RECIPIENT = msg.sender;
FEE_RECIPIENT = msg.sender;
FEE = 5;
emergencyUnlockState = false;
depositsAllowed = true;
// Approving to Staking Lot Contract
_token.approve(address(_staking), 888e30);
}
// Payable
receive() external payable {}
/**
* @notice Lets the owner deactivate lockUp period. This means that if set to true,
* staking lot owners will be able to exitFromStakingLot immediately.
* Reserved for emergency cases only (e.g. migration of liquidity).
* OWNER WILL NOT BE ABLE TO WITHDRAW FUNDS; ONLY UNLOCK FUNDS FOR YOU TO WITHDRAW THEM.
* @param _unlock true or false, default = false. If set to true, owners will be able to withdraw HEGIC
* immediately
*/
function emergencyUnlock(bool _unlock) external onlyOwner {
emergencyUnlockState = _unlock;
}
/**
* @notice Stops the ability to add new deposits
* @param _allow If set to false, new deposits will be rejected
*/
function allowDeposits(bool _allow) external onlyOwner {
depositsAllowed = _allow;
}
/**
* @notice Changes Fee paid to creator (only paid when taking profits)
* @param _fee New fee
*/
function changeFee(uint _fee) external onlyOwner {
require(_fee >= 0, "Fee too low");
require(_fee <= 8, "Fee too high");
FEE = _fee;
}
/**
* @notice Changes Fee Recipient address
* @param _recipient New address
*/
function changeFeeRecipient(address _recipient) external onlyOwner {
FEE_RECIPIENT = payable(_recipient);
}
/**
* @notice Changes Fallback Recipient address. This is only used in case of unexpected behavior
* @param _recipient New address
*/
function changeFallbackRecipient(address _recipient) external onlyOwner {
FALLBACK_RECIPIENT = payable(_recipient);
}
/**
* @notice Changes lock up period. This lock up period is used to lock funds in a staking for for at least some time
* IMPORTANT: Changes only apply to new Staking Lots
* @param _newLockUpPeriod New lock up period in seconds
*/
function changeLockUpPeriod(uint _newLockUpPeriod) external onlyOwner {
require(_newLockUpPeriod <= 2 weeks, "Lock up period too long");
require(_newLockUpPeriod >= 24 hours, "Lock up period too short");
LOCK_UP_PERIOD = _newLockUpPeriod;
}
/**
* @notice Main EXTERNAL function. Deposits HEGIC for the next staking lot.
* If not enough, deposits will be stored until at least 888_000 HEGIC are available.
* Then, the contract will buy a Hegic Staking Lot.
* Once a Staking Lot is bought, users have to wait LOCK_UP_PERIOD (default = 2 weeks) to withdraw funds.
* @param _HEGICAmount Amount of HEGIC to deposit in next staking lot
*/
function deposit(uint _HEGICAmount) external {
require(_HEGICAmount > 0, "Amount too low");
require(_HEGICAmount < STAKING_LOT_PRICE, "Amount too high, buy your own lot");
require(depositsAllowed, "Deposits are not allowed at the moment");
// set fee for that staking lot owner - this effectively sets the maximum FEE an owner can have
// each time user deposits, this checks if current fee is higher or lower than previous fees
// and updates it if it is lower
if(ownerPerformanceFee[msg.sender] > FEE || balanceOf(msg.sender) == 0)
ownerPerformanceFee[msg.sender] = FEE;
//receive deposit
depositHegic(_HEGICAmount);
// use new liquidity (either stores it for next purchase or purchases right away)
useLiquidity(_HEGICAmount, msg.sender);
emit Deposit(msg.sender, _HEGICAmount);
}
/**
* @notice Internal function to transfer deposited HEGIC to the contract and mint sHEGIC (Staked HEGIC)
* @param _HEGICAmount Amount of HEGIC to deposit // Amount of sHEGIC that will be minted
*/
function depositHegic(uint _HEGICAmount) internal {
totalBalance = totalBalance.add(_HEGICAmount);
_mint(msg.sender, _HEGICAmount);
HEGIC.safeTransferFrom(msg.sender, address(this), _HEGICAmount);
}
/**
* @notice Use certain amount of liquidity. Internal function in charge of buying a new lot if enough balance.
* If there is not enough balance to buy a new lot, it will store the HEGIC
* If available balance + _HEGICAmount is higher than STAKING_LOT_PRICE (888_000HEGIC), the remaining
* amount will be stored for the next staking lot purchase. This remaining amount can be withdrawed with no lock up period
*
* @param _HEGICAmount Amount of HEGIC to be used
* @param _account Account that owns _HEGICAmount to which any purchase will be credited to
*/
function useLiquidity(uint _HEGICAmount, address _account) internal {
if(totalBalance.sub(lockedBalance) >= STAKING_LOT_PRICE){
uint pendingAmount = totalBalance.sub(lockedBalance).sub(STAKING_LOT_PRICE);
addToNextLot(_HEGICAmount.sub(pendingAmount), _account);
buyStakingLot();
if(pendingAmount > 0) addToNextLot(pendingAmount, _account);
} else {
addToNextLot(_HEGICAmount, _account);
}
}
/**
* @notice Internal function in charge of buying a new Staking Lot from the Hegic Staking Contract
* Also, it will set up the Lock up AND increase the number of staking lots
*/
function buyStakingLot() internal {
lockedBalance = lockedBalance.add(STAKING_LOT_PRICE);
staking.buy(1);
emit BuyLot(msg.sender, numberOfStakingLots);
startProfit[numberOfStakingLots] = totalProfitPerToken;
stakingLotUnlockTime[numberOfStakingLots] = now + LOCK_UP_PERIOD;
stakingLotActive[numberOfStakingLots] = true;
numberOfStakingLots = numberOfStakingLots + 1;
}
/**
* @notice Internal function in charge of adding the _amount HEGIC to the next lot ledger.
* User will be added as an owner of the lot and will be credited with _amount shares of that lot (total = 888_000 shares)
* @param _amount Amount of HEGIC to be used
* @param _account Account to which _amount will be credited to
*/
function addToNextLot(uint _amount, address _account) internal {
if(stakingLotShares[numberOfStakingLots][_account] == 0) {
ownedStakingLots[_account].push(numberOfStakingLots); // if first contribution in this lot: add to list
stakingLotOwners[numberOfStakingLots].push(_account);
}
// add to shares in next Staking Lot
stakingLotShares[numberOfStakingLots][_account] = stakingLotShares[numberOfStakingLots][_account].add(_amount);
emit AddLiquidity(_account, _amount, numberOfStakingLots);
}
/**
* @notice internal function that withdraws HEGIC deposited in exchange of sHEGIC
*
* @param _amount Amount of sHEGIC to be burned // Amount of HEGIC to be received
*/
function exchangeStakedForReal(uint _amount) internal {
totalBalance = totalBalance.sub(_amount);
_burn(msg.sender, _amount);
HEGIC.safeTransfer(msg.sender, _amount);
emit Withdraw(msg.sender, _amount);
}
/**
* @notice Main EXTERNAL function. This function is called to exit from a certain Staking Lot
* Calling this function will result in the withdrawal of allocated HEGIC for msg.sender
* Owners that are not withdrawing funds will be credited with shares of the next lot to be purchased
*
* @param _slotId Amount of HEGIC to be used
*/
function exitFromStakingLot(uint _slotId) external {
require(stakingLotShares[_slotId][msg.sender] > 0, "Not participating in this lot");
require(_slotId <= numberOfStakingLots, "Staking lot not found");
// if HEGIC not yet staked
if(_slotId == numberOfStakingLots){
uint shares = stakingLotShares[_slotId][msg.sender];
stakingLotShares[_slotId][msg.sender] = 0;
exchangeStakedForReal(shares);
} else {
require((stakingLotUnlockTime[_slotId] <= now) || emergencyUnlockState, "Staking Lot is still locked");
// it is important to withdraw unused funds first to avoid re-ordering attack
require(stakingLotShares[numberOfStakingLots][msg.sender] == 0, "Please withdraw your non-staked liquidity first");
// sell lot
staking.sell(1);
emit SellLot(msg.sender, _slotId);
stakingLotActive[_slotId] = false;
address[] memory slOwners = stakingLotOwners[_slotId];
// I unlock and withdraw msg.sender funds to avoid using her funds in the for loop
uint shares = stakingLotShares[_slotId][msg.sender];
stakingLotShares[_slotId][msg.sender] = 0;
exchangeStakedForReal(shares);
lockedBalance -= shares;
address owner;
for(uint i = 0; i < slOwners.length; i++) {
owner = slOwners[i];
shares = stakingLotShares[_slotId][owner];
stakingLotShares[_slotId][owner] = 0; // put back to 0 the participation in this lot
// put liquidity into next staking lot OR pay staked Hegic back if msg.sender
if(owner != msg.sender) {
lockedBalance -= shares;
saveProfit(owner);
useLiquidity(shares, owner);
}
}
}
}
/**
* @notice Virtual function. To be called to claim Profit from Hegic Staking Contracts.
* It will update profit of current staking lot owners
*/
function updateProfit() public virtual;
/**
* @notice EXTERNAL function. Calling this function will result in receiving profits accumulated
* during the time the HEGIC were deposited
*
*/
function claimProfit() external {
uint profit = saveProfit(msg.sender);
savedProfit[msg.sender] = 0;
_transferProfit(profit, msg.sender, ownerPerformanceFee[msg.sender]);
emit PayProfit(msg.sender, profit, ownerPerformanceFee[msg.sender]);
}
/**
* @notice Support function. Calculates how much of the totalProfitPerToken is not to be paid to an account
* This may be because it was already paid, it was earned before HEGIC were staked, ...
*
* @param _account Amount of HEGIC to be used
*/
function getNotPayableProfit(address _account) public view returns (uint notPayableProfit) {
if(ownedStakingLots[_account].length > 0){
uint lastStakingLot = ownedStakingLots[_account][ownedStakingLots[_account].length-1];
uint accountLastProfit = lastProfit[_account];
if(accountLastProfit <= startProfit[lastStakingLot]) {
// previous lastProfit * number of shares excluding last contribution (Last Staking Lot) + start Profit of Last Staking Lot
uint lastTakenProfit = accountLastProfit.mul(balanceOf(_account).sub(stakingLotShares[lastStakingLot][_account]));
uint initialNotPayableProfit = startProfit[lastStakingLot].mul(stakingLotShares[lastStakingLot][_account]);
notPayableProfit = lastTakenProfit.add(initialNotPayableProfit);
} else {
notPayableProfit = accountLastProfit.mul(balanceOf(_account).sub(getUnlockedTokens(_account)));
}
}
}
/**
* @notice Support function. Calculates how many of the deposited tokens are not currently staked
* These are not producing profits
*
* @param _account Amount of HEGIC to be used
*/
function getUnlockedTokens(address _account) public view returns (uint lockedTokens){
if(ownedStakingLots[_account].length > 0) {
uint lastStakingLot = ownedStakingLots[_account][ownedStakingLots[_account].length-1];
if(lastStakingLot == numberOfStakingLots) lockedTokens = stakingLotShares[lastStakingLot][_account];
}
}
/**
* @notice Support function. Calculates how many of the deposited tokens are not currently staked
* These are not producing profits and will not be accounted for profit calcs.
*
* @param _account Account
*/
function getUnsaved(address _account) public view returns (uint profit) {
uint accountBalance = balanceOf(_account);
uint unlockedTokens = getUnlockedTokens(_account);
uint tokens = accountBalance.sub(unlockedTokens);
profit = 0;
if(tokens > 0)
profit = totalProfitPerToken.mul(tokens).sub(getNotPayableProfit(_account)).div(ACCURACY);
}
/**
* @notice Support function. Calculates how much profit would receive each token if the contract claimed
* profit accumulated in Hegic's Staking Lot contracts
*
* @param _account Account to do the calculation to
*/
function getUnreceivedProfit(address _account) public view returns (uint unreceived){
uint accountBalance = balanceOf(_account);
uint unlockedTokens = getUnlockedTokens(_account);
uint tokens = accountBalance.sub(unlockedTokens);
uint profit = staking.profitOf(address(this));
if(lockedBalance > 0)
unreceived = profit.mul(ACCURACY).div(lockedBalance).mul(tokens).div(ACCURACY);
else
unreceived = 0;
}
/**
* @notice EXTERNAL View function. Returns profit to be paid when claimed for _account
*
* @param _account Account
*/
function profitOf(address _account) external view returns (uint profit) {
uint unreceived = getUnreceivedProfit(_account);
return savedProfit[_account].add(getUnsaved(_account)).add(unreceived);
}
/**
* @notice Internal function that saves unpaid profit to keep accounting.
*
* @param _account Account to save profit to
*/
function saveProfit(address _account) internal returns (uint profit) {
updateProfit();
uint unsaved = getUnsaved(_account);
lastProfit[_account] = totalProfitPerToken;
profit = savedProfit[_account].add(unsaved);
savedProfit[_account] = profit;
}
/**
* @notice Support function. Relevant to the profit system. It will save state of profit before each
* token transfer (either deposit or withdrawal)
*
* @param from Account sending tokens
* @param to Account receiving tokens
*/
function _beforeTokenTransfer(address from, address to, uint256) internal override {
if (from != address(0)) saveProfit(from);
if (to != address(0)) saveProfit(to);
}
/**
* @notice Virtual Internal function. It handles specific code to actually send the profits.
*
* @param _amount Profit (amount being transferred)
* @param _account Account receiving profits
* @param _fee Fee that is being paid to FEE_RECIPIENT (always less than 8%)
*/
function _transferProfit(uint _amount, address _account, uint _fee) internal virtual;
/**
* @notice Public function returning the number of shares that an account holds per specific staking lot
*
* @param _slotId Staking Lot Id
* @param _account Account
*/
function getStakingLotShares(uint _slotId, address _account) view public returns (uint) {
return stakingLotShares[_slotId][_account];
}
/**
* @notice Returns boolean telling if lot is still in lock up period or not
*
* @param _slotId Staking Lot Id
*/
function isInLockUpPeriod(uint _slotId) view public returns (bool) {
return !((stakingLotUnlockTime[_slotId] <= now) || emergencyUnlockState);
}
/**
* @notice Returns boolean telling if lot is active or not
*
* @param _slotId Staking Lot Id
*/
function isActive(uint _slotId) view public returns (bool) {
return stakingLotActive[_slotId];
}
/**
* @notice Returns list of staking lot owners
*
* @param _slotId Staking Lot Id
*/
function getLotOwners(uint _slotId) view public returns (address[] memory slOwners) {
slOwners = stakingLotOwners[_slotId];
}
/**
* @notice Returns performance fee for this specific owner
*
* @param _account Account's address
*/
function getOwnerPerformanceFee(address _account) view public returns (uint performanceFee) {
performanceFee = ownerPerformanceFee[_account];
}
}
contract HegicPooledStakingETH is HegicPooledStaking {
constructor(IERC20 _token, IHegicStaking _staking) public HegicPooledStaking(_token, _staking, "ETH Staked HEGIC", "sHEGICETH") {
}
function _transferProfit(uint _amount, address _account, uint _fee) internal override{
uint netProfit = _amount.mul(uint(100).sub(_fee)).div(100);
payable(_account).transfer(netProfit);
FEE_RECIPIENT.transfer(_amount.sub(netProfit));
}
function updateProfit() public override {
uint profit = staking.profitOf(address(this));
if(profit > 0) profit = staking.claimProfit();
if(lockedBalance <= 0) FALLBACK_RECIPIENT.transfer(profit);
else totalProfitPerToken = totalProfitPerToken.add(profit.mul(ACCURACY).div(lockedBalance));
}
}
contract HegicPooledStakingWBTC is HegicPooledStaking {
IERC20 public immutable underlying;
constructor(IERC20 _token, IHegicStaking _staking, IERC20 _underlying) public
HegicPooledStaking(_token, _staking, "WBTC Staked HEGIC", "sHEGICWBTC") {
underlying = _underlying;
}
/**
* @notice Support internal function. Calling it will transfer _amount WBTC to _account.
* If FEE > 0, a FEE% commission will be paid to FEE_RECIPIENT
* @param _amount Amount to transfer
* @param _account Account that will receive profit
*/
function _transferProfit(uint _amount, address _account, uint _fee) internal override {
uint netProfit = _amount.mul(uint(100).sub(_fee)).div(100);
underlying.safeTransfer(_account, netProfit);
underlying.safeTransfer(FEE_RECIPIENT, _amount.sub(netProfit));
}
/**
* @notice claims profit from Hegic's Staking Contrats and splits it among all currently staked tokens
*/
function updateProfit() public override {
uint profit = staking.profitOf(address(this));
if(profit > 0){
profit = staking.claimProfit();
if(lockedBalance <= 0) underlying.safeTransfer(FALLBACK_RECIPIENT, profit);
else totalProfitPerToken = totalProfitPerToken.add(profit.mul(ACCURACY).div(lockedBalance));
}
}
}
contract FakeHegicStakingETH is ERC20("Hegic ETH Staking Lot", "hlETH"), IHegicStakingETH {
using SafeMath for uint;
using SafeERC20 for IERC20;
uint public LOT_PRICE = 888_000e18;
IERC20 public token;
uint public totalProfit;
event Claim(address account, uint profit);
constructor(IERC20 _token) public {
totalProfit = 0;
token = _token;
_setupDecimals(0);
}
function sendProfit() external payable override {
totalProfit = totalProfit.add(msg.value);
}
function claimProfit() external override returns (uint _profit) {
_profit = totalProfit;
require(_profit > 0, "Zero profit");
emit Claim(msg.sender, _profit);
_transferProfit(_profit);
totalProfit = totalProfit.sub(_profit);
}
function _transferProfit(uint _profit) internal {
msg.sender.transfer(_profit);
}
function buy(uint _amount) external override {
require(_amount > 0, "Amount is zero");
_mint(msg.sender, _amount);
token.safeTransferFrom(msg.sender, address(this), _amount.mul(LOT_PRICE));
}
function sell(uint _amount) external override {
_burn(msg.sender, _amount);
token.safeTransfer(msg.sender, _amount.mul(LOT_PRICE));
}
function profitOf(address) public view override returns (uint _totalProfit) {
_totalProfit = totalProfit;
}
}
contract FakeHegicStakingWBTC is ERC20("Hegic WBTC Staking Lot", "hlWBTC"), IHegicStakingERC20 {
using SafeMath for uint;
using SafeERC20 for IERC20;
uint public totalProfit;
IERC20 public immutable WBTC;
IERC20 public token;
uint public LOT_PRICE = 888_000e18;
event Claim(address account, uint profit);
constructor(IERC20 _wbtc, IERC20 _token) public {
WBTC = _wbtc;
token = _token;
totalProfit = 0;
_setupDecimals(0);
}
function sendProfit(uint _amount) external override {
WBTC.safeTransferFrom(msg.sender, address(this), _amount);
totalProfit = totalProfit.add(_amount);
}
function claimProfit() external override returns (uint _profit) {
_profit = totalProfit;
require(_profit > 0, "Zero profit");
emit Claim(msg.sender, _profit);
_transferProfit(_profit);
totalProfit = totalProfit.sub(_profit);
}
function _transferProfit(uint _profit) internal {
WBTC.safeTransfer(msg.sender, _profit);
}
function buy(uint _amount) external override {
require(_amount > 0, "Amount is zero");
_mint(msg.sender, _amount);
token.safeTransferFrom(msg.sender, address(this), _amount.mul(LOT_PRICE));
}
function sell(uint _amount) external override {
_burn(msg.sender, _amount);
token.safeTransfer(msg.sender, _amount.mul(LOT_PRICE));
}
function profitOf(address) public view override returns (uint _totalProfit) {
_totalProfit = totalProfit;
}
}
contract FakeWBTC is ERC20("FakeWBTC", "FAKE") {
constructor() public {
_setupDecimals(8);
}
function mintTo(address account, uint256 amount) public {
_mint(account, amount);
}
function mint(uint256 amount) public {
_mint(msg.sender, amount);
}
}
contract FakeHEGIC is ERC20("FakeHEGIC", "FAKEH") {
using SafeERC20 for ERC20;
function mintTo(address account, uint256 amount) public {
_mint(account, amount);
}
function mint(uint256 amount) public {
_mint(msg.sender, amount);
}
}
| * @notice EXTERNAL function. Calling this function will result in receiving profits accumulated during the time the HEGIC were deposited/ | function updateProfit() public virtual;
function claimProfit() external {
uint profit = saveProfit(msg.sender);
savedProfit[msg.sender] = 0;
_transferProfit(profit, msg.sender, ownerPerformanceFee[msg.sender]);
emit PayProfit(msg.sender, profit, ownerPerformanceFee[msg.sender]);
}
| 7,455,298 | [
1,
2294,
11702,
445,
18,
21020,
333,
445,
903,
563,
316,
15847,
9214,
1282,
24893,
4982,
326,
813,
326,
4194,
43,
2871,
4591,
443,
1724,
329,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1089,
626,
7216,
1435,
1071,
5024,
31,
203,
203,
203,
203,
203,
203,
203,
203,
203,
565,
445,
7516,
626,
7216,
1435,
3903,
288,
203,
203,
3639,
2254,
450,
7216,
273,
1923,
626,
7216,
12,
3576,
18,
15330,
1769,
203,
203,
3639,
5198,
626,
7216,
63,
3576,
18,
15330,
65,
273,
374,
31,
203,
203,
3639,
389,
13866,
626,
7216,
12,
685,
7216,
16,
1234,
18,
15330,
16,
3410,
25024,
14667,
63,
3576,
18,
15330,
19226,
203,
203,
3639,
3626,
13838,
626,
7216,
12,
3576,
18,
15330,
16,
450,
7216,
16,
3410,
25024,
14667,
63,
3576,
18,
15330,
19226,
203,
203,
565,
289,
203,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x2fC246149B4B8d7bcEF6188A10AF1791380227f1/sources/src/BaseWithStorage/wip/ERC20BaseToken.sol | save gas when allowance is maximal by not reducing it (see https:github.com/ethereum/EIPs/issues/717) | function _burn(address from, uint256 amount) internal {
require(amount > 0, "cannot burn 0 tokens");
if (msg.sender != from && !_superOperators[msg.sender]) {
uint256 currentAllowance = _allowances[from][msg.sender];
require(currentAllowance >= amount, "Not enough funds allowed");
if (currentAllowance != ~uint256(0)) {
_allowances[from][msg.sender] = currentAllowance - amount;
}
}
uint256 currentBalance = _balances[from];
require(currentBalance >= amount, "Not enough funds");
_balances[from] = currentBalance - amount;
_totalSupply -= amount;
emit Transfer(from, address(0), amount);
}
| 8,434,607 | [
1,
5688,
16189,
1347,
1699,
1359,
353,
943,
2840,
635,
486,
9299,
2822,
518,
261,
5946,
2333,
30,
6662,
18,
832,
19,
546,
822,
379,
19,
41,
18246,
19,
9618,
19,
27,
4033,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
70,
321,
12,
2867,
628,
16,
2254,
5034,
3844,
13,
2713,
288,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
12892,
18305,
374,
2430,
8863,
203,
3639,
309,
261,
3576,
18,
15330,
480,
628,
597,
401,
67,
9565,
24473,
63,
3576,
18,
15330,
5717,
288,
203,
5411,
2254,
5034,
783,
7009,
1359,
273,
389,
5965,
6872,
63,
2080,
6362,
3576,
18,
15330,
15533,
203,
5411,
2583,
12,
2972,
7009,
1359,
1545,
3844,
16,
315,
1248,
7304,
284,
19156,
2935,
8863,
203,
5411,
309,
261,
2972,
7009,
1359,
480,
4871,
11890,
5034,
12,
20,
3719,
288,
203,
7734,
389,
5965,
6872,
63,
2080,
6362,
3576,
18,
15330,
65,
273,
783,
7009,
1359,
300,
3844,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
783,
13937,
273,
389,
70,
26488,
63,
2080,
15533,
203,
3639,
2583,
12,
2972,
13937,
1545,
3844,
16,
315,
1248,
7304,
284,
19156,
8863,
203,
3639,
389,
70,
26488,
63,
2080,
65,
273,
783,
13937,
300,
3844,
31,
203,
3639,
389,
4963,
3088,
1283,
3947,
3844,
31,
203,
3639,
3626,
12279,
12,
2080,
16,
1758,
12,
20,
3631,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x00000000000006c7676171937C444f6BDe3D6282/sources/contracts/lib/ConsiderationErrors.sol | * @dev Reverts the current transaction with an "InsufficientNativeTokensSupplied" error message./ | function _revertInsufficientNativeTokensSupplied() pure {
assembly {
mstore(0, InsufficientNativeTokensSupplied_error_selector)
revert(
Error_selector_offset,
InsufficientNativeTokensSupplied_error_length
)
}
}
| 4,301,423 | [
1,
426,
31537,
326,
783,
2492,
598,
392,
1377,
315,
5048,
11339,
9220,
5157,
3088,
3110,
6,
555,
883,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
915,
389,
266,
1097,
5048,
11339,
9220,
5157,
3088,
3110,
1435,
16618,
288,
203,
565,
19931,
288,
203,
3639,
312,
2233,
12,
20,
16,
22085,
11339,
9220,
5157,
3088,
3110,
67,
1636,
67,
9663,
13,
203,
203,
3639,
15226,
12,
203,
5411,
1068,
67,
9663,
67,
3348,
16,
203,
5411,
22085,
11339,
9220,
5157,
3088,
3110,
67,
1636,
67,
2469,
203,
3639,
262,
203,
565,
289,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/4/0xfEd5b158E8E9EC593c6D0aAba63bFf3f825A3711/sources/contracts/TheSouthPark.sol | Whitelist OpenSea proxy contract for easy trading.ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);if (address(proxyRegistry.proxies(account)) == operator) { return true;} | {
return super.isApprovedForAll(account, operator);
public
}*/
| 750,843 | [
1,
18927,
3502,
1761,
69,
2889,
6835,
364,
12779,
1284,
7459,
18,
3886,
4243,
2889,
4243,
273,
7659,
4243,
12,
5656,
4243,
1887,
1769,
430,
261,
2867,
12,
5656,
4243,
18,
20314,
606,
12,
4631,
3719,
422,
3726,
13,
288,
225,
327,
638,
31,
97,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
288,
203,
3639,
327,
2240,
18,
291,
31639,
1290,
1595,
12,
4631,
16,
3726,
1769,
203,
3639,
1071,
203,
565,
289,
5549,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-03-04
*/
// File: node_modules\@openzeppelin\contracts\token\ERC20\IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: node_modules\@openzeppelin\contracts\math\SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: node_modules\@openzeppelin\contracts\utils\Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin\contracts\token\ERC20\SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: node_modules\@openzeppelin\contracts\GSN\Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: node_modules\@openzeppelin\contracts\token\ERC20\ERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File: @openzeppelin\contracts\token\ERC20\ERC20Burnable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
using SafeMath for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// File: contracts\ENERGY.sol
pragma solidity 0.7.6;
contract ENERGY is ERC20Burnable {
using SafeMath for uint256;
uint256 public constant initialSupply = 89099136 * 10 ** 3;
uint256 public lastWeekTime;
uint256 public weekCount;
//staking start when week count set to 1 -> rewards calculated before just updating week
uint256 public constant totalWeeks = 100;
address public stakingContrAddr;
address public liquidityContrAddr;
uint256 public constant timeStep = 1 weeks;
modifier onlyStaking() {
require(_msgSender() == stakingContrAddr, "Not staking contract");
_;
}
constructor (address _liquidityContrAddr) ERC20("ENERGY", "NRGY") {
//89099.136 coins
_setupDecimals(6);
lastWeekTime = block.timestamp;
liquidityContrAddr = _liquidityContrAddr;
_mint(_msgSender(), initialSupply.mul(4).div(10)); //40%
_mint(liquidityContrAddr, initialSupply.mul(6).div(10)); //60%
}
function mintNewCoins(uint256[3] memory lastWeekRewards) public onlyStaking returns(bool) {
if(weekCount >= 1) {
uint256 newMint = lastWeekRewards[0].add(lastWeekRewards[1]).add(lastWeekRewards[2]);
uint256 liquidityMint = (newMint.mul(20)).div(100);
_mint(liquidityContrAddr, liquidityMint);
_mint(stakingContrAddr, newMint);
} else {
_mint(liquidityContrAddr, initialSupply);
}
return true;
}
//updates only at end of week
function updateWeek() public onlyStaking {
weekCount++;
lastWeekTime = block.timestamp;
}
function updateStakingContract(address _stakingContrAddr) public {
require(stakingContrAddr == address(0), "Staking contract is already set");
stakingContrAddr = _stakingContrAddr;
}
function burnOnUnstake(address account, uint256 amount) public onlyStaking {
_burn(account, amount);
}
function getLastWeekUpdateTime() public view returns(uint256) {
return lastWeekTime;
}
function isMintingCompleted() public view returns(bool) {
if(weekCount > totalWeeks) {
return true;
} else {
return false;
}
}
function isGreaterThanAWeek() public view returns(bool) {
if(block.timestamp > getLastWeekUpdateTime().add(timeStep)) {
return true;
} else {
return false;
}
}
}
// File: contracts\NRGYMarketMaker.sol
pragma solidity 0.7.6;
contract NRGYMarketMaker {
using SafeERC20 for IERC20;
using SafeMath for uint256;
struct UserData {
address user;
bool isActive;
uint256 rewards;
uint256 feeRewards;
uint256 depositTime;
uint256 share;
//update when user came first time or after unstaking to stake
uint256 startedWeek;
//update everytime whenever user comes to unstake
uint256 endedWeek;
mapping(uint256 => uint256) shareByWeekNo;
}
struct FeeRewardData {
uint256 value;
uint256 timeStamp;
uint256 totalStakersAtThatTime;
uint256 weekGiven;
mapping(address => bool) isClaimed;
}
ENERGY public energy;
IERC20 public lpToken;
uint256 public totalShares;
//initially it will be 27000
uint256[] public stakingLimit;
uint256 public constant minStakeForFeeRewards = 25 * 10 ** 6;
uint256 public totalRewards;
uint256 public totalFeeRewards;
uint256 public rewardsAvailableInContract;
uint256 public feeRewardsAvailableInContract;
uint256 public feeRewardsCount;
uint256 public totalStakeUsers;
uint256 public constant percentageDivider = 100;
//10%, 30%, 60%
uint256[3] private rewardPercentages = [10, 30, 60];
//7.5%
uint256 public constant unstakeFees = 75;
//total weeks
uint256 public totalWeeks;
//user informations
mapping(uint256 => address) public userList;
mapping(address => UserData) public userInfo;
mapping (address => bool) public smartContractStakers;
//contract info
mapping(uint256 => uint256) private stakePerWeek;
mapping(uint256 => uint256) private totalSharesByWeek;
mapping(uint256 => uint256[3]) private rewardByWeek;
mapping(uint256 => FeeRewardData) private feeRewardData;
event Staked(address indexed _user, uint256 _amountStaked, uint256 _balanceOf);
event Withdrawn(address indexed _user,
uint256 _amountTransferred,
uint256 _amountUnstaked,
uint256 _shareDeducted,
uint256 _rewardsDeducted,
uint256 _feeRewardsDeducted);
event RewardDistributed(uint256 _weekNo, uint256[3] _lastWeekRewards);
event FeeRewardDistributed(uint256 _amount, uint256 _totalFeeRewards);
constructor(address _energy) {
energy = ENERGY(_energy);
lpToken = IERC20(_energy);
totalWeeks = energy.totalWeeks();
stakingLimit.push(27000 * 10 ** 6);
}
// stake the coins
function stake(uint256 amount) public {
_stake(amount, tx.origin);
}
function stakeOnBehalf(uint256 amount, address _who) public {
_stake(amount, _who);
}
function _stake(uint256 _amount, address _who) internal {
uint256 _weekCount = energy.weekCount();
bool isWeekOver = energy.isGreaterThanAWeek();
if((_weekCount >= 1 && !isWeekOver) || _weekCount == 0) {
require(!isStakingLimitReached(_amount, _weekCount), "Stake limit has been reached");
}
//if week over or week is 0
if(!isWeekOver || _weekCount == 0) {
//add current week stake
stakePerWeek[_weekCount] = getStakeByWeekNo(_weekCount).add(_amount);
// update current week cumulative stake
//store total shares by week no at time of stake
totalSharesByWeek[_weekCount] = totalShares.add(_amount);
userInfo[_who].shareByWeekNo[_weekCount] = getUserShareByWeekNo(_who, _weekCount).add(_amount);
//if current week share is 0 get share for previous week
if(_weekCount == 0) {
if(stakingLimit[0] == totalShares.add(_amount)) {
setStakingLimit(_weekCount, stakingLimit[0]);
energy.mintNewCoins(getRewardsByWeekNo(0));
energy.updateWeek();
}
}
} else/*is week is greater than 1 and is over */ {
//update this week shae by adding previous week share
userInfo[_who].shareByWeekNo[_weekCount.add(1)] = getUserShareByWeekNo(_who, _weekCount).add(_amount);
//update next week stake
stakePerWeek[_weekCount.add(1)] = getStakeByWeekNo(_weekCount.add(1)).add(_amount);
//update next week cumulative stake
//store total shares of next week no at time of stake
totalSharesByWeek[_weekCount.add(1)] = totalShares.add(_amount);
setStakingLimit(_weekCount, totalShares);
energy.updateWeek();
//if week over update followings and greater than 1
/*give rewards only after week end and till 3 more weeks of total weeks */
if(_weekCount <= totalWeeks.add(3)) {
//store rewards generated that week by week no at end of week
//eg: when week 1 is over, it will store rewards generated that week before week changed from 1 to 2
setRewards(_weekCount);
uint256 rewardDistributed = (rewardByWeek[_weekCount][0])
.add(rewardByWeek[_weekCount][1])
.add(rewardByWeek[_weekCount][2]);
totalRewards = totalRewards.add(rewardDistributed);
energy.mintNewCoins(getRewardsByWeekNo(_weekCount));
rewardsAvailableInContract = rewardsAvailableInContract.add(rewardDistributed);
emit RewardDistributed(_weekCount, getRewardsByWeekNo(_weekCount));
}
}
//if user not active, set current week as his start week
if(!getUserStatus(_who)) {
userInfo[_who].isActive = true;
if(getUserShare(_who) < minStakeForFeeRewards) {
userInfo[_who].startedWeek = _weekCount;
userInfo[_who].depositTime = block.timestamp;
}
}
if(!isUserPreviouslyStaked(_who)) {
userList[totalStakeUsers] = _who;
totalStakeUsers++;
smartContractStakers[_who] = true;
userInfo[_who].user = _who;
}
userInfo[_who].share = userInfo[_who].share.add(_amount);
//update total shares in the end
totalShares = totalShares.add(_amount);
//if-> user is directly staking
if(msg.sender == tx.origin) {
// now we can issue shares
lpToken.safeTransferFrom(_who, address(this), _amount);
} else /*through liquity contract */ {
// now we can issue shares
//transfer from liquidty contract
lpToken.safeTransferFrom(msg.sender, address(this), _amount);
}
emit Staked(_who, _amount, claimedBalanceOf(_who));
}
function setStakingLimit(uint256 _weekCount, uint256 _share) internal {
uint256 lastWeekStakingLeft = stakingLimit[_weekCount].sub(getStakeByWeekNo(_weekCount));
// first 4 weeks are: 0,1,2,3
if(_weekCount <= 3) {
//32%
stakingLimit.push((_share.mul(32)).div(percentageDivider));
}
if(_weekCount > 3) {
//0.04%
stakingLimit.push((_share.mul(4)).div(percentageDivider));
}
stakingLimit[_weekCount.add(1)] = stakingLimit[_weekCount.add(1)].add(lastWeekStakingLeft);
}
function setRewards(uint256 _weekCount) internal {
(rewardByWeek[_weekCount][0],
rewardByWeek[_weekCount][1],
rewardByWeek[_weekCount][2]) = calculateRewardsByWeekCount(_weekCount);
}
function calculateRewards() public view returns(uint256 _lastWeekReward, uint256 _secondLastWeekReward, uint256 _thirdLastWeekReward) {
return calculateRewardsByWeekCount(energy.weekCount());
}
function calculateRewardsByWeekCount(uint256 _weekCount) public view returns(uint256 _lastWeekReward, uint256 _secondLastWeekReward, uint256 _thirdLastWeekReward) {
bool isLastWeek = (_weekCount >= totalWeeks);
if(isLastWeek) {
if(_weekCount.sub(totalWeeks) == 0) {
_lastWeekReward = (getStakeByWeekNo(_weekCount).mul(rewardPercentages[0])).div(percentageDivider);
_secondLastWeekReward = (getStakeByWeekNo(_weekCount.sub(1)).mul(rewardPercentages[1])).div(percentageDivider);
_thirdLastWeekReward = (getStakeByWeekNo(_weekCount.sub(2)).mul(rewardPercentages[2])).div(percentageDivider);
} else if(_weekCount.sub(totalWeeks) == 1) {
_secondLastWeekReward = (getStakeByWeekNo(_weekCount.sub(1)).mul(rewardPercentages[1])).div(percentageDivider);
_thirdLastWeekReward = (getStakeByWeekNo(_weekCount.sub(2)).mul(rewardPercentages[2])).div(percentageDivider);
} else if(_weekCount.sub(totalWeeks) == 2) {
_thirdLastWeekReward = (getStakeByWeekNo(_weekCount.sub(2)).mul(rewardPercentages[2])).div(percentageDivider);
}
} else {
if(_weekCount == 1) {
_lastWeekReward = (getStakeByWeekNo(_weekCount).mul(rewardPercentages[0])).div(percentageDivider);
} else if(_weekCount == 2) {
_lastWeekReward = (getStakeByWeekNo(_weekCount).mul(rewardPercentages[0])).div(percentageDivider);
_secondLastWeekReward = (getStakeByWeekNo(_weekCount.sub(1)).mul(rewardPercentages[1])).div(percentageDivider);
} else if(_weekCount >= 3) {
_lastWeekReward = (getStakeByWeekNo(_weekCount).mul(rewardPercentages[0])).div(percentageDivider);
_secondLastWeekReward = (getStakeByWeekNo(_weekCount.sub(1)).mul(rewardPercentages[1])).div(percentageDivider);
_thirdLastWeekReward = (getStakeByWeekNo(_weekCount.sub(2)).mul(rewardPercentages[2])).div(percentageDivider);
}
}
}
function isStakingLimitReached(uint256 _amount, uint256 _weekCount) public view returns(bool) {
return (getStakeByWeekNo(_weekCount).add(_amount) > stakingLimit[_weekCount]);
}
function remainingStakingLimit(uint256 _weekCount) public view returns(uint256) {
return (stakingLimit[_weekCount].sub(getStakeByWeekNo(_weekCount)));
}
function distributeFees(uint256 _amount) public {
uint256 _weekCount = energy.weekCount();
FeeRewardData storage _feeRewardData = feeRewardData[feeRewardsCount];
_feeRewardData.value = _amount;
_feeRewardData.timeStamp = block.timestamp;
_feeRewardData.totalStakersAtThatTime = totalStakeUsers;
_feeRewardData.weekGiven = _weekCount;
feeRewardsCount++;
totalFeeRewards = totalFeeRewards.add(_amount);
feeRewardsAvailableInContract = feeRewardsAvailableInContract.add(_amount);
lpToken.safeTransferFrom(msg.sender, address(this), _amount);
emit FeeRewardDistributed(_amount, totalFeeRewards);
}
///unstake the coins
function unstake(uint256 _amount) public {
UserData storage _user = userInfo[msg.sender];
uint256 _weekCount = energy.weekCount();
//get user rewards till date(week) and add to claimed rewards
userInfo[msg.sender].rewards = _user.rewards
.add(getUserRewardsByWeekNo(msg.sender, _weekCount));
//get user fee rewards till date(week) and add to claimed fee rewards
userInfo[msg.sender].feeRewards = _user.feeRewards.add(_calculateFeeRewards(msg.sender));
require(_amount <= claimedBalanceOf(msg.sender), "Unstake amount is greater than user balance");
//calculate unstake fee
uint256 _fees = (_amount.mul(unstakeFees)).div(1000);
//calulcate amount to transfer to user
uint256 _toTransfer = _amount.sub(_fees);
//burn unstake fees
energy.burnOnUnstake(address(this), _fees);
lpToken.safeTransfer(msg.sender, _toTransfer);
//if amount can be paid from rewards
if(_amount <= getUserTotalRewards(msg.sender)) {
//if amount can be paid from rewards
if(_user.rewards >= _amount) {
_user.rewards = _user.rewards.sub(_amount);
rewardsAvailableInContract = rewardsAvailableInContract.sub(_amount);
emit Withdrawn(msg.sender, _toTransfer, _amount, 0, _amount, 0);
} else/*else take sum of fee rewards and rewards */ {
//get remaining amount less than rewards
uint256 remAmount = _amount.sub(_user.rewards);
rewardsAvailableInContract = rewardsAvailableInContract.sub(_user.rewards);
feeRewardsAvailableInContract = feeRewardsAvailableInContract.sub(remAmount);
emit Withdrawn(msg.sender, _toTransfer, _amount, 0, _user.rewards, remAmount);
//update fee rewards from remaining amount
_user.rewards = 0;
_user.feeRewards = _user.feeRewards.sub(remAmount);
}
} else/* take from total shares*/ {
//get remaining amount less than rewards
uint256 remAmount = _amount.sub(getUserTotalRewards(msg.sender));
rewardsAvailableInContract = rewardsAvailableInContract.sub(_user.rewards);
feeRewardsAvailableInContract = feeRewardsAvailableInContract.sub(_user.feeRewards);
emit Withdrawn(msg.sender, _toTransfer, _amount, remAmount, _user.rewards, _user.feeRewards);
_user.rewards = 0;
_user.feeRewards = 0;
//update user share from remaining amount
_user.share = _user.share.sub(remAmount);
//update total shares
totalShares = totalShares.sub(remAmount);
//update total shares by week no at time of unstake
totalSharesByWeek[_weekCount] = totalSharesByWeek[_weekCount].sub(remAmount);
}
lpToken.safeApprove(address(this), 0);
//set user status to false
_user.isActive = false;
//update user end(unstake) week
_user.endedWeek = _weekCount == 0 ? _weekCount : _weekCount.sub(1);
}
function _calculateFeeRewards(address _who) internal returns(uint256) {
uint256 _accumulatedRewards;
//check if user have minimum share too claim fee rewards
if(getUserShare(_who) >= minStakeForFeeRewards) {
//loop through all the rewards
for(uint256 i = 0; i < feeRewardsCount; i++) {
//if rewards week and timestamp is greater than user deposit time and rewards.
//Also only if user has not claimed particular fee rewards
if(getUserStartedWeek(_who) <= feeRewardData[i].weekGiven
&& getUserLastDepositTime(_who) < feeRewardData[i].timeStamp
&& !feeRewardData[i].isClaimed[_who]) {
_accumulatedRewards = _accumulatedRewards.add(feeRewardData[i].value.div(feeRewardData[i].totalStakersAtThatTime));
feeRewardData[i].isClaimed[_who] = true;
}
}
}
return _accumulatedRewards;
}
/*
* ------------------Getter inteface for user---------------------
*
*/
function getUserUnclaimedFeesRewards(address _who) public view returns(uint256) {
uint256 _accumulatedRewards;
//check if user have minimum share too claim fee rewards
if(getUserShare(_who) >= minStakeForFeeRewards) {
//loop through all the rewards
for(uint256 i = 0; i < feeRewardsCount; i++) {
//if rewards week and timestamp is greater than user deposit time and rewards.
//Also only if user has not claimed particular fee rewards
if(getUserStartedWeek(_who) <= feeRewardData[i].weekGiven
&& getUserLastDepositTime(_who) < feeRewardData[i].timeStamp
&& !feeRewardData[i].isClaimed[_who]) {
_accumulatedRewards = _accumulatedRewards.add(feeRewardData[i].value.div(feeRewardData[i].totalStakersAtThatTime));
}
}
}
return _accumulatedRewards;
}
//return rewards till weekcount passed
function getUserCurrentRewards(address _who) public view returns(uint256) {
uint256 _weekCount = energy.weekCount();
uint256[3] memory thisWeekReward;
(thisWeekReward[0],
thisWeekReward[1],
thisWeekReward[2]) = calculateRewardsByWeekCount(_weekCount);
uint256 userShareAtThatWeek = getUserPercentageShareByWeekNo(_who, _weekCount);
return getUserRewardsByWeekNo(_who, _weekCount)
.add(_calculateRewardByUserShare(thisWeekReward, userShareAtThatWeek))
.add(getUserRewards(_who));
}
//return rewards till one week less than the weekcount passed
//calculate rewards till previous week and deduct rewards claimed at time of unstake
//return rewards available to claim
function getUserRewardsByWeekNo(address _who, uint256 _weekCount) public view returns(uint256) {
uint256 rewardsAccumulated;
uint256 userEndWeek = getUserEndedWeek(_who);
//clculate rewards only if user is active or user share is greater than 1
if(getUserStatus(_who) || (getUserShare(_who) > 0)) {
for(uint256 i = userEndWeek.add(1); i < _weekCount; i++) {
uint256 userShareAtThatWeek = getUserPercentageShareByWeekNo(_who, i);
rewardsAccumulated = rewardsAccumulated.add(_calculateRewardByUserShare(getRewardsByWeekNo(i), userShareAtThatWeek));
}
}
return rewardsAccumulated;
}
function _calculateRewardByUserShare(uint256[3] memory rewardAtThatWeek, uint256 userShareAtThatWeek) internal pure returns(uint256) {
return (((rewardAtThatWeek[0]
.add(rewardAtThatWeek[1])
.add(rewardAtThatWeek[2]))
.mul(userShareAtThatWeek))
.div(percentageDivider.mul(percentageDivider)));
}
function getUserPercentageShareByWeekNo(address _who, uint256 _weekCount) public view returns(uint256) {
return _getUserPercentageShareByValue(getSharesByWeekNo(_weekCount), getUserShareByWeekNo(_who, _weekCount));
}
function _getUserPercentageShareByValue(uint256 _totalShares, uint256 _userShare) internal pure returns(uint256) {
if(_totalShares == 0 || _userShare == 0) {
return 0;
} else {
//two times percentageDivider multiplied because of decimal percentage which are less than 1
return (_userShare.mul(percentageDivider.mul(percentageDivider))).div(_totalShares);
}
}
//give sum of share(staked amount) + rewards is user have a claimed it through unstaking
function claimedBalanceOf(address _who) public view returns(uint256) {
return getUserShare(_who).add(getUserRewards(_who)).add(getUserFeeRewards(_who));
}
function getUserRewards(address _who) public view returns(uint256) {
return userInfo[_who].rewards;
}
function getUserFeeRewards(address _who) public view returns(uint256) {
return userInfo[_who].feeRewards;
}
function getUserTotalRewards(address _who) public view returns(uint256) {
return userInfo[_who].feeRewards.add(userInfo[_who].rewards);
}
function getUserShare(address _who) public view returns(uint256) {
return userInfo[_who].share;
}
function getUserShareByWeekNo(address _who, uint256 _weekCount) public view returns(uint256) {
if(getUserStatus(_who)) {
return (_userShareByWeekNo(_who, _weekCount) > 0 || _weekCount == 0)
? _userShareByWeekNo(_who, _weekCount)
: getUserShareByWeekNo(_who, _weekCount.sub(1));
} else if(getUserShare(_who) > 0) {
return getUserShare(_who);
}
return 0;
}
function _userShareByWeekNo(address _who, uint256 _weekCount) internal view returns(uint256) {
return userInfo[_who].shareByWeekNo[_weekCount];
}
function getUserStatus(address _who) public view returns(bool) {
return userInfo[_who].isActive;
}
function getUserStartedWeek(address _who) public view returns(uint256) {
return userInfo[_who].startedWeek;
}
function getUserEndedWeek(address _who) public view returns(uint256) {
return userInfo[_who].endedWeek;
}
function getUserLastDepositTime(address _who) public view returns(uint256) {
return userInfo[_who].depositTime;
}
function isUserPreviouslyStaked(address _who) public view returns(bool) {
return smartContractStakers[_who];
}
function getUserFeeRewardClaimStatus(address _who, uint256 _index) public view returns(bool) {
return feeRewardData[_index].isClaimed[_who];
}
/*
* ------------------Getter inteface for contract---------------------
*
*/
function getRewardsByWeekNo(uint256 _weekCount) public view returns(uint256[3] memory) {
return rewardByWeek[_weekCount];
}
function getFeeRewardsByIndex(uint256 _index) public view returns(uint256, uint256, uint256, uint256) {
return (feeRewardData[_index].value,
feeRewardData[_index].timeStamp,
feeRewardData[_index].totalStakersAtThatTime,
feeRewardData[_index].weekGiven);
}
function getRewardPercentages() public view returns(uint256[3] memory) {
return rewardPercentages;
}
function getStakeByWeekNo(uint256 _weekCount) public view returns(uint256) {
return stakePerWeek[_weekCount];
}
function getSharesByWeekNo(uint256 _weekCount) public view returns(uint256) {
return totalSharesByWeek[_weekCount];
}
} | set user status to false | _user.isActive = false;
| 2,067,784 | [
1,
542,
729,
1267,
358,
629,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
389,
1355,
18,
291,
3896,
273,
629,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.4;
import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
import './interfaces/IVaultFactory.sol';
import './Vault.sol';
contract VaultFactory is IVaultFactory, Moderable, ReentrancyGuard {
address[] public vaults;
mapping(address => bool) public vaultExists;
mapping(address => address) public tokenToVault;
address public flashLoanProviderAddress;
bool public isInitialized = false;
ERC20 public tokenToPayInFee;
uint256 public feeToPublishVault;
address public treasuryAddress = 0xA49174859aA91E139b586F08BbB69BceE847d8a7;
/**
* @dev Only if Vault Factory is not initialized.
**/
modifier onlyNotInitialized {
require(isInitialized == false, 'ONLY_NOT_INITIALIZED');
_;
}
/**
* @dev Only if Vault Factory is initialized.
**/
modifier onlyInitialized {
require(isInitialized, 'ONLY_INITIALIZED');
_;
}
/**
* @dev Change treasury address.
* @param _treasuryAddress address of treasury where part of flash loan fee is sent.
*/
function setTreasuryAddress(address _treasuryAddress) external onlyModerator {
treasuryAddress = _treasuryAddress;
emit VaultFactorySetTreasuryAddress(treasuryAddress);
}
/**
* @dev Initialize VaultFactory
* @param _flashLoanProviderAddress contract to use for getting Flash Loan.
* @param _tokenToPayInFee address of token used for paying fee of listing Vault.
*/
function initialize(address _flashLoanProviderAddress, address _tokenToPayInFee)
external
onlyModerator
onlyNotInitialized
{
tokenToPayInFee = ERC20(_tokenToPayInFee);
feeToPublishVault = 100000 * 10**tokenToPayInFee.decimals();
flashLoanProviderAddress = _flashLoanProviderAddress;
isInitialized = true;
}
/**
* @dev Set/Change fee for publishing your Vault.
* @param _feeToPublishVault amount set to be paid when creating a Vault.
*/
function setFeeToPublishVault(uint256 _feeToPublishVault) external onlyModerator {
feeToPublishVault = _feeToPublishVault;
emit VaultFactorySetFeeToPublishVault(feeToPublishVault);
}
/**
* @dev Create vault factory method.
* @param stakedToken address of staked token in a vault
* @param maxCapacity value for Vault.
*/
function createVault(address stakedToken, uint256 maxCapacity)
external
onlyModerator
onlyInitialized
{
_createVault(stakedToken, maxCapacity);
}
/**
* @dev Overloaded createVault method used for externally be called by anyone that pays fee.
* @param stakedToken used as currency for depositing into Vault.
**/
function createVault(address stakedToken) external onlyInitialized nonReentrant {
IERC20 token = IERC20(stakedToken);
require(
tokenToPayInFee.transferFrom(msg.sender, address(this), feeToPublishVault),
'FEE_TRANSFER_FAILED'
);
require(token.totalSupply() > 0, 'TOTAL_SUPPLY_LESS_THAN_ZERO');
_createVault(stakedToken, token.totalSupply() / 2);
}
/**
* @dev Create vault internal factory method.
* @param stakedToken address of staked token in a vault
* @param maxCapacity value for Vault.
*/
function _createVault(address stakedToken, uint256 maxCapacity) internal {
require(tokenToVault[stakedToken] == address(0), 'VAULT_ALREADY_EXISTS');
bytes32 salt = keccak256(abi.encodePacked(stakedToken));
Vault vault = new Vault{salt: salt}(ERC20(stakedToken));
vaults.push(address(vault));
vaultExists[address(vault)] = true;
tokenToVault[stakedToken] = address(vault);
vault.initialize(treasuryAddress, flashLoanProviderAddress, maxCapacity);
vault.transferModeratorship(moderator()); //Moderator of VaultFactory is moderator of Vault. Otherwise moderator would be the VaultFactory
emit VaultCreated(address(vault));
}
/**
* @dev Withdraw funds payed as tax for Vault listing.
**/
function withdraw() external onlyModerator {
require(
tokenToPayInFee.transfer(msg.sender, tokenToPayInFee.balanceOf(address(this))),
'WITHDRAW_TRANSFER_ERROR'
);
}
/**
* @dev Count how many vaults have been created so far.
* @return Number of vaults created.
*/
function countVaults() external view returns (uint256) {
return vaults.length;
}
/**
* @dev Precompute address of vault.
* @param stakedToken address for a specific vault liquidity token.
* @return Address a vault will have.
*/
function precomputeAddress(address stakedToken) external view returns (address) {
bytes32 salt = keccak256(abi.encodePacked(stakedToken));
return
address(
uint160(
uint256(
keccak256(
abi.encodePacked(
bytes1(0xff),
address(this),
salt,
keccak256(
abi.encodePacked(
type(Vault).creationCode,
abi.encode(ERC20(stakedToken))
)
)
)
)
)
)
);
}
}
| * @dev Create vault internal factory method. @param stakedToken address of staked token in a vault @param maxCapacity value for Vault./ | function _createVault(address stakedToken, uint256 maxCapacity) internal {
require(tokenToVault[stakedToken] == address(0), 'VAULT_ALREADY_EXISTS');
bytes32 salt = keccak256(abi.encodePacked(stakedToken));
vaults.push(address(vault));
vaultExists[address(vault)] = true;
tokenToVault[stakedToken] = address(vault);
vault.initialize(treasuryAddress, flashLoanProviderAddress, maxCapacity);
emit VaultCreated(address(vault));
}
| 1,018,017 | [
1,
1684,
9229,
2713,
3272,
707,
18,
225,
384,
9477,
1345,
1758,
434,
384,
9477,
1147,
316,
279,
9229,
225,
943,
7437,
460,
364,
17329,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
2640,
12003,
12,
2867,
384,
9477,
1345,
16,
2254,
5034,
943,
7437,
13,
2713,
288,
203,
3639,
2583,
12,
2316,
774,
12003,
63,
334,
9477,
1345,
65,
422,
1758,
12,
20,
3631,
296,
27722,
2274,
67,
1013,
20305,
67,
21205,
8284,
203,
3639,
1731,
1578,
4286,
273,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
334,
9477,
1345,
10019,
203,
203,
203,
3639,
9229,
87,
18,
6206,
12,
2867,
12,
26983,
10019,
203,
3639,
9229,
4002,
63,
2867,
12,
26983,
25887,
273,
638,
31,
203,
3639,
1147,
774,
12003,
63,
334,
9477,
1345,
65,
273,
1758,
12,
26983,
1769,
203,
203,
3639,
9229,
18,
11160,
12,
27427,
345,
22498,
1887,
16,
9563,
1504,
304,
2249,
1887,
16,
943,
7437,
1769,
203,
203,
203,
3639,
3626,
17329,
6119,
12,
2867,
12,
26983,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// Sources flattened with hardhat v2.1.2 https://hardhat.org
// File @animoca/ethereum-contracts-erc20_base-4.0.0/contracts/token/ERC20/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.6.8;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `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);
}
// File @animoca/ethereum-contracts-core_library-5.0.0/contracts/algo/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity 0.6.8;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumMap for EnumMap.Map;
*
* // Declare a set state variable
* EnumMap.Map private myMap;
* }
* ```
*/
library EnumMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// This means that we can only create new EnumMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 key;
bytes32 value;
}
struct Map {
// Storage of map keys and values
MapEntry[] entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping(bytes32 => uint256) indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
Map storage map,
bytes32 key,
bytes32 value
) internal returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map.indexes[key];
if (keyIndex == 0) {
// Equivalent to !contains(map, key)
map.entries.push(MapEntry({key: key, value: value}));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map.indexes[key] = map.entries.length;
return true;
} else {
map.entries[keyIndex - 1].value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(Map storage map, bytes32 key) internal returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map.indexes[key];
if (keyIndex != 0) {
// Equivalent to contains(map, key)
// To delete a key-value pair from the entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map.entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map.entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map.entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map.indexes[lastEntry.key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map.entries.pop();
// Delete the index for the deleted slot
delete map.indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(Map storage map, bytes32 key) internal view returns (bool) {
return map.indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function length(Map storage map) internal view returns (uint256) {
return map.entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Map storage map, uint256 index) internal view returns (bytes32, bytes32) {
require(map.entries.length > index, "EnumMap: index out of bounds");
MapEntry storage entry = map.entries[index];
return (entry.key, entry.value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(Map storage map, bytes32 key) internal view returns (bytes32) {
uint256 keyIndex = map.indexes[key];
require(keyIndex != 0, "EnumMap: nonexistent key"); // Equivalent to contains(map, key)
return map.entries[keyIndex - 1].value; // All indexes are 1-based
}
}
// File @animoca/ethereum-contracts-core_library-5.0.0/contracts/algo/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity 0.6.8;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumSet for EnumSet.Set;
*
* // Declare a set state variable
* EnumSet.Set private mySet;
* }
* ```
*/
library EnumSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Set storage set, bytes32 value) internal returns (bool) {
if (!contains(set, value)) {
set.values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set.indexes[value] = set.values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Set storage set, bytes32 value) internal returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set.indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set.values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set.values[lastIndex];
// Move the last value to the index where the value to delete is
set.values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set.indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set.values.pop();
// Delete the index for the deleted slot
delete set.indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Set storage set, bytes32 value) internal view returns (bool) {
return set.indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(Set storage set) internal view returns (uint256) {
return set.values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Set storage set, uint256 index) internal view returns (bytes32) {
require(set.values.length > index, "EnumSet: index out of bounds");
return set.values[index];
}
}
// File @openzeppelin/contracts/GSN/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity >=0.6.0 <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 () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File @animoca/ethereum-contracts-core_library-5.0.0/contracts/payment/[email protected]
pragma solidity 0.6.8;
/**
@title PayoutWallet
@dev adds support for a payout wallet
Note: .
*/
contract PayoutWallet is Ownable {
event PayoutWalletSet(address payoutWallet_);
address payable public payoutWallet;
constructor(address payoutWallet_) internal {
setPayoutWallet(payoutWallet_);
}
function setPayoutWallet(address payoutWallet_) public onlyOwner {
require(payoutWallet_ != address(0), "Payout: zero address");
require(payoutWallet_ != address(this), "Payout: this contract as payout");
require(payoutWallet_ != payoutWallet, "Payout: same payout wallet");
payoutWallet = payable(payoutWallet_);
emit PayoutWalletSet(payoutWallet);
}
}
// File @animoca/ethereum-contracts-core_library-5.0.0/contracts/utils/[email protected]
pragma solidity 0.6.8;
/**
* Contract module which allows derived contracts to implement a mechanism for
* activating, or 'starting', a contract.
*
* This module is used through inheritance. It will make available the modifiers
* `whenNotStarted` and `whenStarted`, which can be applied to the functions of
* your contract. Those functions will only be 'startable' once the modifiers
* are put in place.
*/
contract Startable is Context {
event Started(address account);
uint256 private _startedAt;
/**
* Modifier to make a function callable only when the contract has not started.
*/
modifier whenNotStarted() {
require(_startedAt == 0, "Startable: started");
_;
}
/**
* Modifier to make a function callable only when the contract has started.
*/
modifier whenStarted() {
require(_startedAt != 0, "Startable: not started");
_;
}
/**
* Constructor.
*/
constructor() internal {}
/**
* Returns the timestamp when the contract entered the started state.
* @return The timestamp when the contract entered the started state.
*/
function startedAt() public view returns (uint256) {
return _startedAt;
}
/**
* Triggers the started state.
* @dev Emits the Started event when the function is successfully called.
*/
function _start() internal virtual whenNotStarted {
_startedAt = now;
emit Started(_msgSender());
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @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 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());
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File @animoca/ethereum-contracts-sale_base-8.0.0/contracts/sale/interfaces/[email protected]
pragma solidity 0.6.8;
/**
* @title ISale
*
* An interface for a contract which allows merchants to display products and customers to purchase them.
*
* Products, designated as SKUs, are represented by bytes32 identifiers so that an identifier can carry an
* explicit name under the form of a fixed-length string. Each SKU can be priced via up to several payment
* tokens which can be ETH and/or ERC20(s). ETH token is represented by the magic value TOKEN_ETH, which means
* this value can be used as the 'token' argument of the purchase-related functions to indicate ETH payment.
*
* The total available supply for a SKU is fixed at its creation. The magic value SUPPLY_UNLIMITED is used
* to represent a SKU with an infinite, never-decreasing supply. An optional purchase notifications receiver
* contract address can be set for a SKU at its creation: if the value is different from the zero address,
* the function `onPurchaseNotificationReceived` will be called on this address upon every purchase of the SKU.
*
* This interface is designed to be consistent while managing a variety of implementation scenarios. It is
* also intended to be developer-friendly: all vital information is consistently deductible from the events
* (backend-oriented), as well as retrievable through calls to public functions (frontend-oriented).
*/
interface ISale {
/**
* Event emitted to notify about the magic values necessary for interfacing with this contract.
* @param names An array of names for the magic values used by the contract.
* @param values An array of values for the magic values used by the contract.
*/
event MagicValues(bytes32[] names, bytes32[] values);
/**
* Event emitted to notify about the creation of a SKU.
* @param sku The identifier of the created SKU.
* @param totalSupply The initial total supply for sale.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param notificationsReceiver If not the zero address, the address of a contract on which `onPurchaseNotificationReceived` will be called after
* each purchase. If this is the zero address, the call is not enabled.
*/
event SkuCreation(bytes32 sku, uint256 totalSupply, uint256 maxQuantityPerPurchase, address notificationsReceiver);
/**
* Event emitted to notify about a change in the pricing of a SKU.
* @dev `tokens` and `prices` arrays MUST have the same length.
* @param sku The identifier of the updated SKU.
* @param tokens An array of updated payment tokens. If empty, interpret as all payment tokens being disabled.
* @param prices An array of updated prices for each of the payment tokens.
* Zero price values are used for payment tokens being disabled.
*/
event SkuPricingUpdate(bytes32 indexed sku, address[] tokens, uint256[] prices);
/**
* Event emitted to notify about a purchase.
* @param purchaser The initiater and buyer of the purchase.
* @param recipient The recipient of the purchase.
* @param token The token used as the currency for the payment.
* @param sku The identifier of the purchased SKU.
* @param quantity The purchased quantity.
* @param userData Optional extra user input data.
* @param totalPrice The amount of `token` paid.
* @param extData Implementation-specific extra purchase data, such as
* details about discounts applied, conversion rates, purchase receipts, etc.
*/
event Purchase(
address indexed purchaser,
address recipient,
address indexed token,
bytes32 indexed sku,
uint256 quantity,
bytes userData,
uint256 totalPrice,
bytes extData
);
/**
* Returns the magic value used to represent the ETH payment token.
* @dev MUST NOT be the zero address.
* @return the magic value used to represent the ETH payment token.
*/
// solhint-disable-next-line func-name-mixedcase
function TOKEN_ETH() external pure returns (address);
/**
* Returns the magic value used to represent an infinite, never-decreasing SKU's supply.
* @dev MUST NOT be zero.
* @return the magic value used to represent an infinite, never-decreasing SKU's supply.
*/
// solhint-disable-next-line func-name-mixedcase
function SUPPLY_UNLIMITED() external pure returns (uint256);
/**
* Performs a purchase.
* @dev Reverts if `recipient` is the zero address.
* @dev Reverts if `token` is the address zero.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @dev Emits the Purchase event.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
*/
function purchaseFor(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external payable;
/**
* Estimates the computed final total amount to pay for a purchase, including any potential discount.
* @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time).
* @dev If an implementer contract uses the `pricingData` field, it SHOULD document how to interpret the values.
* @dev Reverts if `recipient` is the zero address.
* @dev Reverts if `token` is the zero address.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @param recipient The recipient of the purchase used to calculate the total price amount.
* @param token The payment token used to calculate the total price amount.
* @param sku The identifier of the SKU used to calculate the total price amount.
* @param quantity The quantity used to calculate the total price amount.
* @param userData Optional extra user input data.
* @return totalPrice The computed total price to pay.
* @return pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* If not empty, the implementer MUST document how to interepret the values.
*/
function estimatePurchase(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external view returns (uint256 totalPrice, bytes32[] memory pricingData);
/**
* Returns the information relative to a SKU.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of payment tokens is bounded, so that this function does not run out of gas.
* @dev Reverts if `sku` does not exist.
* @param sku The SKU identifier.
* @return totalSupply The initial total supply for sale.
* @return remainingSupply The remaining supply for sale.
* @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function.
* @return tokens The list of supported payment tokens.
* @return prices The list of associated prices for each of the `tokens`.
*/
function getSkuInfo(bytes32 sku)
external
view
returns (
uint256 totalSupply,
uint256 remainingSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver,
address[] memory tokens,
uint256[] memory prices
);
/**
* Returns the list of created SKU identifiers.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of SKUs is bounded, so that this function does not run out of gas.
* @return skus the list of created SKU identifiers.
*/
function getSkus() external view returns (bytes32[] memory skus);
}
// File @animoca/ethereum-contracts-sale_base-8.0.0/contracts/sale/interfaces/[email protected]
pragma solidity 0.6.8;
/**
* @title IPurchaseNotificationsReceiver
* Interface for any contract that wants to support purchase notifications from a Sale contract.
*/
interface IPurchaseNotificationsReceiver {
/**
* Handles the receipt of a purchase notification.
* @dev This function MUST return the function selector, otherwise the caller will revert the transaction.
* The selector to be returned can be obtained as `this.onPurchaseNotificationReceived.selector`
* @dev This function MAY throw.
* @param purchaser The purchaser of the purchase.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
* @param totalPrice The total price paid.
* @param pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* @param paymentData Implementation-specific extra payment data, such as conversion rates.
* @param deliveryData Implementation-specific extra delivery data, such as purchase receipts.
* @return `bytes4(keccak256(
* "onPurchaseNotificationReceived(address,address,address,bytes32,uint256,bytes,uint256,bytes32[],bytes32[],bytes32[])"))`
*/
function onPurchaseNotificationReceived(
address purchaser,
address recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData,
uint256 totalPrice,
bytes32[] calldata pricingData,
bytes32[] calldata paymentData,
bytes32[] calldata deliveryData
) external returns (bytes4);
}
// File @animoca/ethereum-contracts-sale_base-8.0.0/contracts/sale/abstract/[email protected]
pragma solidity 0.6.8;
/**
* @title PurchaseLifeCycles
* An abstract contract which define the life cycles for a purchase implementer.
*/
abstract contract PurchaseLifeCycles {
/**
* Wrapper for the purchase data passed as argument to the life cycle functions and down to their step functions.
*/
struct PurchaseData {
address payable purchaser;
address payable recipient;
address token;
bytes32 sku;
uint256 quantity;
bytes userData;
uint256 totalPrice;
bytes32[] pricingData;
bytes32[] paymentData;
bytes32[] deliveryData;
}
/* Internal Life Cycle Functions */
/**
* `estimatePurchase` lifecycle.
* @param purchase The purchase conditions.
*/
function _estimatePurchase(PurchaseData memory purchase) internal view virtual returns (uint256 totalPrice, bytes32[] memory pricingData) {
_validation(purchase);
_pricing(purchase);
totalPrice = purchase.totalPrice;
pricingData = purchase.pricingData;
}
/**
* `purchaseFor` lifecycle.
* @param purchase The purchase conditions.
*/
function _purchaseFor(PurchaseData memory purchase) internal virtual {
_validation(purchase);
_pricing(purchase);
_payment(purchase);
_delivery(purchase);
_notification(purchase);
}
/* Internal Life Cycle Step Functions */
/**
* Lifecycle step which validates the purchase pre-conditions.
* @dev Responsibilities:
* - Ensure that the purchase pre-conditions are met and revert if not.
* @param purchase The purchase conditions.
*/
function _validation(PurchaseData memory purchase) internal view virtual;
/**
* Lifecycle step which computes the purchase price.
* @dev Responsibilities:
* - Computes the pricing formula, including any discount logic and price conversion;
* - Set the value of `purchase.totalPrice`;
* - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _pricing(PurchaseData memory purchase) internal view virtual;
/**
* Lifecycle step which manages the transfer of funds from the purchaser.
* @dev Responsibilities:
* - Ensure the payment reaches destination in the expected output token;
* - Handle any token swap logic;
* - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _payment(PurchaseData memory purchase) internal virtual;
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update;
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _delivery(PurchaseData memory purchase) internal virtual;
/**
* Lifecycle step which notifies of the purchase.
* @dev Responsibilities:
* - Manage after-purchase event(s) emission.
* - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable.
* @param purchase The purchase conditions.
*/
function _notification(PurchaseData memory purchase) internal virtual;
}
// File @animoca/ethereum-contracts-sale_base-8.0.0/contracts/sale/abstract/[email protected]
pragma solidity 0.6.8;
/**
* @title Sale
* An abstract base sale contract with a minimal implementation of ISale and administration functions.
* A minimal implementation of the `_validation`, `_delivery` and `notification` life cycle step functions
* are provided, but the inheriting contract must implement `_pricing` and `_payment`.
*/
abstract contract Sale is PurchaseLifeCycles, ISale, PayoutWallet, Startable, Pausable {
using Address for address;
using SafeMath for uint256;
using EnumSet for EnumSet.Set;
using EnumMap for EnumMap.Map;
struct SkuInfo {
uint256 totalSupply;
uint256 remainingSupply;
uint256 maxQuantityPerPurchase;
address notificationsReceiver;
EnumMap.Map prices;
}
address public constant override TOKEN_ETH = address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
uint256 public constant override SUPPLY_UNLIMITED = type(uint256).max;
EnumSet.Set internal _skus;
mapping(bytes32 => SkuInfo) internal _skuInfos;
uint256 internal immutable _skusCapacity;
uint256 internal immutable _tokensPerSkuCapacity;
/**
* Constructor.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param payoutWallet_ the payout wallet.
* @param skusCapacity the cap for the number of managed SKUs.
* @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU.
*/
constructor(
address payoutWallet_,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity
) internal PayoutWallet(payoutWallet_) {
_skusCapacity = skusCapacity;
_tokensPerSkuCapacity = tokensPerSkuCapacity;
bytes32[] memory names = new bytes32[](2);
bytes32[] memory values = new bytes32[](2);
(names[0], values[0]) = ("TOKEN_ETH", bytes32(uint256(TOKEN_ETH)));
(names[1], values[1]) = ("SUPPLY_UNLIMITED", bytes32(uint256(SUPPLY_UNLIMITED)));
emit MagicValues(names, values);
_pause();
}
/* Public Admin Functions */
/**
* Actvates, or 'starts', the contract.
* @dev Emits the `Started` event.
* @dev Emits the `Unpaused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has already been started.
* @dev Reverts if the contract is not paused.
*/
function start() public virtual onlyOwner {
_start();
_unpause();
}
/**
* Pauses the contract.
* @dev Emits the `Paused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has not been started yet.
* @dev Reverts if the contract is already paused.
*/
function pause() public virtual onlyOwner whenStarted {
_pause();
}
/**
* Resumes the contract.
* @dev Emits the `Unpaused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has not been started yet.
* @dev Reverts if the contract is not paused.
*/
function unpause() public virtual onlyOwner whenStarted {
_unpause();
}
/**
* Sets the token prices for the specified product SKU.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if `tokens` and `prices` have different lengths.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if one of the `tokens` is the zero address.
* @dev Reverts if the update results in too many tokens for the SKU.
* @dev Emits the `SkuPricingUpdate` event.
* @param sku The identifier of the SKU.
* @param tokens The list of payment tokens to update.
* If empty, disable all the existing payment tokens.
* @param prices The list of prices to apply for each payment token.
* Zero price values are used to disable a payment token.
*/
function updateSkuPricing(
bytes32 sku,
address[] memory tokens,
uint256[] memory prices
) public virtual onlyOwner {
uint256 length = tokens.length;
// solhint-disable-next-line reason-string
require(length == prices.length, "Sale: tokens/prices lengths mismatch");
SkuInfo storage skuInfo = _skuInfos[sku];
require(skuInfo.totalSupply != 0, "Sale: non-existent sku");
EnumMap.Map storage tokenPrices = skuInfo.prices;
if (length == 0) {
uint256 currentLength = tokenPrices.length();
for (uint256 i = 0; i < currentLength; ++i) {
// TODO add a clear function in EnumMap and EnumSet and use it
(bytes32 token, ) = tokenPrices.at(0);
tokenPrices.remove(token);
}
} else {
_setTokenPrices(tokenPrices, tokens, prices);
}
emit SkuPricingUpdate(sku, tokens, prices);
}
/* ISale Public Functions */
/**
* Performs a purchase.
* @dev Reverts if the sale has not started.
* @dev Reverts if the sale is paused.
* @dev Reverts if `recipient` is the zero address.
* @dev Reverts if `token` is the zero address.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @dev Emits the Purchase event.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
*/
function purchaseFor(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external payable virtual override whenStarted whenNotPaused {
PurchaseData memory purchase;
purchase.purchaser = _msgSender();
purchase.recipient = recipient;
purchase.token = token;
purchase.sku = sku;
purchase.quantity = quantity;
purchase.userData = userData;
_purchaseFor(purchase);
}
/**
* Estimates the computed final total amount to pay for a purchase, including any potential discount.
* @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time).
* @dev If an implementer contract uses the `pricingData` field, it SHOULD document how to interpret the values.
* @dev Reverts if the sale has not started.
* @dev Reverts if the sale is paused.
* @dev Reverts if `recipient` is the zero address.
* @dev Reverts if `token` is the zero address.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @param recipient The recipient of the purchase used to calculate the total price amount.
* @param token The payment token used to calculate the total price amount.
* @param sku The identifier of the SKU used to calculate the total price amount.
* @param quantity The quantity used to calculate the total price amount.
* @param userData Optional extra user input data.
* @return totalPrice The computed total price.
* @return pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* If not empty, the implementer MUST document how to interepret the values.
*/
function estimatePurchase(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external view virtual override whenStarted whenNotPaused returns (uint256 totalPrice, bytes32[] memory pricingData) {
PurchaseData memory purchase;
purchase.purchaser = _msgSender();
purchase.recipient = recipient;
purchase.token = token;
purchase.sku = sku;
purchase.quantity = quantity;
purchase.userData = userData;
return _estimatePurchase(purchase);
}
/**
* Returns the information relative to a SKU.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of payment tokens is bounded, so that this function does not run out of gas.
* @dev Reverts if `sku` does not exist.
* @param sku The SKU identifier.
* @return totalSupply The initial total supply for sale.
* @return remainingSupply The remaining supply for sale.
* @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function.
* @return tokens The list of supported payment tokens.
* @return prices The list of associated prices for each of the `tokens`.
*/
function getSkuInfo(bytes32 sku)
external
view
override
returns (
uint256 totalSupply,
uint256 remainingSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver,
address[] memory tokens,
uint256[] memory prices
)
{
SkuInfo storage skuInfo = _skuInfos[sku];
uint256 length = skuInfo.prices.length();
totalSupply = skuInfo.totalSupply;
require(totalSupply != 0, "Sale: non-existent sku");
remainingSupply = skuInfo.remainingSupply;
maxQuantityPerPurchase = skuInfo.maxQuantityPerPurchase;
notificationsReceiver = skuInfo.notificationsReceiver;
tokens = new address[](length);
prices = new uint256[](length);
for (uint256 i = 0; i < length; ++i) {
(bytes32 token, bytes32 price) = skuInfo.prices.at(i);
tokens[i] = address(uint256(token));
prices[i] = uint256(price);
}
}
/**
* Returns the list of created SKU identifiers.
* @return skus the list of created SKU identifiers.
*/
function getSkus() external view override returns (bytes32[] memory skus) {
skus = _skus.values;
}
/* Internal Utility Functions */
/**
* Creates an SKU.
* @dev Reverts if `totalSupply` is zero.
* @dev Reverts if `sku` already exists.
* @dev Reverts if `notificationsReceiver` is not the zero address and is not a contract address.
* @dev Reverts if the update results in too many SKUs.
* @dev Emits the `SkuCreation` event.
* @param sku the SKU identifier.
* @param totalSupply the initial total supply.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param notificationsReceiver The purchase notifications receiver contract address.
* If set to the zero address, the notification is not enabled.
*/
function _createSku(
bytes32 sku,
uint256 totalSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver
) internal virtual {
require(totalSupply != 0, "Sale: zero supply");
require(_skus.length() < _skusCapacity, "Sale: too many skus");
require(_skus.add(sku), "Sale: sku already created");
if (notificationsReceiver != address(0)) {
// solhint-disable-next-line reason-string
require(notificationsReceiver.isContract(), "Sale: receiver is not a contract");
}
SkuInfo storage skuInfo = _skuInfos[sku];
skuInfo.totalSupply = totalSupply;
skuInfo.remainingSupply = totalSupply;
skuInfo.maxQuantityPerPurchase = maxQuantityPerPurchase;
skuInfo.notificationsReceiver = notificationsReceiver;
emit SkuCreation(sku, totalSupply, maxQuantityPerPurchase, notificationsReceiver);
}
/**
* Updates SKU token prices.
* @dev Reverts if one of the `tokens` is the zero address.
* @dev Reverts if the update results in too many tokens for the SKU.
* @param tokenPrices Storage pointer to a mapping of SKU token prices to update.
* @param tokens The list of payment tokens to update.
* @param prices The list of prices to apply for each payment token.
* Zero price values are used to disable a payment token.
*/
function _setTokenPrices(
EnumMap.Map storage tokenPrices,
address[] memory tokens,
uint256[] memory prices
) internal virtual {
for (uint256 i = 0; i < tokens.length; ++i) {
address token = tokens[i];
require(token != address(0), "Sale: zero address token");
uint256 price = prices[i];
if (price == 0) {
tokenPrices.remove(bytes32(uint256(token)));
} else {
tokenPrices.set(bytes32(uint256(token)), bytes32(price));
}
}
require(tokenPrices.length() <= _tokensPerSkuCapacity, "Sale: too many tokens");
}
/* Internal Life Cycle Step Functions */
/**
* Lifecycle step which validates the purchase pre-conditions.
* @dev Responsibilities:
* - Ensure that the purchase pre-conditions are met and revert if not.
* @dev Reverts if `purchase.recipient` is the zero address.
* @dev Reverts if `purchase.token` is the zero address.
* @dev Reverts if `purchase.quantity` is zero.
* @dev Reverts if `purchase.quantity` is greater than the SKU's `maxQuantityPerPurchase`.
* @dev Reverts if `purchase.quantity` is greater than the available supply.
* @dev Reverts if `purchase.sku` does not exist.
* @dev Reverts if `purchase.sku` exists but does not have a price set for `purchase.token`.
* @dev If this function is overriden, the implementer SHOULD super call this before.
* @param purchase The purchase conditions.
*/
function _validation(PurchaseData memory purchase) internal view virtual override {
require(purchase.recipient != address(0), "Sale: zero address recipient");
require(purchase.token != address(0), "Sale: zero address token");
require(purchase.quantity != 0, "Sale: zero quantity purchase");
SkuInfo storage skuInfo = _skuInfos[purchase.sku];
require(skuInfo.totalSupply != 0, "Sale: non-existent sku");
require(skuInfo.maxQuantityPerPurchase >= purchase.quantity, "Sale: above max quantity");
if (skuInfo.totalSupply != SUPPLY_UNLIMITED) {
require(skuInfo.remainingSupply >= purchase.quantity, "Sale: insufficient supply");
}
bytes32 priceKey = bytes32(uint256(purchase.token));
require(skuInfo.prices.contains(priceKey), "Sale: non-existent sku token");
}
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update;
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @dev Reverts if there is not enough available supply.
* @dev If this function is overriden, the implementer SHOULD super call it.
* @param purchase The purchase conditions.
*/
function _delivery(PurchaseData memory purchase) internal virtual override {
SkuInfo memory skuInfo = _skuInfos[purchase.sku];
if (skuInfo.totalSupply != SUPPLY_UNLIMITED) {
_skuInfos[purchase.sku].remainingSupply = skuInfo.remainingSupply.sub(purchase.quantity);
}
}
/**
* Lifecycle step which notifies of the purchase.
* @dev Responsibilities:
* - Manage after-purchase event(s) emission.
* - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable.
* @dev Reverts if `onPurchaseNotificationReceived` throws or returns an incorrect value.
* @dev Emits the `Purchase` event. The values of `purchaseData` are the concatenated values of `priceData`, `paymentData`
* and `deliveryData`. If not empty, the implementer MUST document how to interpret these values.
* @dev If this function is overriden, the implementer SHOULD super call it.
* @param purchase The purchase conditions.
*/
function _notification(PurchaseData memory purchase) internal virtual override {
emit Purchase(
purchase.purchaser,
purchase.recipient,
purchase.token,
purchase.sku,
purchase.quantity,
purchase.userData,
purchase.totalPrice,
abi.encodePacked(purchase.pricingData, purchase.paymentData, purchase.deliveryData)
);
address notificationsReceiver = _skuInfos[purchase.sku].notificationsReceiver;
if (notificationsReceiver != address(0)) {
// solhint-disable-next-line reason-string
require(
IPurchaseNotificationsReceiver(notificationsReceiver).onPurchaseNotificationReceived(
purchase.purchaser,
purchase.recipient,
purchase.token,
purchase.sku,
purchase.quantity,
purchase.userData,
purchase.totalPrice,
purchase.pricingData,
purchase.paymentData,
purchase.deliveryData
) == IPurchaseNotificationsReceiver(address(0)).onPurchaseNotificationReceived.selector, // TODO precompute return value
"Sale: wrong receiver return value"
);
}
}
}
// File @animoca/ethereum-contracts-sale_base-8.0.0/contracts/sale/[email protected]
pragma solidity 0.6.8;
/**
* @title FixedPricesSale
* An Sale which implements a fixed prices strategy.
* The final implementer is responsible for implementing any additional pricing and/or delivery logic.
*/
contract FixedPricesSale is Sale {
/**
* Constructor.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param payoutWallet_ the payout wallet.
* @param skusCapacity the cap for the number of managed SKUs.
* @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU.
*/
constructor(
address payoutWallet_,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity
) internal Sale(payoutWallet_, skusCapacity, tokensPerSkuCapacity) {}
/* Internal Life Cycle Functions */
/**
* Lifecycle step which computes the purchase price.
* @dev Responsibilities:
* - Computes the pricing formula, including any discount logic and price conversion;
* - Set the value of `purchase.totalPrice`;
* - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it.
* @dev Reverts if `purchase.sku` does not exist.
* @dev Reverts if `purchase.token` is not supported by the SKU.
* @dev Reverts in case of price overflow.
* @param purchase The purchase conditions.
*/
function _pricing(PurchaseData memory purchase) internal view virtual override {
SkuInfo storage skuInfo = _skuInfos[purchase.sku];
require(skuInfo.totalSupply != 0, "Sale: unsupported SKU");
EnumMap.Map storage prices = skuInfo.prices;
uint256 unitPrice = _unitPrice(purchase, prices);
purchase.totalPrice = unitPrice.mul(purchase.quantity);
}
/**
* Lifecycle step which manages the transfer of funds from the purchaser.
* @dev Responsibilities:
* - Ensure the payment reaches destination in the expected output token;
* - Handle any token swap logic;
* - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it.
* @dev Reverts in case of payment failure.
* @param purchase The purchase conditions.
*/
function _payment(PurchaseData memory purchase) internal virtual override {
if (purchase.token == TOKEN_ETH) {
require(msg.value >= purchase.totalPrice, "Sale: insufficient ETH provided");
payoutWallet.transfer(purchase.totalPrice);
uint256 change = msg.value.sub(purchase.totalPrice);
if (change != 0) {
purchase.purchaser.transfer(change);
}
} else {
require(IERC20(purchase.token).transferFrom(_msgSender(), payoutWallet, purchase.totalPrice), "Sale: ERC20 payment failed");
}
}
/* Internal Utility Functions */
/**
* Retrieves the unit price of a SKU for the specified payment token.
* @dev Reverts if the specified payment token is unsupported.
* @param purchase The purchase conditions specifying the payment token with which the unit price will be retrieved.
* @param prices Storage pointer to a mapping of SKU token prices to retrieve the unit price from.
* @return unitPrice The unit price of a SKU for the specified payment token.
*/
function _unitPrice(PurchaseData memory purchase, EnumMap.Map storage prices) internal view virtual returns (uint256 unitPrice) {
unitPrice = uint256(prices.get(bytes32(uint256(purchase.token))));
require(unitPrice != 0, "Sale: unsupported payment token");
}
}
// File @animoca/ethereum-contracts-sale_base-8.0.0/contracts/sale/[email protected]
pragma solidity 0.6.8;
/**
* @title FixedOrderInventorySale
* A FixedPricesSale contract that handles the purchase of NFTs of an inventory contract to a
* receipient. The provisioning of the NFTs occurs in a sequential order defined by a token list.
* Only a single SKU is supported.
*/
contract FixedOrderInventorySale is FixedPricesSale {
address public immutable inventory;
uint256 public tokenIndex;
uint256[] public tokenList;
/**
* Constructor.
* @dev Reverts if `inventory_` is the zero address.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param inventory_ The inventory contract from which the NFT sale supply is attributed from.
* @param payoutWallet The payout wallet.
* @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU.
*/
constructor(
address inventory_,
address payoutWallet,
uint256 tokensPerSkuCapacity
)
public
FixedPricesSale(
payoutWallet,
1, // single SKU
tokensPerSkuCapacity
)
{
// solhint-disable-next-line reason-string
require(inventory_ != address(0), "FixedOrderInventorySale: zero address inventory");
inventory = inventory_;
}
/**
* Adds additional tokens to the sale supply.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if `tokens` is empty.
* @dev Reverts if any of `tokens` are zero.
* @dev The list of tokens specified (in sequence) will be appended to the end of the ordered
* sale supply list.
* @param tokens The list of tokens to add.
*/
function addSupply(uint256[] memory tokens) public virtual onlyOwner {
uint256 numTokens = tokens.length;
// solhint-disable-next-line reason-string
require(numTokens != 0, "FixedOrderInventorySale: empty tokens to add");
for (uint256 i = 0; i != numTokens; ++i) {
uint256 token = tokens[i];
// solhint-disable-next-line reason-string
require(token != 0, "FixedOrderInventorySale: adding zero token");
tokenList.push(token);
}
if (_skus.length() != 0) {
bytes32 sku = _skus.at(0);
SkuInfo storage skuInfo = _skuInfos[sku];
skuInfo.totalSupply += numTokens;
skuInfo.remainingSupply += numTokens;
}
}
/**
* Sets the tokens of the ordered sale supply list.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if called when the contract is not paused.
* @dev Reverts if the sale supply is empty.
* @dev Reverts if the lengths of `indexes` and `tokens` do not match.
* @dev Reverts if `indexes` is zero length.
* @dev Reverts if any of `indexes` are less than `tokenIndex`.
* @dev Reverts if any of `indexes` are out-of-bounds.
* @dev Reverts it `tokens` is zero length.
* @dev Reverts if any of `tokens` are zero.
* @dev Does not allow resizing of the sale supply, only the re-ordering or replacment of
* existing tokens.
* @dev Because the elements of `indexes` and `tokens` are processed in sequence, duplicate
* entries in either array are permitted, which allows for ordered operations to be performed
* on the ordered sale supply list in the same transaction.
* @param indexes The list of indexes in the ordered sale supply list whose element values
* will be set.
* @param tokens The new tokens to set in the ordered sale supply list at the corresponding
* positions provided by `indexes`.
*/
function setSupply(uint256[] memory indexes, uint256[] memory tokens) public virtual onlyOwner whenPaused {
uint256 tokenListLength = tokenList.length;
// solhint-disable-next-line reason-string
require(tokenListLength != 0, "FixedOrderInventorySale: empty token list");
uint256 numIndexes = indexes.length;
// solhint-disable-next-line reason-string
require(numIndexes != 0, "FixedOrderInventorySale: empty indexes");
uint256 numTokens = tokens.length;
// solhint-disable-next-line reason-string
require(numIndexes == numTokens, "FixedOrderInventorySale: array length mismatch");
uint256 tokenIndex_ = tokenIndex;
for (uint256 i = 0; i != numIndexes; ++i) {
uint256 index = indexes[i];
// solhint-disable-next-line reason-string
require(index >= tokenIndex_, "FixedOrderInventorySale: invalid index");
// solhint-disable-next-line reason-string
require(index < tokenListLength, "FixedOrderInventorySale: index out-of-bounds");
uint256 token = tokens[i];
// solhint-disable-next-line reason-string
require(token != 0, "FixedOrderInventorySale: zero token");
tokenList[index] = token;
}
}
/**
* Retrieves the amount of total sale supply.
* @return The amount of total sale supply.
*/
function getTotalSupply() public view virtual returns (uint256) {
return tokenList.length;
}
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update.
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @dev Reverts if there is not enough available supply.
* @dev Updates `purchase.deliveryData` with the list of tokens allocated from `tokenList` for
* this purchase.
* @param purchase The purchase conditions.
*/
function _delivery(PurchaseData memory purchase) internal virtual override {
super._delivery(purchase);
purchase.deliveryData = new bytes32[](purchase.quantity);
uint256 tokenCount = 0;
uint256 tokenIndex_ = tokenIndex;
while (tokenCount != purchase.quantity) {
purchase.deliveryData[tokenCount] = bytes32(tokenList[tokenIndex_]);
++tokenCount;
++tokenIndex_;
}
tokenIndex = tokenIndex_;
}
}
// File contracts/sale/FixedOrderSandNftSale.sol
pragma solidity 0.6.8;
/**
* @title FixedOrderSandNftSale
* A FixedOrderInventorySale contract implementation that handles the purchases of Sandbox NFTs
* track NFTs from a holder account to the recipient. The provisioning of the NFTs from the holder
* account occurs in a sequential order defined by a token list. Only a single SKU is supported.
*/
contract FixedOrderSandNftSale is FixedOrderInventorySale {
address public immutable tokenHolder;
/**
* Constructor.
* @dev Reverts if `inventory` is the zero address.
* @dev Reverts if `tokenHolder` is the zero address.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param inventory The inventory contract from which the NFT sale supply is attributed from.
* @param tokenHolder_ The account holding the pool of sale inventory NFTs.
* @param payoutWallet The payout wallet.
* @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU.
*/
constructor(
address inventory,
address tokenHolder_,
address payoutWallet,
uint256 tokensPerSkuCapacity
) public FixedOrderInventorySale(inventory, payoutWallet, tokensPerSkuCapacity) {
// solhint-disable-next-line reason-string
require(tokenHolder_ != address(0), "FixedOrderSandNftSale: zero address token holder");
tokenHolder = tokenHolder_;
}
/**
* Creates an SKU.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if called when the contract is not paused.
* @dev Reverts if the initial sale supply is empty.
* @dev Reverts if `sku` already exists.
* @dev Reverts if `notificationsReceiver` is not the zero address and is not a contract address.
* @dev Reverts if the update results in too many SKUs.
* @dev Emits the `SkuCreation` event.
* @param sku the SKU identifier.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param notificationsReceiver The purchase notifications receiver contract address.
* If set to the zero address, the notification is not enabled.
*/
function createSku(
bytes32 sku,
uint256 maxQuantityPerPurchase,
address notificationsReceiver
) external onlyOwner whenPaused {
_createSku(sku, tokenList.length, maxQuantityPerPurchase, notificationsReceiver);
}
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update.
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @dev Reverts if there is not enough available supply.
* @dev Reverts if this contract does not have the minter role on the inventory contract.
* @dev Updates `purchase.deliveryData` with the list of tokens allocated from `tokenList` for
* this purchase.
* @dev Mints the tokens allocated in `purchase.deliveryData` to the purchase recipient.
* @param purchase The purchase conditions.
*/
function _delivery(PurchaseData memory purchase) internal virtual override {
super._delivery(purchase);
uint256[] memory ids = new uint256[](purchase.quantity);
uint256[] memory values = new uint256[](purchase.quantity);
for (uint256 index = 0; index != purchase.quantity; ++index) {
ids[index] = uint256(purchase.deliveryData[index]);
values[index] = 1;
}
IFixedOrderInventoryTransferable(inventory).safeBatchTransferFrom(tokenHolder, purchase.recipient, ids, values, "");
}
}
/**
* @dev Interface for the transfer function of the NFT inventory contract.
*/
interface IFixedOrderInventoryTransferable {
/**
* @notice Transfers `values` amount(s) of `ids` from the `from` address to the `to` address specified (with safety call).
* @dev Caller must be approved to manage the tokens being transferred out of the `from` account (see "Approval" section of the standard).
* MUST revert if `to` is the zero address.
* MUST revert if length of `ids` is not the same as length of `values`.
* MUST revert if any of the balance(s) of the holder(s) for token(s) in `ids` is lower than the respective amount(s) in `values` sent to the
* recipient.
* MUST revert on any other error.
* MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of
* the standard).
* Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
* After the above conditions for the transfer(s) in the batch are met, this function MUST check if `to` is a smart contract
* (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `to` and act appropriately (see "Safe Transfer
* Rules" section of the standard).
* @param from Source address
* @param to Target address
* @param ids IDs of each token type (order and length must match _values array)
* @param values Transfer amounts per token type (order and length must match _ids array)
* @param data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `to`
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external;
} | * Creates an SKU. @dev Reverts if called by any other than the contract owner. @dev Reverts if called when the contract is not paused. @dev Reverts if the initial sale supply is empty. @dev Reverts if `sku` already exists. @dev Reverts if `notificationsReceiver` is not the zero address and is not a contract address. @dev Reverts if the update results in too many SKUs. @dev Emits the `SkuCreation` event. @param sku the SKU identifier. @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase. @param notificationsReceiver The purchase notifications receiver contract address. If set to the zero address, the notification is not enabled./ | function createSku(
bytes32 sku,
uint256 maxQuantityPerPurchase,
address notificationsReceiver
) external onlyOwner whenPaused {
_createSku(sku, tokenList.length, maxQuantityPerPurchase, notificationsReceiver);
}
| 10,376,163 | [
1,
2729,
392,
29469,
18,
225,
868,
31537,
309,
2566,
635,
1281,
1308,
2353,
326,
6835,
3410,
18,
225,
868,
31537,
309,
2566,
1347,
326,
6835,
353,
486,
17781,
18,
225,
868,
31537,
309,
326,
2172,
272,
5349,
14467,
353,
1008,
18,
225,
868,
31537,
309,
1375,
20763,
68,
1818,
1704,
18,
225,
868,
31537,
309,
1375,
15286,
12952,
68,
353,
486,
326,
3634,
1758,
471,
353,
486,
279,
6835,
1758,
18,
225,
868,
31537,
309,
326,
1089,
1686,
316,
4885,
4906,
12038,
3477,
18,
225,
7377,
1282,
326,
1375,
24130,
9906,
68,
871,
18,
225,
16731,
326,
29469,
2756,
18,
225,
943,
12035,
2173,
23164,
1021,
4207,
2935,
10457,
364,
279,
2202,
23701,
18,
225,
9208,
12952,
1021,
23701,
9208,
5971,
6835,
1758,
18,
225,
971,
444,
358,
326,
3634,
1758,
16,
326,
3851,
353,
486,
3696,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
752,
24130,
12,
203,
3639,
1731,
1578,
16731,
16,
203,
3639,
2254,
5034,
943,
12035,
2173,
23164,
16,
203,
3639,
1758,
9208,
12952,
203,
565,
262,
3903,
1338,
5541,
1347,
28590,
288,
203,
3639,
389,
2640,
24130,
12,
20763,
16,
1147,
682,
18,
2469,
16,
943,
12035,
2173,
23164,
16,
9208,
12952,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2020-11-16
*/
/*
██╗ ███████╗██╗ ██╗
██║ ██╔════╝╚██╗██╔╝
██║ █████╗ ╚███╔╝
██║ ██╔══╝ ██╔██╗
███████╗███████╗██╔╝ ██╗
╚══════╝╚══════╝╚═╝ ╚═╝
██╗ ██████╗ ██████╗██╗ ██╗███████╗██████╗
██║ ██╔═══██╗██╔════╝██║ ██╔╝██╔════╝██╔══██╗
██║ ██║ ██║██║ █████╔╝ █████╗ ██████╔╝
██║ ██║ ██║██║ ██╔═██╗ ██╔══╝ ██╔══██╗
███████╗╚██████╔╝╚██████╗██║ ██╗███████╗██║ ██║
╚══════╝ ╚═════╝ ╚═════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝
DEAR MSG.SENDER(S):
/ LXL is a project in beta
// Please audit & use at your own risk
/// Entry into LXL shall not create an attorney/client relationship
//// Likewise, LXL should not be construed as legal advice or replacement for professional counsel
///// STEAL THIS C0D3SL4W
~presented by LexDAO LLC \+|+/
*/
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.7.4;
interface IERC20 { // brief interface for erc20 token tx
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
library Address { // helper for address type - see openzeppelin-contracts/blob/master/contracts/utils/Address.sol
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
}
library SafeERC20 { // wrapper around erc20 token tx for non-standard contract - see openzeppelin-contracts/blob/master/contracts/token/ERC20/SafeERC20.sol
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
require(address(token).isContract(), "SafeERC20: call to non-contract");
(bool success, bytes memory returnData) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returnData.length > 0) { // return data is optional
require(abi.decode(returnData, (bool)), "SafeERC20: erc20 operation did not succeed");
}
}
}
library SafeMath { // arithmetic wrapper for unit under/overflow check
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
uint256 c = a / b;
return c;
}
}
contract Context { // describe current contract execution context (metaTX support) - see openzeppelin-contracts/blob/master/contracts/GSN/Context.sol
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract ReentrancyGuard { // call wrapper for reentrancy check - see https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/ReentrancyGuard.sol
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
modifier nonReentrant() {
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
_status = _ENTERED;
_;
_status = _NOT_ENTERED;
}
}
/**
* @title LexLocker.
* @author LexDAO LLC.
* @notice Milestone token locker registry with resolution.
*/
contract LexLocker is Context, ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeMath for uint256;
/*$<⚖️️> LXL <⚔️>$*/
address public manager; // account managing LXL settings - see 'Manager Functions' - updateable by manager
address public swiftResolverToken; // token required to participate as swift resolver - updateable by manager
address public wETH; // ether token wrapper contract reference - updateable by manager
uint256 private lockerCount; // lockers counted into LXL registry
uint256 public MAX_DURATION; // time limit in seconds on token lockup - default 63113904 (2-year) - updateable by manager
uint256 public resolutionRate; // rate to determine resolution fee for disputed locker (e.g., 20 = 5% of remainder) - updateable by manager
uint256 public swiftResolverTokenBalance; // balance required in `swiftResolverToken` to participate as swift resolver - updateable by manager
string public lockerTerms; // general terms wrapping LXL - updateable by manager
string[] public marketTerms; // market terms stamped by manager
string[] public resolutions; // locker resolutions stamped by LXL resolver
mapping(address => uint256[]) private clientRegistrations; // tracks registered lockers per client account
mapping(address => uint256[]) private providerRegistrations; // tracks registered lockers per provider account
mapping(address => bool) public swiftResolverConfirmed; // tracks registered swift resolver status
mapping(uint256 => ADR) public adrs; // tracks ADR details for registered LXL
mapping(uint256 => Locker) public lockers; // tracks registered LXL details
event DepositLocker(address indexed client, address clientOracle, address indexed provider, address indexed resolver, address token, uint256[] amount, uint256 registration, uint256 sum, uint256 termination, string details, bool swiftResolver);
event RegisterLocker(address indexed client, address clientOracle, address indexed provider, address indexed resolver, address token, uint256[] amount, uint256 registration, uint256 sum, uint256 termination, string details, bool swiftResolver);
event ConfirmLocker(uint256 registration);
event RequestLockerResolution(address indexed client, address indexed counterparty, address indexed resolver, address token, uint256 deposit, uint256 registration, string details, bool swiftResolver);
event Release(uint256 milestone, uint256 registration);
event Withdraw(uint256 registration);
event AssignClientOracle(address indexed clientOracle, uint256 registration);
event ClientProposeResolver(address indexed proposedResolver, uint256 registration, string details);
event ProviderProposeResolver(address indexed proposedResolver, uint256 registration, string details);
event Lock(address indexed caller, uint256 registration, string details);
event Resolve(address indexed resolver, uint256 clientAward, uint256 providerAward, uint256 registration, uint256 resolutionFee, string resolution);
event AddMarketTerms(uint256 index, string terms);
event AmendMarketTerms(uint256 index, string terms);
event UpdateLockerSettings(address indexed manager, address indexed swiftResolverToken, address wETH, uint256 MAX_DURATION, uint256 resolutionRate, uint256 swiftResolverTokenBalance, string lockerTerms);
event TributeToManager(uint256 amount, string details);
event UpdateSwiftResolverStatus(address indexed swiftResolver, string details, bool confirmed);
struct ADR {
address proposedResolver;
address resolver;
uint8 clientProposedResolver;
uint8 providerProposedResolver;
uint256 resolutionRate;
string resolution;
bool swiftResolver;
}
struct Locker {
address client;
address clientOracle;
address provider;
address token;
uint8 confirmed;
uint8 locked;
uint256[] amount;
uint256 currentMilestone;
uint256 milestones;
uint256 released;
uint256 sum;
uint256 termination;
string details;
}
constructor(
address _manager,
address _swiftResolverToken,
address _wETH,
uint256 _MAX_DURATION,
uint256 _resolutionRate,
uint256 _swiftResolverTokenBalance,
string memory _lockerTerms
) {
manager = _manager;
swiftResolverToken = _swiftResolverToken;
wETH = _wETH;
MAX_DURATION = _MAX_DURATION;
resolutionRate = _resolutionRate;
swiftResolverTokenBalance = _swiftResolverTokenBalance;
lockerTerms = _lockerTerms;
}
/***************
LOCKER FUNCTIONS
***************/
// ************
// REGISTRATION
// ************
/**
* @notice LXL can be registered as deposit from `client` for benefit of `provider`.
* @dev If LXL `token` is wETH, msg.value can be wrapped into wETH in single call.
* @param clientOracle Account that can help call `release()` and `withdraw()` (default to `client` if unsure).
* @param provider Account to receive registered `amount`s.
* @param resolver Account that can call `resolve()` to award `sum` remainder between LXL parties.
* @param token Token address for `amount` deposit.
* @param amount Lump `sum` or array of milestone `amount`s to be sent to `provider` on call of `release()`.
* @param termination Exact `termination` date in seconds since epoch.
* @param details Context re: LXL.
* @param swiftResolver If `true`, `sum` remainder can be resolved by holders of `swiftResolverToken`.
*/
function depositLocker( // CLIENT-TRACK
address clientOracle,
address provider,
address resolver,
address token,
uint256[] memory amount,
uint256 termination,
string memory details,
bool swiftResolver
) external nonReentrant payable returns (uint256) {
require(_msgSender() != resolver && clientOracle != resolver && provider != resolver, "client/clientOracle/provider = resolver");
require(termination <= block.timestamp.add(MAX_DURATION), "duration maxed");
uint256 sum;
for (uint256 i = 0; i < amount.length; i++) {
sum = sum.add(amount[i]);
}
if (msg.value > 0) {
require(token == wETH && msg.value == sum, "!ethBalance");
(bool success, ) = wETH.call{value: msg.value}("");
require(success, "!ethCall");
IERC20(wETH).safeTransfer(address(this), msg.value);
} else {
IERC20(token).safeTransferFrom(_msgSender(), address(this), sum);
}
lockerCount++;
uint256 registration = lockerCount;
clientRegistrations[_msgSender()].push(registration);
providerRegistrations[provider].push(registration);
adrs[registration] = ADR(
address(0),
resolver,
0,
0,
resolutionRate,
"",
swiftResolver);
lockers[registration] = Locker(
_msgSender(),
clientOracle,
provider,
token,
1,
0,
amount,
1,
amount.length,
0,
sum,
termination,
details);
emit DepositLocker(_msgSender(), clientOracle, provider, resolver, token, amount, registration, sum, termination, details, swiftResolver);
return registration;
}
/**
* @notice LXL can be registered as `provider` request for `client` deposit (by calling `confirmLocker()`).
* @param client Account to provide `sum` deposit and call `release()` of registered `amount`s.
* @param clientOracle Account that can help call `release()` and `withdraw()` (default to `client` if unsure).
* @param provider Account to receive registered `amount`s.
* @param resolver Account that can call `resolve()` to award `sum` remainder between LXL parties.
* @param token Token address for `amount` deposit.
* @param amount Lump `sum` or array of milestone `amount`s to be sent to `provider` on call of `release()`.
* @param termination Exact `termination` date in seconds since epoch.
* @param details Context re: LXL.
* @param swiftResolver If `true`, `sum` remainder can be resolved by holders of `swiftResolverToken`.
*/
function registerLocker( // PROVIDER-TRACK
address client,
address clientOracle,
address provider,
address resolver,
address token,
uint256[] memory amount,
uint256 termination,
string memory details,
bool swiftResolver
) external nonReentrant returns (uint256) {
require(client != resolver && clientOracle != resolver && provider != resolver, "client/clientOracle/provider = resolver");
require(termination <= block.timestamp.add(MAX_DURATION), "duration maxed");
uint256 sum;
for (uint256 i = 0; i < amount.length; i++) {
sum = sum.add(amount[i]);
}
lockerCount++;
uint256 registration = lockerCount;
clientRegistrations[client].push(registration);
providerRegistrations[provider].push(registration);
adrs[registration] = ADR(
address(0),
resolver,
0,
0,
resolutionRate,
"",
swiftResolver);
lockers[registration] = Locker(
client,
clientOracle,
provider,
token,
0,
0,
amount,
1,
amount.length,
0,
sum,
termination,
details);
emit RegisterLocker(client, clientOracle, provider, resolver, token, amount, registration, sum, termination, details, swiftResolver);
return registration;
}
/**
* @notice LXL `client` can confirm after `registerLocker()` is called to deposit `sum` for `provider`.
* @dev If LXL `token` is wETH, msg.value can be wrapped into wETH in single call.
* @param registration Registered LXL number.
*/
function confirmLocker(uint256 registration) external nonReentrant payable { // PROVIDER-TRACK
Locker storage locker = lockers[registration];
require(_msgSender() == locker.client, "!client");
require(locker.confirmed == 0, "confirmed");
address token = locker.token;
uint256 sum = locker.sum;
if (msg.value > 0) {
require(token == wETH && msg.value == sum, "!ethBalance");
(bool success, ) = wETH.call{value: msg.value}("");
require(success, "!ethCall");
IERC20(wETH).safeTransfer(address(this), msg.value);
} else {
IERC20(token).safeTransferFrom(_msgSender(), address(this), sum);
}
locker.confirmed = 1;
emit ConfirmLocker(registration);
}
/**
* @notice LXL depositor (`client`) can request direct resolution between selected `counterparty` over `deposit`. E.g., staked wager to benefit charity as `counterparty`.
* @dev If LXL `token` is wETH, msg.value can be wrapped into wETH in single call.
* @param counterparty Other account (`provider`) that can receive award from `resolver`.
* @param resolver Account that can call `resolve()` to award `deposit` between LXL parties.
* @param token Token address for `deposit`.
* @param deposit Lump sum amount for `deposit`.
* @param details Context re: resolution request.
* @param swiftResolver If `true`, `deposit` can be resolved by holders of `swiftResolverToken`.
*/
function requestLockerResolution(address counterparty, address resolver, address token, uint256 deposit, string memory details, bool swiftResolver) external nonReentrant payable returns (uint256) {
require(_msgSender() != resolver && counterparty != resolver, "client/counterparty = resolver");
if (msg.value > 0) {
require(token == wETH && msg.value == deposit, "!ethBalance");
(bool success, ) = wETH.call{value: msg.value}("");
require(success, "!ethCall");
IERC20(wETH).safeTransfer(address(this), msg.value);
} else {
IERC20(token).safeTransferFrom(_msgSender(), address(this), deposit);
}
uint256[] memory amount = new uint256[](1);
amount[0] = deposit;
lockerCount++;
uint256 registration = lockerCount;
clientRegistrations[_msgSender()].push(registration);
providerRegistrations[counterparty].push(registration);
adrs[registration] = ADR(
address(0),
resolver,
0,
0,
resolutionRate,
"",
swiftResolver);
lockers[registration] = Locker(
_msgSender(),
address(0),
counterparty,
token,
1,
1,
amount,
0,
0,
0,
deposit,
0,
details);
emit RequestLockerResolution(_msgSender(), counterparty, resolver, token, deposit, registration, details, swiftResolver);
return registration;
}
// ***********
// CLIENT MGMT
// ***********
/**
* @notice LXL `client` can assign account as `clientOracle` to help call `release()` and `withdraw()`.
* @param clientOracle Account that can help call `release()` and `withdraw()` (default to `client` if unsure).
* @param registration Registered LXL number.
*/
function assignClientOracle(address clientOracle, uint256 registration) external nonReentrant {
Locker storage locker = lockers[registration];
require(_msgSender() == locker.client, "!client");
require(locker.locked == 0, "locked");
require(locker.released < locker.sum, "released");
locker.clientOracle = clientOracle;
emit AssignClientOracle(clientOracle, registration);
}
/**
* @notice LXL `client` or `clientOracle` can release milestone `amount` to `provider`.
* @param registration Registered LXL number.
*/
function release(uint256 registration) external nonReentrant {
Locker storage locker = lockers[registration];
require(_msgSender() == locker.client || _msgSender() == locker.clientOracle, "!client/oracle");
require(locker.confirmed == 1, "!confirmed");
require(locker.locked == 0, "locked");
require(locker.released < locker.sum, "released");
uint256 milestone = locker.currentMilestone-1;
uint256 payment = locker.amount[milestone];
IERC20(locker.token).safeTransfer(locker.provider, payment);
locker.released = locker.released.add(payment);
if (locker.released < locker.sum) {locker.currentMilestone++;}
emit Release(milestone+1, registration);
}
/**
* @notice LXL `client` or `clientOracle` can withdraw `sum` remainder after `termination`.
* @dev `release()` can still be called by `client` or `clientOracle` after `termination` to preserve extension option.
* @param registration Registered LXL number.
*/
function withdraw(uint256 registration) external nonReentrant {
Locker storage locker = lockers[registration];
require(_msgSender() == locker.client || _msgSender() == locker.clientOracle, "!client/oracle");
require(locker.confirmed == 1, "!confirmed");
require(locker.locked == 0, "locked");
require(locker.released < locker.sum, "released");
require(locker.termination < block.timestamp, "!terminated");
uint256 remainder = locker.sum.sub(locker.released);
IERC20(locker.token).safeTransfer(locker.client, remainder);
locker.released = locker.sum;
emit Withdraw(registration);
}
// **********
// RESOLUTION
// **********
/**
* @notice LXL `client` or `provider` can lock to freeze release and withdrawal of `sum` remainder until `resolver` calls `resolve()`.
* @dev `lock()` can be called repeatedly to allow LXL parties to continue to provide context until resolution.
* @param registration Registered LXL number.
* @param details Context re: lock and/or dispute.
*/
function lock(uint256 registration, string calldata details) external nonReentrant {
Locker storage locker = lockers[registration];
require(_msgSender() == locker.client || _msgSender() == locker.provider, "!party");
require(locker.confirmed == 1, "!confirmed");
require(locker.released < locker.sum, "released");
locker.locked = 1;
emit Lock(_msgSender(), registration, details);
}
/**
* @notice After LXL is locked, selected `resolver` calls to distribute `sum` remainder between `client` and `provider` minus fee.
* @param registration Registered LXL number.
* @param clientAward Remainder awarded to `client`.
* @param providerAward Remainder awarded to `provider`.
* @param resolution Context re: resolution.
*/
function resolve(uint256 registration, uint256 clientAward, uint256 providerAward, string calldata resolution) external nonReentrant {
ADR storage adr = adrs[registration];
Locker storage locker = lockers[registration];
uint256 remainder = locker.sum.sub(locker.released);
uint256 resolutionFee = remainder.div(adr.resolutionRate); // calculate dispute resolution fee as set on registration
require(_msgSender() != locker.client && _msgSender() != locker.clientOracle && _msgSender() != locker.provider, "client/clientOracle/provider = resolver");
require(locker.locked == 1, "!locked");
require(locker.released < locker.sum, "released");
require(clientAward.add(providerAward) == remainder.sub(resolutionFee), "awards != remainder - fee");
if (adr.swiftResolver) {
require(IERC20(swiftResolverToken).balanceOf(_msgSender()) >= swiftResolverTokenBalance && swiftResolverConfirmed[_msgSender()], "!swiftResolverTokenBalance/confirmed");
} else {
require(_msgSender() == adr.resolver, "!resolver");
}
IERC20(locker.token).safeTransfer(locker.client, clientAward);
IERC20(locker.token).safeTransfer(locker.provider, providerAward);
IERC20(locker.token).safeTransfer(adr.resolver, resolutionFee);
adr.resolution = resolution;
locker.released = locker.sum;
resolutions.push(resolution);
emit Resolve(_msgSender(), clientAward, providerAward, registration, resolutionFee, resolution);
}
/**
* @notice 1-time, fallback to allow LXL party to suggest new `resolver` to counterparty.
* @dev LXL `client` calls to update `resolver` selection - if matches `provider` suggestion or confirmed, `resolver` updates.
* @param proposedResolver Proposed account to resolve LXL.
* @param registration Registered LXL number.
* @param details Context re: proposed `resolver`.
*/
function clientProposeResolver(address proposedResolver, uint256 registration, string calldata details) external nonReentrant {
ADR storage adr = adrs[registration];
Locker storage locker = lockers[registration];
require(_msgSender() == locker.client, "!client");
require(adr.clientProposedResolver == 0, "pending");
require(locker.released < locker.sum, "released");
if (adr.proposedResolver == proposedResolver) {
adr.resolver = proposedResolver;
} else {
adr.clientProposedResolver = 0;
adr.providerProposedResolver = 0;
}
adr.proposedResolver = proposedResolver;
adr.clientProposedResolver = 1;
emit ClientProposeResolver(proposedResolver, registration, details);
}
/**
* @notice 1-time, fallback to allow LXL party to suggest new `resolver` to counterparty.
* @dev LXL `provider` calls to update `resolver` selection. If matches `client` suggestion or confirmed, `resolver` updates.
* @param proposedResolver Proposed account to resolve LXL.
* @param registration Registered LXL number.
* @param details Context re: proposed `resolver`.
*/
function providerProposeResolver(address proposedResolver, uint256 registration, string calldata details) external nonReentrant {
ADR storage adr = adrs[registration];
Locker storage locker = lockers[registration];
require(_msgSender() == locker.provider, "!provider");
require(adr.providerProposedResolver == 0, "pending");
require(locker.released < locker.sum, "released");
if (adr.proposedResolver == proposedResolver) {
adr.resolver = proposedResolver;
} else {
adr.clientProposedResolver = 0;
adr.providerProposedResolver = 0;
}
adr.proposedResolver = proposedResolver;
adr.providerProposedResolver = 1;
emit ProviderProposeResolver(proposedResolver, registration, details);
}
/**
* @notice Swift resolvers can call to update service status.
* @dev Swift resolvers must first confirm and can continue with details / cancel service.
* @param details Context re: status update.
* @param confirmed If `true`, swift resolver can participate in LXL resolution.
*/
function updateSwiftResolverStatus(string calldata details, bool confirmed) external nonReentrant {
require(IERC20(swiftResolverToken).balanceOf(_msgSender()) >= swiftResolverTokenBalance, "!swiftResolverTokenBalance");
swiftResolverConfirmed[_msgSender()] = confirmed;
emit UpdateSwiftResolverStatus(_msgSender(), details, confirmed);
}
// *******
// GETTERS
// *******
function getClientRegistrations(address account) external view returns (uint256[] memory) { // get set of `client` registered lockers
return clientRegistrations[account];
}
function getLockerCount() external view returns (uint256) { // helper to make it easier to track total lockers
return lockerCount;
}
function getLockerMilestones(uint256 registration) external view returns (address, uint256[] memory) { // returns `token` and batch of milestone amounts for `provider`
return (lockers[registration].token, lockers[registration].amount);
}
function getMarketTermsCount() external view returns (uint256) { // helper to make it easier to track total market terms stamped by `manager`
return marketTerms.length;
}
function getProviderRegistrations(address account) external view returns (uint256[] memory) { // get set of `provider` registered lockers
return providerRegistrations[account];
}
function getResolutionCount() external view returns (uint256) { // helper to make it easier to track total resolutions passed by LXL `resolver`s
return resolutions.length;
}
/****************
MANAGER FUNCTIONS
****************/
/**
* @dev Throws if caller is not LXL `manager`.
*/
modifier onlyManager {
require(msg.sender == manager, "!manager");
_;
}
/**
* @notice Updates LXL with new market `terms`.
* @param terms New `terms` to add to LXL market.
*/
function addMarketTerms(string calldata terms) external nonReentrant onlyManager {
marketTerms.push(terms);
emit AddMarketTerms(marketTerms.length-1, terms);
}
/**
* @notice Updates LXL with amended market `terms`.
* @param index Targeted location in `marketTerms` array.
* @param terms Amended `terms` to add to LXL market.
*/
function amendMarketTerms(uint256 index, string calldata terms) external nonReentrant onlyManager {
marketTerms[index] = terms;
emit AmendMarketTerms(index, terms);
}
/**
* @notice General payment function for `manager` of LXL contract.
* @param details Describes context for ether transfer.
*/
function tributeToManager(string calldata details) external nonReentrant payable {
(bool success, ) = manager.call{value: msg.value}("");
require(success, "!ethCall");
emit TributeToManager(msg.value, details);
}
/**
* @notice Updates LXL management settings.
* @param _manager Account that governs LXL contract settings.
* @param _swiftResolverToken Token to mark participants in swift resolution.
* @param _wETH Standard contract reference to wrap ether.
* @param _MAX_DURATION Time limit in seconds on token lockup - default 63113904 (2-year).
* @param _resolutionRate Rate to determine resolution fee for disputed locker (e.g., 20 = 5% of remainder).
* @param _swiftResolverTokenBalance Token balance required to perform swift resolution.
* @param _lockerTerms General terms wrapping LXL.
*/
function updateLockerSettings(
address _manager,
address _swiftResolverToken,
address _wETH,
uint256 _MAX_DURATION,
uint256 _resolutionRate,
uint256 _swiftResolverTokenBalance,
string calldata _lockerTerms
) external nonReentrant onlyManager {
manager = _manager;
swiftResolverToken = _swiftResolverToken;
wETH = _wETH;
MAX_DURATION = _MAX_DURATION;
resolutionRate = _resolutionRate;
swiftResolverTokenBalance = _swiftResolverTokenBalance;
lockerTerms = _lockerTerms;
emit UpdateLockerSettings(_manager, _swiftResolverToken, _wETH, _MAX_DURATION, _resolutionRate, _swiftResolverTokenBalance, _lockerTerms);
}
} | * @notice LXL depositor (`client`) can request direct resolution between selected `counterparty` over `deposit`. E.g., staked wager to benefit charity as `counterparty`. @dev If LXL `token` is wETH, msg.value can be wrapped into wETH in single call. @param counterparty Other account (`provider`) that can receive award from `resolver`. @param resolver Account that can call `resolve()` to award `deposit` between LXL parties. @param token Token address for `deposit`. @param deposit Lump sum amount for `deposit`. @param details Context re: resolution request. @param swiftResolver If `true`, `deposit` can be resolved by holders of `swiftResolverToken`./ | function requestLockerResolution(address counterparty, address resolver, address token, uint256 deposit, string memory details, bool swiftResolver) external nonReentrant payable returns (uint256) {
require(_msgSender() != resolver && counterparty != resolver, "client/counterparty = resolver");
if (msg.value > 0) {
require(token == wETH && msg.value == deposit, "!ethBalance");
require(success, "!ethCall");
IERC20(wETH).safeTransfer(address(this), msg.value);
IERC20(token).safeTransferFrom(_msgSender(), address(this), deposit);
}
uint256[] memory amount = new uint256[](1);
amount[0] = deposit;
lockerCount++;
uint256 registration = lockerCount;
clientRegistrations[_msgSender()].push(registration);
providerRegistrations[counterparty].push(registration);
adrs[registration] = ADR(
address(0),
resolver,
0,
0,
resolutionRate,
"",
swiftResolver);
lockers[registration] = Locker(
_msgSender(),
address(0),
counterparty,
token,
1,
1,
amount,
0,
0,
0,
deposit,
0,
details);
emit RequestLockerResolution(_msgSender(), counterparty, resolver, token, deposit, registration, details, swiftResolver);
return registration;
(bool success, ) = wETH.call{value: msg.value}("");
} else {
}
| 2,248,359 | [
1,
48,
23668,
443,
1724,
280,
21863,
2625,
24065,
848,
590,
2657,
7861,
3086,
3170,
1375,
7476,
21214,
68,
1879,
1375,
323,
1724,
8338,
512,
18,
75,
12990,
384,
9477,
341,
6817,
358,
27641,
7216,
1149,
560,
487,
1375,
7476,
21214,
8338,
225,
971,
511,
23668,
1375,
2316,
68,
353,
341,
1584,
44,
16,
1234,
18,
1132,
848,
506,
5805,
1368,
341,
1584,
44,
316,
2202,
745,
18,
225,
3895,
21214,
4673,
2236,
21863,
6778,
24065,
716,
848,
6798,
279,
2913,
628,
1375,
14122,
8338,
225,
5039,
6590,
716,
848,
745,
1375,
10828,
20338,
358,
279,
2913,
1375,
323,
1724,
68,
3086,
511,
23668,
1087,
606,
18,
225,
1147,
3155,
1758,
364,
1375,
323,
1724,
8338,
225,
443,
1724,
511,
2801,
2142,
3844,
364,
1375,
323,
1724,
8338,
225,
3189,
1772,
283,
30,
7861,
590,
18,
225,
30331,
4301,
971,
1375,
3767,
9191,
1375,
323,
1724,
68,
848,
506,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
565,
445,
590,
2531,
264,
11098,
12,
2867,
3895,
21214,
16,
1758,
5039,
16,
1758,
1147,
16,
2254,
5034,
443,
1724,
16,
533,
3778,
3189,
16,
1426,
30331,
4301,
13,
3903,
1661,
426,
8230,
970,
8843,
429,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2583,
24899,
3576,
12021,
1435,
480,
5039,
597,
3895,
21214,
480,
5039,
16,
315,
2625,
19,
7476,
21214,
273,
5039,
8863,
203,
540,
203,
3639,
309,
261,
3576,
18,
1132,
405,
374,
13,
288,
203,
5411,
2583,
12,
2316,
422,
341,
1584,
44,
597,
1234,
18,
1132,
422,
443,
1724,
16,
17528,
546,
13937,
8863,
203,
5411,
2583,
12,
4768,
16,
17528,
546,
1477,
8863,
203,
5411,
467,
654,
39,
3462,
12,
91,
1584,
44,
2934,
4626,
5912,
12,
2867,
12,
2211,
3631,
1234,
18,
1132,
1769,
203,
5411,
467,
654,
39,
3462,
12,
2316,
2934,
4626,
5912,
1265,
24899,
3576,
12021,
9334,
1758,
12,
2211,
3631,
443,
1724,
1769,
203,
3639,
289,
203,
540,
203,
3639,
2254,
5034,
8526,
3778,
3844,
273,
394,
2254,
5034,
8526,
12,
21,
1769,
203,
3639,
3844,
63,
20,
65,
273,
443,
1724,
31,
203,
3639,
28152,
1380,
9904,
31,
203,
3639,
2254,
5034,
7914,
273,
28152,
1380,
31,
203,
540,
203,
3639,
1004,
20175,
1012,
63,
67,
3576,
12021,
1435,
8009,
6206,
12,
14170,
1769,
203,
3639,
2893,
20175,
1012,
63,
7476,
21214,
8009,
6206,
12,
14170,
1769,
203,
540,
203,
3639,
1261,
5453,
63,
14170,
65,
273,
432,
6331,
12,
7010,
5411,
1758,
12,
20,
3631,
203,
5411,
5039,
16,
203,
2
]
|
pragma solidity ^0.4.18;
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) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions"
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner
* @param newOwner The address to transfer ownership to
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/*
* @title Migration Agent interface
*/
contract MigrationAgent {
function migrateFrom(address _from, uint256 _value);
}
contract ERC20 {
function totalSupply() constant returns (uint256);
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value);
function transferFrom(address from, address to, uint256 value);
function approve(address spender, uint256 value);
function allowance(address owner, address spender) constant returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract PitEur is Ownable, ERC20 {
using SafeMath for uint256;
uint8 private _decimals = 18;
uint256 private decimalMultiplier = 10**(uint256(_decimals));
string private _name = "PIT-EUR";
string private _symbol = "PIT-EUR";
uint256 private _totalSupply = 100000000 * decimalMultiplier;
bool public tradable = true;
// Wallet Address of Token
address public multisig;
// Function to access name of token
function name() constant returns (string) {
return _name;
}
// Function to access symbol of token
function symbol() constant returns (string) {
return _symbol;
}
// Function to access decimals of token
function decimals() constant returns (uint8) {
return _decimals;
}
// Function to access total supply of tokens
function totalSupply() constant returns (uint256) {
return _totalSupply;
}
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
mapping(address => uint256) releaseTimes;
address public migrationAgent;
uint256 public totalMigrated;
event Migrate(address indexed _from, address indexed _to, uint256 _value);
// Constructor
// @notice PitEur Contract
// @return the transaction address
function PitEur(address _multisig) {
require(_multisig != 0x0);
multisig = _multisig;
balances[multisig] = _totalSupply;
}
modifier canTrade() {
require(tradable);
_;
}
// Standard function transfer similar to ERC20 transfer with no _data
// Added due to backwards compatibility reasons
function transfer(address to, uint256 value) canTrade {
require(!isLocked(msg.sender));
require (balances[msg.sender] >= value && value > 0);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
Transfer(msg.sender, to, value);
}
/**
* @dev Gets the balance of the specified address
* @param who The address to query the the balance of
* @return An uint256 representing the amount owned by the passed address
*/
function balanceOf(address who) constant returns (uint256) {
return balances[who];
}
/**
* @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 transfered
*/
function transferFrom(address from, address to, uint256 value) canTrade {
require(to != 0x0);
require(!isLocked(from));
uint256 _allowance = allowed[from][msg.sender];
require(value > 0 && _allowance >= value);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = _allowance.sub(value);
Transfer(from, to, value);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender
* @param spender The address which will spend the funds
* @param value The amount of tokens to be spent
*/
function approve(address spender, uint256 value) canTrade {
require((value >= 0) && (allowed[msg.sender][spender] >= 0));
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
}
// Check the allowed value for the spender to withdraw from owner
// @param owner The address of the owner
// @param spender The address of the spender
// @return the amount which spender is still allowed to withdraw from owner
function allowance(address owner, address spender) constant returns (uint256) {
return allowed[owner][spender];
}
/**
* @dev Function to update tradable status
* @param _newTradableState New tradable state
* @return A boolean that indicates if the operation was successful
*/
function setTradable(bool _newTradableState) onlyOwner public {
tradable = _newTradableState;
}
/**
* Function to lock a given address until the specified date
* @param spender Address to lock
* @param date A timestamp specifying when the account will be unlocked
* @return A boolean that indicates if the operation was successful
*/
function timeLock(address spender, uint256 date) public onlyOwner returns (bool) {
releaseTimes[spender] = date;
return true;
}
/**
* Function to check if a given address is locked or not
* @param _spender Address
* @return A boolean that indicates if the account is locked or not
*/
function isLocked(address _spender) public view returns (bool) {
if (releaseTimes[_spender] == 0 || releaseTimes[_spender] <= block.timestamp) {
return false;
}
return true;
}
/**
* @notice Set address of migration target contract and enable migration process
* @dev Required state: Operational Normal
* @dev State transition: -> Operational Migration
* @param _agent The address of the MigrationAgent contract
*/
function setMigrationAgent(address _agent) external onlyOwner {
require(migrationAgent == 0x0 && totalMigrated == 0);
migrationAgent = _agent;
}
/*
* @notice Migrate tokens to the new token contract.
* @dev Required state: Operational Migration
* @param _value The amount of token to be migrated
*/
function migrate(uint256 value) external {
require(migrationAgent != 0x0);
require(value >= 0);
require(value <= balances[msg.sender]);
balances[msg.sender] -= value;
_totalSupply = _totalSupply.sub(value);
totalMigrated = totalMigrated.add(value);
MigrationAgent(migrationAgent).migrateFrom(msg.sender, value);
Migrate(msg.sender, migrationAgent, value);
}
} | Wallet Address of Token Function to access name of token | contract PitEur is Ownable, ERC20 {
using SafeMath for uint256;
uint8 private _decimals = 18;
uint256 private decimalMultiplier = 10**(uint256(_decimals));
string private _name = "PIT-EUR";
string private _symbol = "PIT-EUR";
uint256 private _totalSupply = 100000000 * decimalMultiplier;
bool public tradable = true;
address public multisig;
function name() constant returns (string) {
return _name;
}
function symbol() constant returns (string) {
return _symbol;
}
function decimals() constant returns (uint8) {
return _decimals;
}
function totalSupply() constant returns (uint256) {
return _totalSupply;
}
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
mapping(address => uint256) releaseTimes;
address public migrationAgent;
uint256 public totalMigrated;
event Migrate(address indexed _from, address indexed _to, uint256 _value);
function PitEur(address _multisig) {
require(_multisig != 0x0);
multisig = _multisig;
balances[multisig] = _totalSupply;
}
modifier canTrade() {
require(tradable);
_;
}
function transfer(address to, uint256 value) canTrade {
require(!isLocked(msg.sender));
require (balances[msg.sender] >= value && value > 0);
balances[msg.sender] = balances[msg.sender].sub(value);
balances[to] = balances[to].add(value);
Transfer(msg.sender, to, value);
}
function balanceOf(address who) constant returns (uint256) {
return balances[who];
}
function transferFrom(address from, address to, uint256 value) canTrade {
require(to != 0x0);
require(!isLocked(from));
uint256 _allowance = allowed[from][msg.sender];
require(value > 0 && _allowance >= value);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
allowed[from][msg.sender] = _allowance.sub(value);
Transfer(from, to, value);
}
function approve(address spender, uint256 value) canTrade {
require((value >= 0) && (allowed[msg.sender][spender] >= 0));
allowed[msg.sender][spender] = value;
Approval(msg.sender, spender, value);
}
function allowance(address owner, address spender) constant returns (uint256) {
return allowed[owner][spender];
}
function setTradable(bool _newTradableState) onlyOwner public {
tradable = _newTradableState;
}
function timeLock(address spender, uint256 date) public onlyOwner returns (bool) {
releaseTimes[spender] = date;
return true;
}
function isLocked(address _spender) public view returns (bool) {
if (releaseTimes[_spender] == 0 || releaseTimes[_spender] <= block.timestamp) {
return false;
}
return true;
}
function isLocked(address _spender) public view returns (bool) {
if (releaseTimes[_spender] == 0 || releaseTimes[_spender] <= block.timestamp) {
return false;
}
return true;
}
function setMigrationAgent(address _agent) external onlyOwner {
require(migrationAgent == 0x0 && totalMigrated == 0);
migrationAgent = _agent;
}
function migrate(uint256 value) external {
require(migrationAgent != 0x0);
require(value >= 0);
require(value <= balances[msg.sender]);
balances[msg.sender] -= value;
_totalSupply = _totalSupply.sub(value);
totalMigrated = totalMigrated.add(value);
MigrationAgent(migrationAgent).migrateFrom(msg.sender, value);
Migrate(msg.sender, migrationAgent, value);
}
} | 14,692,591 | [
1,
16936,
5267,
434,
3155,
4284,
358,
2006,
508,
434,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
453,
305,
41,
295,
353,
14223,
6914,
16,
4232,
39,
3462,
288,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
225,
2254,
28,
3238,
389,
31734,
273,
6549,
31,
203,
225,
2254,
5034,
3238,
6970,
23365,
273,
1728,
636,
12,
11890,
5034,
24899,
31734,
10019,
203,
203,
225,
533,
3238,
389,
529,
273,
315,
1102,
56,
17,
41,
1099,
14432,
203,
225,
533,
3238,
389,
7175,
273,
315,
1102,
56,
17,
41,
1099,
14432,
203,
225,
2254,
5034,
3238,
389,
4963,
3088,
1283,
273,
2130,
9449,
380,
6970,
23365,
31,
203,
203,
225,
1426,
1071,
1284,
17394,
273,
638,
31,
203,
203,
225,
1758,
1071,
22945,
360,
31,
203,
203,
225,
445,
508,
1435,
5381,
1135,
261,
1080,
13,
288,
203,
565,
327,
389,
529,
31,
203,
225,
289,
203,
203,
225,
445,
3273,
1435,
5381,
1135,
261,
1080,
13,
288,
203,
565,
327,
389,
7175,
31,
203,
225,
289,
203,
203,
225,
445,
15105,
1435,
5381,
1135,
261,
11890,
28,
13,
288,
203,
565,
327,
389,
31734,
31,
203,
225,
289,
203,
203,
225,
445,
2078,
3088,
1283,
1435,
5381,
1135,
261,
11890,
5034,
13,
288,
203,
565,
327,
389,
4963,
3088,
1283,
31,
203,
225,
289,
203,
203,
225,
2874,
12,
2867,
516,
2254,
5034,
13,
324,
26488,
31,
203,
225,
2874,
12,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
2935,
31,
203,
225,
2874,
12,
2867,
516,
2254,
5034,
13,
3992,
10694,
31,
203,
225,
1758,
1071,
6333,
3630,
31,
203,
225,
2254,
5034,
1071,
2
]
|
./full_match/1/0x9965cCd16803432C6a0842f1D5690f32E427aEDd/sources/contracts/LiveMintTokyo.sol | Pindar Custom Contract
| if(ArtBlocksProjectID == 100) { MintedWorkTokenID = IMinter(_Pindar).purchaseTo(Recipient); } | 8,470,905 | [
1,
52,
728,
297,
6082,
13456,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5411,
309,
12,
4411,
6450,
4109,
734,
422,
2130,
13,
288,
490,
474,
329,
2421,
1345,
734,
273,
6246,
2761,
24899,
52,
728,
297,
2934,
12688,
12104,
774,
12,
18241,
1769,
289,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
pragma experimental ABIEncoderV2;
import "../WitnetRequestBoardUpgradableBase.sol";
import "../../data/WitnetBoardDataACLs.sol";
import "../../interfaces/IWitnetRequestBoardAdmin.sol";
import "../../interfaces/IWitnetRequestBoardAdminACLs.sol";
import "../../libs/WitnetParserLib.sol";
import "../../patterns/Payable.sol";
/// @title Witnet Request Board "trustable" base implementation contract.
/// @notice Contract to bridge requests to Witnet Decentralized Oracle Network.
/// @dev This contract enables posting requests that Witnet bridges will insert into the Witnet network.
/// The result of the requests will be posted back to this contract by the bridge nodes too.
/// @author The Witnet Foundation
abstract contract WitnetRequestBoardTrustableBase
is
Payable,
IWitnetRequestBoardAdmin,
IWitnetRequestBoardAdminACLs,
WitnetBoardDataACLs,
WitnetRequestBoardUpgradableBase
{
using Witnet for bytes;
using WitnetParserLib for Witnet.Result;
uint256 internal constant _ESTIMATED_REPORT_RESULT_GAS = 120547;
constructor(bool _upgradable, bytes32 _versionTag, address _currency)
Payable(_currency)
WitnetRequestBoardUpgradableBase(_upgradable, _versionTag)
{}
// ================================================================================================================
// --- Overrides 'Upgradable' -------------------------------------------------------------------------------------
/// Initialize storage-context when invoked as delegatecall.
/// @dev Must fail when trying to initialize same instance more than once.
function initialize(bytes memory _initData) virtual external override {
address _owner = _state().owner;
if (_owner == address(0)) {
// set owner if none set yet
_owner = msg.sender;
_state().owner = _owner;
} else {
// only owner can initialize:
require(msg.sender == _owner, "WitnetRequestBoardTrustableBase: only owner");
}
if (_state().base != address(0)) {
// current implementation cannot be initialized more than once:
require(_state().base != base(), "WitnetRequestBoardTrustableBase: already initialized");
}
_state().base = base();
emit Upgraded(msg.sender, base(), codehash(), version());
// Do actual base initialization:
setReporters(abi.decode(_initData, (address[])));
}
/// Tells whether provided address could eventually upgrade the contract.
function isUpgradableFrom(address _from) external view override returns (bool) {
address _owner = _state().owner;
return (
// false if the WRB is intrinsically not upgradable, or `_from` is no owner
isUpgradable()
&& _owner == _from
);
}
// ================================================================================================================
// --- Full implementation of 'IWitnetRequestBoardAdmin' ----------------------------------------------------------
/// Gets admin/owner address.
function owner()
public view
override
returns (address)
{
return _state().owner;
}
/// Transfers ownership.
function transferOwnership(address _newOwner)
external
virtual override
onlyOwner
{
address _owner = _state().owner;
if (_newOwner != _owner) {
_state().owner = _newOwner;
emit OwnershipTransferred(_owner, _newOwner);
}
}
// ================================================================================================================
// --- Full implementation of 'IWitnetRequestBoardAdminACLs' ------------------------------------------------------
/// Tells whether given address is included in the active reporters control list.
/// @param _reporter The address to be checked.
function isReporter(address _reporter) public view override returns (bool) {
return _acls().isReporter_[_reporter];
}
/// Adds given addresses to the active reporters control list.
/// @dev Can only be called from the owner address.
/// @dev Emits the `ReportersSet` event.
/// @param _reporters List of addresses to be added to the active reporters control list.
function setReporters(address[] memory _reporters)
public
override
onlyOwner
{
for (uint ix = 0; ix < _reporters.length; ix ++) {
address _reporter = _reporters[ix];
_acls().isReporter_[_reporter] = true;
}
emit ReportersSet(_reporters);
}
/// Removes given addresses from the active reporters control list.
/// @dev Can only be called from the owner address.
/// @dev Emits the `ReportersUnset` event.
/// @param _exReporters List of addresses to be added to the active reporters control list.
function unsetReporters(address[] memory _exReporters)
public
override
onlyOwner
{
for (uint ix = 0; ix < _exReporters.length; ix ++) {
address _reporter = _exReporters[ix];
_acls().isReporter_[_reporter] = false;
}
emit ReportersUnset(_exReporters);
}
// ================================================================================================================
// --- Full implementation of 'IWitnetRequestBoardReporter' -------------------------------------------------------
/// Reports the Witnet-provided result to a previously posted request.
/// @dev Will assume `block.timestamp` as the timestamp at which the request was solved.
/// @dev Fails if:
/// @dev - the `_queryId` is not in 'Posted' status.
/// @dev - provided `_drTxHash` is zero;
/// @dev - length of provided `_result` is zero.
/// @param _queryId The unique identifier of the data request.
/// @param _drTxHash The hash of the solving tally transaction in Witnet.
/// @param _cborBytes The result itself as bytes.
function reportResult(
uint256 _queryId,
bytes32 _drTxHash,
bytes calldata _cborBytes
)
external
override
onlyReporters
inStatus(_queryId, Witnet.QueryStatus.Posted)
{
// solhint-disable not-rely-on-time
_reportResult(_queryId, block.timestamp, _drTxHash, _cborBytes);
}
/// Reports the Witnet-provided result to a previously posted request.
/// @dev Fails if:
/// @dev - called from unauthorized address;
/// @dev - the `_queryId` is not in 'Posted' status.
/// @dev - provided `_drTxHash` is zero;
/// @dev - length of provided `_result` is zero.
/// @param _queryId The unique query identifier
/// @param _timestamp The timestamp of the solving tally transaction in Witnet.
/// @param _drTxHash The hash of the solving tally transaction in Witnet.
/// @param _cborBytes The result itself as bytes.
function reportResult(
uint256 _queryId,
uint256 _timestamp,
bytes32 _drTxHash,
bytes calldata _cborBytes
)
external
override
onlyReporters
inStatus(_queryId, Witnet.QueryStatus.Posted)
{
_reportResult(_queryId, _timestamp, _drTxHash, _cborBytes);
}
// ================================================================================================================
// --- Full implementation of 'IWitnetRequestBoardRequestor' ------------------------------------------------------
/// Retrieves copy of all response data related to a previously posted request, removing the whole query from storage.
/// @dev Fails if the `_queryId` is not in 'Reported' status, or called from an address different to
/// @dev the one that actually posted the given request.
/// @param _queryId The unique query identifier.
function deleteQuery(uint256 _queryId)
public
virtual override
inStatus(_queryId, Witnet.QueryStatus.Reported)
returns (Witnet.Response memory _response)
{
Witnet.Query storage _query = _state().queries[_queryId];
require(
msg.sender == _query.request.requester,
"WitnetRequestBoardTrustableBase: only requester"
);
_response = _query.response;
delete _state().queries[_queryId];
emit DeletedQuery(_queryId, msg.sender);
}
/// Requests the execution of the given Witnet Data Request in expectation that it will be relayed and solved by the Witnet DON.
/// A reward amount is escrowed by the Witnet Request Board that will be transferred to the reporter who relays back the Witnet-provided
/// result to this request.
/// @dev Fails if:
/// @dev - provided reward is too low.
/// @dev - provided script is zero address.
/// @dev - provided script bytecode is empty.
/// @param _addr The address of a IWitnetRequest contract, containing the actual Data Request seralized bytecode.
/// @return _queryId An unique query identifier.
function postRequest(IWitnetRequest _addr)
public payable
virtual override
returns (uint256 _queryId)
{
uint256 _value = _getMsgValue();
uint256 _gasPrice = _getGasPrice();
// Checks the tally reward is covering gas cost
uint256 minResultReward = _gasPrice * _ESTIMATED_REPORT_RESULT_GAS;
require(_value >= minResultReward, "WitnetRequestBoardTrustableBase: reward too low");
// Validates provided script:
require(address(_addr) != address(0), "WitnetRequestBoardTrustableBase: null script");
bytes memory _bytecode = _addr.bytecode();
require(_bytecode.length > 0, "WitnetRequestBoardTrustableBase: empty script");
_queryId = ++ _state().numQueries;
Witnet.Request storage _request = _getRequestData(_queryId);
_request.requester = msg.sender;
_request.addr = _addr;
_request.hash = _bytecode.hash();
_request.gasprice = _gasPrice;
_request.reward = _value;
// Let observers know that a new request has been posted
emit PostedRequest(_queryId, msg.sender);
}
/// Increments the reward of a previously posted request by adding the transaction value to it.
/// @dev Updates request `gasPrice` in case this method is called with a higher
/// @dev gas price value than the one used in previous calls to `postRequest` or
/// @dev `upgradeReward`.
/// @dev Fails if the `_queryId` is not in 'Posted' status.
/// @dev Fails also in case the request `gasPrice` is increased, and the new
/// @dev reward value gets below new recalculated threshold.
/// @param _queryId The unique query identifier.
function upgradeReward(uint256 _queryId)
public payable
virtual override
inStatus(_queryId, Witnet.QueryStatus.Posted)
{
Witnet.Request storage _request = _getRequestData(_queryId);
uint256 _newReward = _request.reward + _getMsgValue();
uint256 _newGasPrice = _getGasPrice();
// If gas price is increased, then check if new rewards cover gas costs
if (_newGasPrice > _request.gasprice) {
// Checks the reward is covering gas cost
uint256 _minResultReward = _newGasPrice * _ESTIMATED_REPORT_RESULT_GAS;
require(
_newReward >= _minResultReward,
"WitnetRequestBoardTrustableBase: reward too low"
);
_request.gasprice = _newGasPrice;
}
_request.reward = _newReward;
}
// ================================================================================================================
// --- Full implementation of 'IWitnetRequestBoardView' -----------------------------------------------------------
/// Estimates the amount of reward we need to insert for a given gas price.
/// @param _gasPrice The gas price for which we need to calculate the rewards.
function estimateReward(uint256 _gasPrice)
external view
virtual override
returns (uint256)
{
return _gasPrice * _ESTIMATED_REPORT_RESULT_GAS;
}
/// Returns next request id to be generated by the Witnet Request Board.
function getNextQueryId()
external view
override
returns (uint256)
{
return _state().numQueries + 1;
}
/// Gets the whole Query data contents, if any, no matter its current status.
function getQueryData(uint256 _queryId)
external view
override
returns (Witnet.Query memory)
{
return _state().queries[_queryId];
}
/// Gets current status of given query.
function getQueryStatus(uint256 _queryId)
external view
override
returns (Witnet.QueryStatus)
{
return _getQueryStatus(_queryId);
}
/// Retrieves the whole Request record posted to the Witnet Request Board.
/// @dev Fails if the `_queryId` is not valid or, if it has been deleted,
/// @dev or if the related script bytecode got changed after being posted.
/// @param _queryId The unique identifier of a previously posted query.
function readRequest(uint256 _queryId)
external view
override
notDeleted(_queryId)
returns (Witnet.Request memory)
{
return _checkRequest(_queryId);
}
/// Retrieves the Witnet data request actual bytecode of a previously posted request.
/// @dev Fails if the `_queryId` is not valid or, if it has been deleted,
/// @dev or if the related script bytecode got changed after being posted.
/// @param _queryId The unique identifier of the request query.
function readRequestBytecode(uint256 _queryId)
external view
override
notDeleted(_queryId)
returns (bytes memory _bytecode)
{
Witnet.Request storage _request = _getRequestData(_queryId);
if (address(_request.addr) != address(0)) {
// if DR's request contract address is not zero,
// we assume the DR has not been deleted, so
// DR's bytecode can still be fetched:
_bytecode = _request.addr.bytecode();
require(
_bytecode.hash() == _request.hash,
"WitnetRequestBoardTrustableBase: bytecode changed after posting"
);
}
}
/// Retrieves the gas price that any assigned reporter will have to pay when reporting
/// result to a previously posted Witnet data request.
/// @dev Fails if the `_queryId` is not valid or, if it has been deleted,
/// @dev or if the related script bytecode got changed after being posted.
/// @param _queryId The unique query identifier
function readRequestGasPrice(uint256 _queryId)
external view
override
notDeleted(_queryId)
returns (uint256)
{
return _checkRequest(_queryId).gasprice;
}
/// Retrieves the reward currently set for a previously posted request.
/// @dev Fails if the `_queryId` is not valid or, if it has been deleted,
/// @dev or if the related script bytecode got changed after being posted.
/// @param _queryId The unique query identifier
function readRequestReward(uint256 _queryId)
external view
override
notDeleted(_queryId)
returns (uint256)
{
return _checkRequest(_queryId).reward;
}
/// Retrieves the Witnet-provided result, and metadata, to a previously posted request.
/// @dev Fails if the `_queryId` is not in 'Reported' status.
/// @param _queryId The unique query identifier
function readResponse(uint256 _queryId)
external view
override
inStatus(_queryId, Witnet.QueryStatus.Reported)
returns (Witnet.Response memory _response)
{
return _getResponseData(_queryId);
}
/// Retrieves the hash of the Witnet transaction that actually solved the referred query.
/// @dev Fails if the `_queryId` is not in 'Reported' status.
/// @param _queryId The unique query identifier.
function readResponseDrTxHash(uint256 _queryId)
external view
override
inStatus(_queryId, Witnet.QueryStatus.Reported)
returns (bytes32)
{
return _getResponseData(_queryId).drTxHash;
}
/// Retrieves the address that reported the result to a previously-posted request.
/// @dev Fails if the `_queryId` is not in 'Reported' status.
/// @param _queryId The unique query identifier
function readResponseReporter(uint256 _queryId)
external view
override
inStatus(_queryId, Witnet.QueryStatus.Reported)
returns (address)
{
return _getResponseData(_queryId).reporter;
}
/// Retrieves the Witnet-provided CBOR-bytes result of a previously posted request.
/// @dev Fails if the `_queryId` is not in 'Reported' status.
/// @param _queryId The unique query identifier
function readResponseResult(uint256 _queryId)
external view
override
inStatus(_queryId, Witnet.QueryStatus.Reported)
returns (Witnet.Result memory)
{
Witnet.Response storage _response = _getResponseData(_queryId);
return WitnetParserLib.resultFromCborBytes(_response.cborBytes);
}
/// Retrieves the timestamp in which the result to the referred query was solved by the Witnet DON.
/// @dev Fails if the `_queryId` is not in 'Reported' status.
/// @param _queryId The unique query identifier.
function readResponseTimestamp(uint256 _queryId)
external view
override
inStatus(_queryId, Witnet.QueryStatus.Reported)
returns (uint256)
{
return _getResponseData(_queryId).timestamp;
}
// ================================================================================================================
// --- Full implementation of 'IWitnetRequestParser' interface ----------------------------------------------------
/// Decode raw CBOR bytes into a Witnet.Result instance.
/// @param _cborBytes Raw bytes representing a CBOR-encoded value.
/// @return A `Witnet.Result` instance.
function resultFromCborBytes(bytes memory _cborBytes)
external pure
override
returns (Witnet.Result memory)
{
return WitnetParserLib.resultFromCborBytes(_cborBytes);
}
/// Decode a CBOR value into a Witnet.Result instance.
/// @param _cborValue An instance of `Witnet.CBOR`.
/// @return A `Witnet.Result` instance.
function resultFromCborValue(Witnet.CBOR memory _cborValue)
external pure
override
returns (Witnet.Result memory)
{
return WitnetParserLib.resultFromCborValue(_cborValue);
}
/// Tell if a Witnet.Result is successful.
/// @param _result An instance of Witnet.Result.
/// @return `true` if successful, `false` if errored.
function isOk(Witnet.Result memory _result)
external pure
override
returns (bool)
{
return _result.isOk();
}
/// Tell if a Witnet.Result is errored.
/// @param _result An instance of Witnet.Result.
/// @return `true` if errored, `false` if successful.
function isError(Witnet.Result memory _result)
external pure
override
returns (bool)
{
return _result.isError();
}
/// Decode a bytes value from a Witnet.Result as a `bytes` value.
/// @param _result An instance of Witnet.Result.
/// @return The `bytes` decoded from the Witnet.Result.
function asBytes(Witnet.Result memory _result)
external pure
override returns (bytes memory)
{
return _result.asBytes();
}
/// Decode an error code from a Witnet.Result as a member of `Witnet.ErrorCodes`.
/// @param _result An instance of `Witnet.Result`.
/// @return The `CBORValue.Error memory` decoded from the Witnet.Result.
function asErrorCode(Witnet.Result memory _result)
external pure
override
returns (Witnet.ErrorCodes)
{
return _result.asErrorCode();
}
/// Generate a suitable error message for a member of `Witnet.ErrorCodes` and its corresponding arguments.
/// @dev WARN: Note that client contracts should wrap this function into a try-catch foreseing potential errors generated in this function
/// @param _result An instance of `Witnet.Result`.
/// @return A tuple containing the `CBORValue.Error memory` decoded from the `Witnet.Result`, plus a loggable error message.
function asErrorMessage(Witnet.Result memory _result)
external pure
override
returns (Witnet.ErrorCodes, string memory)
{
return _result.asErrorMessage();
}
/// Decode a raw error from a `Witnet.Result` as a `uint64[]`.
/// @param _result An instance of `Witnet.Result`.
/// @return The `uint64[]` raw error as decoded from the `Witnet.Result`.
function asRawError(Witnet.Result memory _result)
external pure
override
returns(uint64[] memory)
{
return _result.asRawError();
}
/// Decode a boolean value from a Witnet.Result as an `bool` value.
/// @param _result An instance of Witnet.Result.
/// @return The `bool` decoded from the Witnet.Result.
function asBool(Witnet.Result memory _result)
external pure
override
returns (bool)
{
return _result.asBool();
}
/// Decode a fixed16 (half-precision) numeric value from a Witnet.Result as an `int32` value.
/// @dev Due to the lack of support for floating or fixed point arithmetic in the EVM, this method offsets all values.
/// by 5 decimal orders so as to get a fixed precision of 5 decimal positions, which should be OK for most `fixed16`.
/// use cases. In other words, the output of this method is 10,000 times the actual value, encoded into an `int32`.
/// @param _result An instance of Witnet.Result.
/// @return The `int128` decoded from the Witnet.Result.
function asFixed16(Witnet.Result memory _result)
external pure
override
returns (int32)
{
return _result.asFixed16();
}
/// Decode an array of fixed16 values from a Witnet.Result as an `int128[]` value.
/// @param _result An instance of Witnet.Result.
/// @return The `int128[]` decoded from the Witnet.Result.
function asFixed16Array(Witnet.Result memory _result)
external pure
override
returns (int32[] memory)
{
return _result.asFixed16Array();
}
/// Decode a integer numeric value from a Witnet.Result as an `int128` value.
/// @param _result An instance of Witnet.Result.
/// @return The `int128` decoded from the Witnet.Result.
function asInt128(Witnet.Result memory _result)
external pure
override
returns (int128)
{
return _result.asInt128();
}
/// Decode an array of integer numeric values from a Witnet.Result as an `int128[]` value.
/// @param _result An instance of Witnet.Result.
/// @return The `int128[]` decoded from the Witnet.Result.
function asInt128Array(Witnet.Result memory _result)
external pure
override
returns (int128[] memory)
{
return _result.asInt128Array();
}
/// Decode a string value from a Witnet.Result as a `string` value.
/// @param _result An instance of Witnet.Result.
/// @return The `string` decoded from the Witnet.Result.
function asString(Witnet.Result memory _result)
external pure
override
returns (string memory)
{
return _result.asString();
}
/// Decode an array of string values from a Witnet.Result as a `string[]` value.
/// @param _result An instance of Witnet.Result.
/// @return The `string[]` decoded from the Witnet.Result.
function asStringArray(Witnet.Result memory _result)
external pure
override
returns (string[] memory)
{
return _result.asStringArray();
}
/// Decode a natural numeric value from a Witnet.Result as a `uint64` value.
/// @param _result An instance of Witnet.Result.
/// @return The `uint64` decoded from the Witnet.Result.
function asUint64(Witnet.Result memory _result)
external pure
override
returns(uint64)
{
return _result.asUint64();
}
/// Decode an array of natural numeric values from a Witnet.Result as a `uint64[]` value.
/// @param _result An instance of Witnet.Result.
/// @return The `uint64[]` decoded from the Witnet.Result.
function asUint64Array(Witnet.Result memory _result)
external pure
override
returns (uint64[] memory)
{
return _result.asUint64Array();
}
// ================================================================================================================
// --- Internal functions -----------------------------------------------------------------------------------------
function _checkRequest(uint256 _queryId)
internal view
returns (Witnet.Request storage _request)
{
_request = _getRequestData(_queryId);
if (address(_request.addr) != address(0)) {
// if the script contract address is not zero,
// we assume the query has not been deleted, so
// the request script bytecode can still be fetched:
bytes memory _bytecode = _request.addr.bytecode();
require(
_bytecode.hash() == _request.hash,
"WitnetRequestBoardTrustableBase: bytecode changed after posting"
);
}
}
function _reportResult(
uint256 _queryId,
uint256 _timestamp,
bytes32 _drTxHash,
bytes memory _cborBytes
)
internal
{
require(_drTxHash != 0, "WitnetRequestBoardTrustableDefault: Witnet drTxHash cannot be zero");
// Ensures the result byes do not have zero length
// This would not be a valid encoding with CBOR and could trigger a reentrancy attack
require(_cborBytes.length != 0, "WitnetRequestBoardTrustableDefault: result cannot be empty");
Witnet.Query storage _query = _state().queries[_queryId];
Witnet.Response storage _response = _query.response;
// solhint-disable not-rely-on-time
_response.timestamp = _timestamp;
_response.drTxHash = _drTxHash;
_response.reporter = msg.sender;
_response.cborBytes = _cborBytes;
_safeTransferTo(payable(msg.sender), _query.request.reward);
emit PostedResult(_queryId, msg.sender);
}
}
| Increments the reward of a previously posted request by adding the transaction value to it. @dev Updates request `gasPrice` in case this method is called with a higher @dev gas price value than the one used in previous calls to `postRequest` or @dev `upgradeReward`. @dev Fails if the `_queryId` is not in 'Posted' status. @dev Fails also in case the request `gasPrice` is increased, and the new @dev reward value gets below new recalculated threshold. @param _queryId The unique query identifier. If gas price is increased, then check if new rewards cover gas costs Checks the reward is covering gas cost | function upgradeReward(uint256 _queryId)
public payable
virtual override
inStatus(_queryId, Witnet.QueryStatus.Posted)
{
Witnet.Request storage _request = _getRequestData(_queryId);
uint256 _newReward = _request.reward + _getMsgValue();
uint256 _newGasPrice = _getGasPrice();
if (_newGasPrice > _request.gasprice) {
uint256 _minResultReward = _newGasPrice * _ESTIMATED_REPORT_RESULT_GAS;
require(
_newReward >= _minResultReward,
"WitnetRequestBoardTrustableBase: reward too low"
);
_request.gasprice = _newGasPrice;
}
_request.reward = _newReward;
}
| 12,858,663 | [
1,
27597,
1346,
326,
19890,
434,
279,
7243,
23082,
590,
635,
6534,
326,
2492,
460,
358,
518,
18,
225,
15419,
590,
1375,
31604,
5147,
68,
316,
648,
333,
707,
353,
2566,
598,
279,
10478,
225,
16189,
6205,
460,
2353,
326,
1245,
1399,
316,
2416,
4097,
358,
1375,
2767,
691,
68,
578,
225,
1375,
15097,
17631,
1060,
8338,
225,
8911,
87,
309,
326,
1375,
67,
2271,
548,
68,
353,
486,
316,
296,
3349,
329,
11,
1267,
18,
225,
8911,
87,
2546,
316,
648,
326,
590,
1375,
31604,
5147,
68,
353,
31383,
16,
471,
326,
394,
225,
19890,
460,
5571,
5712,
394,
283,
22113,
5573,
18,
225,
389,
2271,
548,
1021,
3089,
843,
2756,
18,
971,
16189,
6205,
353,
31383,
16,
1508,
866,
309,
394,
283,
6397,
5590,
16189,
22793,
13074,
326,
19890,
353,
5590,
310,
16189,
6991,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
8400,
17631,
1060,
12,
11890,
5034,
389,
2271,
548,
13,
203,
3639,
1071,
8843,
429,
203,
3639,
5024,
3849,
4202,
203,
3639,
316,
1482,
24899,
2271,
548,
16,
678,
305,
2758,
18,
1138,
1482,
18,
3349,
329,
13,
203,
565,
288,
203,
3639,
678,
305,
2758,
18,
691,
2502,
389,
2293,
273,
389,
588,
17031,
24899,
2271,
548,
1769,
203,
203,
3639,
2254,
5034,
389,
2704,
17631,
1060,
273,
389,
2293,
18,
266,
2913,
397,
389,
588,
3332,
620,
5621,
203,
3639,
2254,
5034,
389,
2704,
27998,
5147,
273,
389,
588,
27998,
5147,
5621,
203,
203,
3639,
309,
261,
67,
2704,
27998,
5147,
405,
389,
2293,
18,
31604,
8694,
13,
288,
203,
5411,
2254,
5034,
389,
1154,
1253,
17631,
1060,
273,
389,
2704,
27998,
5147,
380,
389,
11027,
3445,
6344,
67,
22710,
67,
12289,
67,
43,
3033,
31,
203,
5411,
2583,
12,
203,
7734,
389,
2704,
17631,
1060,
1545,
389,
1154,
1253,
17631,
1060,
16,
203,
7734,
315,
59,
305,
2758,
691,
22233,
14146,
429,
2171,
30,
19890,
4885,
4587,
6,
203,
5411,
11272,
203,
5411,
389,
2293,
18,
31604,
8694,
273,
389,
2704,
27998,
5147,
31,
203,
3639,
289,
203,
3639,
389,
2293,
18,
266,
2913,
273,
389,
2704,
17631,
1060,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
interface IERC20 {
// ERC20 Optional Views
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
// Views
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
// Mutative functions
function transfer(address to, uint value) external returns (bool);
function approve(address spender, uint value) external returns (bool);
function transferFrom(
address from,
address to,
uint value
) external returns (bool);
// Events
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
interface IBinaryOptionMarketManager {
/* ========== TYPES ========== */
struct Fees {
uint poolFee;
uint creatorFee;
uint refundFee;
}
struct Durations {
uint maxOraclePriceAge;
uint expiryDuration;
uint maxTimeToMaturity;
}
struct CreatorLimits {
uint capitalRequirement;
uint skewLimit;
}
/* ========== VIEWS / VARIABLES ========== */
function fees() external view returns (uint poolFee, uint creatorFee, uint refundFee);
function durations() external view returns (uint maxOraclePriceAge, uint expiryDuration, uint maxTimeToMaturity);
function creatorLimits() external view returns (uint capitalRequirement, uint skewLimit);
function marketCreationEnabled() external view returns (bool);
function totalDeposited() external view returns (uint);
function numActiveMarkets() external view returns (uint);
function activeMarkets(uint index, uint pageSize) external view returns (address[] memory);
function numMaturedMarkets() external view returns (uint);
function maturedMarkets(uint index, uint pageSize) external view returns (address[] memory);
/* ========== MUTATIVE FUNCTIONS ========== */
function createMarket(
bytes32 oracleKey, uint strikePrice,
uint[2] calldata times, // [biddingEnd, maturity]
uint[2] calldata bids // [longBid, shortBid]
) external returns (IBinaryOptionMarket);
function resolveMarket(address market) external;
function expireMarkets(address[] calldata market) external;
}
interface IBinaryOptionMarket {
/* ========== TYPES ========== */
enum Phase { Bidding, Trading, Maturity, Expiry }
enum Side { Long, Short }
struct Options {
IBinaryOption long;
IBinaryOption short;
}
struct Prices {
uint long;
uint short;
}
struct Times {
uint biddingEnd;
uint maturity;
uint expiry;
}
struct OracleDetails {
bytes32 key;
uint strikePrice;
uint finalPrice;
}
/* ========== VIEWS / VARIABLES ========== */
function options() external view returns (IBinaryOption long, IBinaryOption short);
function prices() external view returns (uint long, uint short);
function times() external view returns (uint biddingEnd, uint maturity, uint destructino);
function oracleDetails() external view returns (bytes32 key, uint strikePrice, uint finalPrice);
function fees() external view returns (uint poolFee, uint creatorFee, uint refundFee);
function creatorLimits() external view returns (uint capitalRequirement, uint skewLimit);
function deposited() external view returns (uint);
function creator() external view returns (address);
function resolved() external view returns (bool);
function phase() external view returns (Phase);
function oraclePriceAndTimestamp() external view returns (uint price, uint updatedAt);
function canResolve() external view returns (bool);
function result() external view returns (Side);
function pricesAfterBidOrRefund(Side side, uint value, bool refund) external view returns (uint long, uint short);
function bidOrRefundForPrice(Side bidSide, Side priceSide, uint price, bool refund) external view returns (uint);
function bidsOf(address account) external view returns (uint long, uint short);
function totalBids() external view returns (uint long, uint short);
function claimableBalancesOf(address account) external view returns (uint long, uint short);
function totalClaimableSupplies() external view returns (uint long, uint short);
function balancesOf(address account) external view returns (uint long, uint short);
function totalSupplies() external view returns (uint long, uint short);
function exercisableDeposits() external view returns (uint);
/* ========== MUTATIVE FUNCTIONS ========== */
function bid(Side side, uint value) external;
function refund(Side side, uint value) external returns (uint refundMinusFee);
function claimOptions() external returns (uint longClaimed, uint shortClaimed);
function exerciseOptions() external returns (uint);
}
interface IBinaryOption {
/* ========== VIEWS / VARIABLES ========== */
function market() external view returns (IBinaryOptionMarket);
function bidOf(address account) external view returns (uint);
function totalBids() external view returns (uint);
function balanceOf(address account) external view returns (uint);
function totalSupply() external view returns (uint);
function claimableBalanceOf(address account) external view returns (uint);
function totalClaimableSupply() external view returns (uint);
}
contract BinaryOptionMarketData {
struct OptionValues {
uint long;
uint short;
}
struct Deposits {
uint deposited;
uint exercisableDeposits;
}
struct Resolution {
bool resolved;
bool canResolve;
}
struct OraclePriceAndTimestamp {
uint price;
uint updatedAt;
}
// used for things that don't change over the lifetime of the contract
struct MarketParameters {
address creator;
IBinaryOptionMarket.Options options;
IBinaryOptionMarket.Times times;
IBinaryOptionMarket.OracleDetails oracleDetails;
IBinaryOptionMarketManager.Fees fees;
IBinaryOptionMarketManager.CreatorLimits creatorLimits;
}
struct MarketData {
OraclePriceAndTimestamp oraclePriceAndTimestamp;
IBinaryOptionMarket.Prices prices;
Deposits deposits;
Resolution resolution;
IBinaryOptionMarket.Phase phase;
IBinaryOptionMarket.Side result;
OptionValues totalBids;
OptionValues totalClaimableSupplies;
OptionValues totalSupplies;
}
struct AccountData {
OptionValues bids;
OptionValues claimable;
OptionValues balances;
}
function getMarketParameters(IBinaryOptionMarket market) public view returns (MarketParameters memory) {
(IBinaryOption long, IBinaryOption short) = market.options();
(uint biddingEndDate, uint maturityDate, uint expiryDate) = market.times();
(bytes32 key, uint strikePrice, uint finalPrice) = market.oracleDetails();
(uint poolFee, uint creatorFee, uint refundFee) = market.fees();
MarketParameters memory data = MarketParameters(
market.creator(),
IBinaryOptionMarket.Options(long, short),
IBinaryOptionMarket.Times(biddingEndDate,maturityDate,expiryDate),
IBinaryOptionMarket.OracleDetails(key, strikePrice, finalPrice),
IBinaryOptionMarketManager.Fees(poolFee, creatorFee, refundFee),
IBinaryOptionMarketManager.CreatorLimits(0, 0)
);
// Stack too deep otherwise.
(uint capitalRequirement, uint skewLimit) = market.creatorLimits();
data.creatorLimits = IBinaryOptionMarketManager.CreatorLimits(capitalRequirement, skewLimit);
return data;
}
function getMarketData(IBinaryOptionMarket market) public view returns (MarketData memory) {
(uint price, uint updatedAt) = market.oraclePriceAndTimestamp();
(uint longClaimable, uint shortClaimable) = market.totalClaimableSupplies();
(uint longSupply, uint shortSupply) = market.totalSupplies();
(uint longBids, uint shortBids) = market.totalBids();
(uint longPrice, uint shortPrice) = market.prices();
return MarketData(
OraclePriceAndTimestamp(price, updatedAt),
IBinaryOptionMarket.Prices(longPrice, shortPrice),
Deposits(market.deposited(), market.exercisableDeposits()),
Resolution(market.resolved(), market.canResolve()),
market.phase(),
market.result(),
OptionValues(longBids, shortBids),
OptionValues(longClaimable, shortClaimable),
OptionValues(longSupply, shortSupply)
);
}
function getAccountMarketData(IBinaryOptionMarket market, address account) public view returns (AccountData memory) {
(uint longBid, uint shortBid) = market.bidsOf(account);
(uint longClaimable, uint shortClaimable) = market.claimableBalancesOf(account);
(uint longBalance, uint shortBalance) = market.balancesOf(account);
return AccountData(
OptionValues(longBid, shortBid),
OptionValues(longClaimable, shortClaimable),
OptionValues(longBalance, shortBalance)
);
}
}
| Stack too deep otherwise. | function getMarketParameters(IBinaryOptionMarket market) public view returns (MarketParameters memory) {
(IBinaryOption long, IBinaryOption short) = market.options();
(uint biddingEndDate, uint maturityDate, uint expiryDate) = market.times();
(bytes32 key, uint strikePrice, uint finalPrice) = market.oracleDetails();
(uint poolFee, uint creatorFee, uint refundFee) = market.fees();
MarketParameters memory data = MarketParameters(
market.creator(),
IBinaryOptionMarket.Options(long, short),
IBinaryOptionMarket.Times(biddingEndDate,maturityDate,expiryDate),
IBinaryOptionMarket.OracleDetails(key, strikePrice, finalPrice),
IBinaryOptionMarketManager.Fees(poolFee, creatorFee, refundFee),
IBinaryOptionMarketManager.CreatorLimits(0, 0)
);
(uint capitalRequirement, uint skewLimit) = market.creatorLimits();
data.creatorLimits = IBinaryOptionMarketManager.CreatorLimits(capitalRequirement, skewLimit);
return data;
}
| 5,395,760 | [
1,
2624,
4885,
4608,
3541,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
23232,
278,
2402,
12,
45,
5905,
1895,
3882,
278,
13667,
13,
1071,
1476,
1135,
261,
3882,
278,
2402,
3778,
13,
288,
203,
203,
3639,
261,
45,
5905,
1895,
1525,
16,
467,
5905,
1895,
3025,
13,
273,
13667,
18,
2116,
5621,
203,
3639,
261,
11890,
324,
1873,
310,
24640,
16,
2254,
29663,
1626,
16,
2254,
10839,
1626,
13,
273,
13667,
18,
8293,
5621,
203,
3639,
261,
3890,
1578,
498,
16,
2254,
609,
2547,
5147,
16,
2254,
727,
5147,
13,
273,
13667,
18,
280,
16066,
3790,
5621,
203,
3639,
261,
11890,
2845,
14667,
16,
2254,
11784,
14667,
16,
2254,
16255,
14667,
13,
273,
13667,
18,
3030,
281,
5621,
203,
203,
3639,
6622,
278,
2402,
3778,
501,
273,
6622,
278,
2402,
12,
203,
5411,
13667,
18,
20394,
9334,
203,
5411,
467,
5905,
1895,
3882,
278,
18,
1320,
12,
5748,
16,
3025,
3631,
203,
5411,
467,
5905,
1895,
3882,
278,
18,
10694,
12,
70,
1873,
310,
24640,
16,
7373,
2336,
1626,
16,
22409,
1626,
3631,
203,
5411,
467,
5905,
1895,
3882,
278,
18,
23601,
3790,
12,
856,
16,
609,
2547,
5147,
16,
727,
5147,
3631,
203,
5411,
467,
5905,
1895,
3882,
278,
1318,
18,
2954,
281,
12,
6011,
14667,
16,
11784,
14667,
16,
16255,
14667,
3631,
203,
5411,
467,
5905,
1895,
3882,
278,
1318,
18,
10636,
12768,
12,
20,
16,
374,
13,
203,
3639,
11272,
203,
203,
3639,
261,
11890,
12872,
18599,
16,
2254,
20001,
3039,
13,
273,
13667,
18,
20394,
12768,
5621,
203,
3639,
501,
18,
20394,
12768,
273,
467,
5905,
1895,
3882,
278,
1318,
2
]
|
./full_match/4/0x673667658E0dF94a63aE708eE66B7664D3C5Da3b/sources/browser/Untitled.sol | @dev - Proposal: mark a proposal as processed in the DAO registry | function processProposal(uint256 _proposalId)
external
hasAccess(this, FlagHelper.Flag.PROCESS_PROPOSAL)
{
Proposal storage proposal = _setProposalFlag(
_proposalId,
FlagHelper.Flag.PROCESSED
);
uint256 flags = proposal.flags;
emit ProcessedProposal(_proposalId, flags);
}
| 13,321,978 | [
1,
17,
19945,
30,
2267,
279,
14708,
487,
5204,
316,
326,
463,
20463,
4023,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1207,
14592,
12,
11890,
5034,
389,
685,
8016,
548,
13,
203,
3639,
3903,
203,
3639,
24836,
12,
2211,
16,
9960,
2276,
18,
4678,
18,
16560,
67,
3373,
7057,
1013,
13,
203,
565,
288,
203,
3639,
19945,
2502,
14708,
273,
389,
542,
14592,
4678,
12,
203,
5411,
389,
685,
8016,
548,
16,
203,
5411,
9960,
2276,
18,
4678,
18,
3373,
1441,
22276,
203,
3639,
11272,
203,
3639,
2254,
5034,
2943,
273,
14708,
18,
7133,
31,
203,
203,
3639,
3626,
1186,
3692,
14592,
24899,
685,
8016,
548,
16,
2943,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender account.
*/
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 {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev modifier to allow actions only when the contract IS paused
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev modifier to allow actions only when the contract IS NOT paused
*/
modifier whenPaused {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused returns (bool) {
paused = true;
Pause();
return true;
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused returns (bool) {
paused = false;
Unpause();
return true;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Controllable
* @dev The Controllable contract has an controller address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Controllable {
address public controller;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender account.
*/
function Controllable() public {
controller = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyController() {
require(msg.sender == controller);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newController The address to transfer ownership to.
*/
function transferControl(address newController) public onlyController {
if (newController != address(0)) {
controller = newController;
}
}
}
/**
* @title TokenInterface
* Standard Mintable ERC20 Token
*/
contract TokenInterface is Controllable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(address indexed _owner, address indexed _spender, uint256 _amount);
event Transfer(address indexed from, address indexed to, uint256 value);
function totalSupply() public constant returns (uint);
function totalSupplyAt(uint _blockNumber) public constant returns(uint);
function balanceOf(address _owner) public constant returns (uint256 balance);
function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint);
function transfer(address _to, uint256 _amount) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success);
function approve(address _spender, uint256 _amount) public returns (bool success);
function approveAndCall(address _spender, uint256 _amount, bytes _extraData) public returns (bool success);
function allowance(address _owner, address _spender) public constant returns (uint256 remaining);
function mint(address _owner, uint _amount) public returns (bool);
function lockPresaleBalances() public returns (bool);
function finishMinting() public returns (bool);
function enableTransfers(bool _value) public;
function enableMasterTransfers(bool _value) public;
function createCloneToken(uint _snapshotBlock, string _cloneTokenName, string _cloneTokenSymbol) public returns (address);
}
/**
* @title Presale
*/
contract Presale is Pausable {
using SafeMath for uint256;
TokenInterface public token;
bool public finalized = false;
uint256 public startTime = 1511177379;
uint256 public endTime = 1513769380;
uint256 public tokenCap = 10000 * (10 ** 18);
uint256 public cap = tokenCap / (10 ** 18);
uint256 public weiCap = cap * price;
uint256 public minInvestment = 100;
uint256 public decimalsMultiplier = (10 ** 18);
uint256 public totalWeiRaised;
uint256 public tokensMinted;
uint256 public totalSupply;
address public wallet = 0x5b6061446f8bd652e6dc09366c57f1fa802012c3;
uint256 public price = 1000;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event Finalized();
function TokenSale(address _tokenAddress) public {
require(_tokenAddress != 0x0);
token = TokenInterface(_tokenAddress);
}
// fallback function to buy tokens
function() public payable
{
buyTokens(msg.sender);
}
/**
* Low level token purchse function
* @param beneficiary will recieve the tokens.
*/
function buyTokens(address beneficiary)
public
payable
whenNotPaused
whenNotFinalized
{
require(beneficiary != 0x0);
require(validPurchase());
uint256 weiAmount = msg.value;
totalWeiRaised = totalWeiRaised.add(weiAmount);
uint256 tokens = weiAmount.mul(decimalsMultiplier).div(price);
tokensMinted = tokensMinted.add(tokens);
require(tokensMinted < tokenCap);
token.mint(beneficiary, tokens);
TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
forwardFunds();
}
function forwardFunds() internal
{
wallet.transfer(msg.value);
}
/**
* Validates the purchase (period, minimum amount, within cap)
* @return {bool} valid
*/
function validPurchase() internal constant returns (bool) {
uint256 current = now;
require(current >= startTime);
require(current <= endTime);
return true;
}
/**
* Change the Token controller
* @param _newController {address} New Token controller
*/
function changeController(address _newController) onlyOwner public returns (bool) {
token.transferControl(_newController);
return true;
}
function enableTransfers() public returns (bool) {
token.enableTransfers(true);
return true;
}
function lockTransfers() public onlyOwner returns (bool) {
token.enableTransfers(false);
return true;
}
function finalize() public onlyOwner returns (bool) {
require(paused);
token.finishMinting();
Finalized();
finalized = true;
return true;
}
modifier whenNotFinalized() {
require(!finalized);
_;
}
}
| fallback function to buy tokens | function() public payable
{
buyTokens(msg.sender);
}
| 7,269,137 | [
1,
16471,
445,
358,
30143,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
1435,
1071,
8843,
429,
203,
225,
288,
203,
565,
30143,
5157,
12,
3576,
18,
15330,
1769,
203,
225,
289,
203,
203,
21281,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0xE21DC27E7E190292241dA2378df02dbF9e72B8fe/sources/src/raffle.sol | Declare use of custom ERC20 tokens | contract NFTRaffleContract {
address public admin;
uint256 public ticketCost;
event LotteryStarted();
event LotteryEnded();
event NFTPrizeSet(address nftContract, uint256 tokenId);
event BalanceWithdrawn(uint256 amount);
pragma solidity ^0.8.13;
struct TokenInfo {
IERC20 paytoken;
uint256 costvalue;
}
TokenInfo[] public AllowedCrypto;
function addCurrency(
IERC20 _paytoken,
uint256 _costvalue
) public onlyAdmin {
AllowedCrypto.push(
TokenInfo({
paytoken: _paytoken,
costvalue: _costvalue
})
);
}
function addCurrency(
IERC20 _paytoken,
uint256 _costvalue
) public onlyAdmin {
AllowedCrypto.push(
TokenInfo({
paytoken: _paytoken,
costvalue: _costvalue
})
);
}
constructor() {
}
modifier onlyAdmin() {
_;
}
function isPlayer(address participant) private view returns (bool) {
for (uint256 i = 0; i < players.length; i++) {
if (players[i] == participant) {
return true;
}
}
return false;
}
function isPlayer(address participant) private view returns (bool) {
for (uint256 i = 0; i < players.length; i++) {
if (players[i] == participant) {
return true;
}
}
return false;
}
function isPlayer(address participant) private view returns (bool) {
for (uint256 i = 0; i < players.length; i++) {
if (players[i] == participant) {
return true;
}
}
return false;
}
function buyTicket(uint256 numberOfTickets, uint256 _pid) public payable {
TokenInfo storage tokens = AllowedCrypto[_pid];
IERC20 paytoken;
paytoken = tokens.paytoken;
uint256 cost;
cost = tokens.costvalue;
allow = paytoken.allowance(msg.sender, address(this));
paytoken.transferFrom(msg.sender,address(this), cost * numberOfTickets);
entryCounts[msg.sender] += numberOfTickets;
totalEntries += numberOfTickets;
if (!isPlayer(msg.sender)) {
}
for (uint256 i = 0; i < numberOfTickets; i++) {
}
}
function buyTicket(uint256 numberOfTickets, uint256 _pid) public payable {
TokenInfo storage tokens = AllowedCrypto[_pid];
IERC20 paytoken;
paytoken = tokens.paytoken;
uint256 cost;
cost = tokens.costvalue;
allow = paytoken.allowance(msg.sender, address(this));
paytoken.transferFrom(msg.sender,address(this), cost * numberOfTickets);
entryCounts[msg.sender] += numberOfTickets;
totalEntries += numberOfTickets;
if (!isPlayer(msg.sender)) {
}
for (uint256 i = 0; i < numberOfTickets; i++) {
}
}
function buyTicket(uint256 numberOfTickets, uint256 _pid) public payable {
TokenInfo storage tokens = AllowedCrypto[_pid];
IERC20 paytoken;
paytoken = tokens.paytoken;
uint256 cost;
cost = tokens.costvalue;
allow = paytoken.allowance(msg.sender, address(this));
paytoken.transferFrom(msg.sender,address(this), cost * numberOfTickets);
entryCounts[msg.sender] += numberOfTickets;
totalEntries += numberOfTickets;
if (!isPlayer(msg.sender)) {
}
for (uint256 i = 0; i < numberOfTickets; i++) {
}
}
function startLottery(address _nftContract, uint256 _tokenId) public onlyAdmin {
require(nftContract == address(0), "Prize from previous lottery not transferred");
require(
ERC721Base(_nftContract).ownerOf(_tokenId) == admin,
"Admin does not own the specified NFT."
nftContract = _nftContract;
tokenId = _tokenId;
emit NFTPrizeSet(nftContract, tokenId);
}
function endLottery() public onlyAdmin {
}
function random() private view returns (uint256) {
return
uint256(
keccak256(
abi.encodePacked(
block.prevrandao,
block.timestamp,
players.length
)
)
);
}
function resetEntryCounts() private {
for (uint256 i = 0; i < players.length; i++) {
entryCounts[players[i]] = 0;
}
}
function resetEntryCounts() private {
for (uint256 i = 0; i < players.length; i++) {
entryCounts[players[i]] = 0;
}
}
function pickWinner() public onlyAdmin {
delete winnerOfPrize;
winnerOfPrize.push(winner);
ERC721Base(nftContract).transferFrom(admin, winner, tokenId);
}
function changeTicketCost(uint256 _newCost) public onlyAdmin {
}
function initialize() public {
}
function getTokenCostInfo(uint256 _pid) public view returns (uint256){
TokenInfo storage tokens = AllowedCrypto[_pid];
IERC20 paytoken;
paytoken = tokens.paytoken;
uint256 cost;
cost = tokens.costvalue;
return cost;
}
function getPlayers() public view returns (address[] memory) {
}
function getBalance() public view returns (uint256) {
}
function getWinner() public view returns (address[] memory) {
return winnerOfPrize;
}
function getBalanceERC20(uint256 _pid) public view returns (uint256) {
TokenInfo storage tokens = AllowedCrypto[_pid];
IERC20 paytoken;
paytoken = tokens.paytoken;
}
function getTokenInfo(uint256 _pid) public view returns (address) {
TokenInfo storage tokens = AllowedCrypto[_pid];
IERC20 paytoken;
paytoken = tokens.paytoken;
}
function withdrawBalance() public onlyAdmin {
require(address(this).balance > 0, "No balance to withdraw.");
uint256 amount = address(this).balance;
payable(admin).transfer(amount);
emit BalanceWithdrawn(amount);
}
function withdraw(uint256 _pid) public payable onlyAdmin() {
TokenInfo storage tokens = AllowedCrypto[_pid];
IERC20 paytoken;
paytoken = tokens.paytoken;
paytoken.transfer(msg.sender, paytoken.balanceOf(address(this)));
}
function resetContract() public onlyAdmin {
delete AllowedCrypto;
delete winnerOfPrize;
}
} | 1,922,876 | [
1,
3456,
834,
999,
434,
1679,
4232,
39,
3462,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
423,
42,
4349,
7329,
298,
8924,
288,
203,
565,
1758,
1071,
3981,
31,
203,
565,
2254,
5034,
1071,
9322,
8018,
31,
203,
377,
203,
565,
871,
511,
352,
387,
93,
9217,
5621,
203,
565,
871,
511,
352,
387,
93,
28362,
5621,
203,
565,
871,
423,
4464,
2050,
554,
694,
12,
2867,
290,
1222,
8924,
16,
2254,
5034,
1147,
548,
1769,
203,
565,
871,
30918,
1190,
9446,
82,
12,
11890,
5034,
3844,
1769,
203,
377,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
3437,
31,
203,
203,
565,
1958,
3155,
966,
288,
203,
5411,
467,
654,
39,
3462,
8843,
2316,
31,
203,
5411,
2254,
5034,
6991,
1132,
31,
203,
3639,
289,
203,
3639,
3155,
966,
8526,
1071,
16740,
18048,
31,
203,
3639,
445,
527,
7623,
12,
203,
5411,
467,
654,
39,
3462,
389,
10239,
2316,
16,
203,
5411,
2254,
5034,
389,
12398,
1132,
203,
3639,
262,
1071,
1338,
4446,
288,
203,
5411,
16740,
18048,
18,
6206,
12,
203,
7734,
3155,
966,
12590,
203,
10792,
8843,
2316,
30,
389,
10239,
2316,
16,
203,
10792,
6991,
1132,
30,
389,
12398,
1132,
203,
7734,
289,
13,
203,
5411,
11272,
203,
3639,
289,
203,
3639,
445,
527,
7623,
12,
203,
5411,
467,
654,
39,
3462,
389,
10239,
2316,
16,
203,
5411,
2254,
5034,
389,
12398,
1132,
203,
3639,
262,
1071,
1338,
4446,
288,
203,
5411,
16740,
18048,
18,
6206,
12,
203,
7734,
3155,
966,
12590,
203,
10792,
8843,
2316,
30,
389,
10239,
2316,
16,
203,
10792,
6991,
1132,
30,
389,
12398,
1132,
203,
7734,
289,
13,
2
]
|
./partial_match/1/0x7Ba3b4473d314c17398969864CA13C4d0C3336B4/sources/lib/cross-margin-engine/lib/core-physical/src/libraries/PhysicalActionUtil.sol | * @param tokenId option token id to mint @param amount amount of token to mint (6 decimals) @param subAccount sub account to receive minted option/ | function createMintIntoAccountAction(uint256 tokenId, uint256 amount, address subAccount)
internal
pure
returns (ActionArgs memory action)
{
}
| 15,964,202 | [
1,
2316,
548,
1456,
1147,
612,
358,
312,
474,
225,
3844,
3844,
434,
1147,
358,
312,
474,
261,
26,
15105,
13,
225,
720,
3032,
720,
2236,
358,
6798,
312,
474,
329,
1456,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
752,
49,
474,
5952,
3032,
1803,
12,
11890,
5034,
1147,
548,
16,
2254,
5034,
3844,
16,
1758,
720,
3032,
13,
203,
3639,
2713,
203,
3639,
16618,
203,
3639,
1135,
261,
1803,
2615,
3778,
1301,
13,
203,
565,
288,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x9cE40fb807eaF4aB3712c7D8797eE8107B36C46e/sources/FckAirdrop.sol | * @dev called by the operator to set the new operator to pause the token/ | function transferPauseOperator(address newPauseOperator) onlyPauseOperator public {
require(newPauseOperator != address(0));
emit PauseOperatorTransferred(pauseOperator, newPauseOperator);
pauseOperator = newPauseOperator;
}
| 4,259,936 | [
1,
11777,
635,
326,
3726,
358,
444,
326,
394,
3726,
358,
11722,
326,
1147,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7412,
19205,
5592,
12,
2867,
394,
19205,
5592,
13,
1338,
19205,
5592,
1071,
288,
203,
3639,
2583,
12,
2704,
19205,
5592,
480,
1758,
12,
20,
10019,
203,
3639,
3626,
31357,
5592,
1429,
4193,
12,
19476,
5592,
16,
394,
19205,
5592,
1769,
203,
3639,
11722,
5592,
273,
394,
19205,
5592,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/3/0x925681038F86d9454B58A8aAe9D3fC6365aed244/sources/KrajCoin.sol | _reflectFee(rFee, rBurn, tFee, tBurn, tCharity); | function _transferStandard(address sender, address recipient, uint256 tAmount) private {
uint256 currentRate = _getRate();
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tBurn, uint256 tCharity) = _getValues(tAmount);
uint256 rBurn = tBurn.mul(currentRate);
_standardTransferContent(sender, recipient, rAmount, rTransferAmount);
_sendToCharity(tCharity, sender);
_sendToDev(tFee, sender);
emit Transfer(sender, recipient, tTransferAmount);
}
| 8,150,252 | [
1,
67,
1734,
1582,
14667,
12,
86,
14667,
16,
436,
38,
321,
16,
268,
14667,
16,
268,
38,
321,
16,
268,
2156,
560,
1769,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
13866,
8336,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
268,
6275,
13,
3238,
288,
203,
3639,
2254,
5034,
783,
4727,
273,
389,
588,
4727,
5621,
203,
3639,
261,
11890,
5034,
436,
6275,
16,
2254,
5034,
436,
5912,
6275,
16,
2254,
5034,
436,
14667,
16,
2254,
5034,
268,
5912,
6275,
16,
2254,
5034,
268,
14667,
16,
2254,
5034,
268,
38,
321,
16,
2254,
5034,
268,
2156,
560,
13,
273,
389,
588,
1972,
12,
88,
6275,
1769,
203,
3639,
2254,
5034,
436,
38,
321,
273,
268,
38,
321,
18,
16411,
12,
2972,
4727,
1769,
203,
3639,
389,
10005,
5912,
1350,
12,
15330,
16,
8027,
16,
436,
6275,
16,
436,
5912,
6275,
1769,
203,
3639,
389,
4661,
774,
2156,
560,
12,
88,
2156,
560,
16,
5793,
1769,
203,
3639,
389,
4661,
774,
8870,
12,
88,
14667,
16,
5793,
1769,
203,
3639,
3626,
12279,
12,
15330,
16,
8027,
16,
268,
5912,
6275,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.0;
contract SimpleStorage {
//Check for data
//0-->new user
//1->user already exists
//2->for logging out the user
mapping(string=>string) private user_data;
mapping(string=>string) private logindata;
mapping(string=>uint) private data_checker;
mapping (string=>uint) private activeUsers;
function compareStrings (string a, string b) view returns (bool){
return keccak256(a) == keccak256(b);
}
function signup(string username,string password,string data)
public returns(bool){
if(data_checker[username]!=0) return false;
user_data[username] = data;
data_checker[username]=1;
logindata[username]=password;
return true;
}
function login(string username,string password) public returns(bool){
if(data_checker[username]==0){
return false;
}
else if(compareStrings(logindata[username],password)){
activeUsers[username]=1;//Here the user is logged in and
//we are saving it as 1
return true;
}
else{
return false;
}
}
function logout(string username) public returns(bool){
if(activeUsers[username]==1){//Check If the user is already loogged in
activeUsers[username]=2;//assign another variable for logging out
return true;
}
else{
return false;
}
}
function display_data(string username) view public returns(string)
{
return (user_data[username]);
}
} | Here the user is logged in and
| activeUsers[username]=1; | 6,442,656 | [
1,
26715,
326,
729,
353,
7545,
316,
471,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
6647,
2695,
6588,
63,
5053,
65,
33,
21,
31,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.11;
pragma experimental ABIEncoderV2;
import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "deps/@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "interfaces/uniswap/IUniswapRouterV2.sol";
import "interfaces/uniswap/IUniswapV2Factory.sol";
import "interfaces/curve/ICurveFi.sol";
import "interfaces/curve/ICurveGauge.sol";
import "interfaces/uniswap/IUniswapRouterV2.sol";
import "interfaces/badger/IBadgerGeyser.sol";
import "interfaces/badger/IController.sol";
import "../BaseStrategy.sol";
import "interfaces/uniswap/IStakingRewards.sol";
/*
Strategy to compound badger rewards
- Deposit Badger into the vault to receive more from a special rewards pool
*/
contract StrategyDiggLpMetaFarm is BaseStrategy {
using SafeERC20Upgradeable for IERC20Upgradeable;
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
address public geyser;
address public digg; // Digg Token
address public constant wbtc = 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599; // wBTC Token
address public constant weth = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // Weth Token, used for crv <> weth <> wbtc route
event HarvestLpMetaFarm(
uint256 badgerHarvested,
uint256 totalDigg,
uint256 diggConvertedToWbtc,
uint256 wbtcFromConversion,
uint256 lpGained,
uint256 lpDeposited,
uint256 timestamp,
uint256 blockNumber
);
struct HarvestData {
uint256 badgerHarvested;
uint256 totalDigg;
uint256 diggConvertedToWbtc;
uint256 wbtcFromConversion;
uint256 lpGained;
uint256 lpDeposited;
}
function initialize(
address _governance,
address _strategist,
address _controller,
address _keeper,
address _guardian,
address[3] memory _wantConfig,
uint256[3] memory _feeConfig
) public initializer {
__BaseStrategy_init(_governance, _strategist, _controller, _keeper, _guardian);
want = _wantConfig[0];
geyser = _wantConfig[1];
digg = _wantConfig[2];
performanceFeeGovernance = _feeConfig[0];
performanceFeeStrategist = _feeConfig[1];
withdrawalFee = _feeConfig[2];
}
/// ===== View Functions =====
function getName() external override pure returns (string memory) {
return "StrategyBadgerLpMetaFarm";
}
function balanceOfPool() public override view returns (uint256) {
return IStakingRewards(geyser).balanceOf(address(this));
}
function getProtectedTokens() public override view returns (address[] memory) {
address[] memory protectedTokens = new address[](3);
protectedTokens[0] = want;
protectedTokens[1] = geyser;
protectedTokens[2] = digg;
return protectedTokens;
}
/// ===== Internal Core Implementations =====
function _onlyNotProtectedTokens(address _asset) internal override {
require(address(want) != _asset, "want");
require(address(geyser) != _asset, "geyser");
require(address(digg) != _asset, "digg");
}
/// @dev Deposit Badger into the staking contract
function _deposit(uint256 _want) internal override {
_safeApproveHelper(want, geyser, _want);
IStakingRewards(geyser).stake(_want);
}
/// @dev Exit stakingRewards position
/// @dev Harvest all Badger and sent to controller
function _withdrawAll() internal override {
IStakingRewards(geyser).exit();
// Send non-native rewards to controller
uint256 _badger = IERC20Upgradeable(digg).balanceOf(address(this));
IERC20Upgradeable(digg).safeTransfer(IController(controller).rewards(), _badger);
}
/// @dev Withdraw from staking rewards, using earnings first
function _withdrawSome(uint256 _amount) internal override returns (uint256) {
uint256 _want = IERC20Upgradeable(want).balanceOf(address(this));
if (_want < _amount) {
uint256 _toWithdraw = _amount.sub(_want);
IStakingRewards(geyser).withdraw(_toWithdraw);
}
return _amount;
}
/// @dev Harvest accumulated digg rewards and convert them to LP tokens
/// @dev Restake the gained LP tokens in the Geyser
function harvest() external whenNotPaused returns (HarvestData memory) {
_onlyAuthorizedActors();
HarvestData memory harvestData;
uint256 _beforeBadger = IERC20Upgradeable(digg).balanceOf(address(this));
uint256 _beforeLp = IERC20Upgradeable(want).balanceOf(address(this));
// Harvest rewards from Geyser
IStakingRewards(geyser).getReward();
harvestData.totalDigg = IERC20Upgradeable(digg).balanceOf(address(this));
harvestData.badgerHarvested = harvestData.totalDigg.sub(_beforeBadger);
// Swap half of harvested digg for wBTC in liquidity pool
if (harvestData.totalDigg > 0) {
harvestData.diggConvertedToWbtc = harvestData.badgerHarvested.div(2);
if (harvestData.diggConvertedToWbtc > 0) {
address[] memory path = new address[](2);
path[0] = digg; // Badger
path[1] = wbtc;
_swap(digg, harvestData.diggConvertedToWbtc, path);
// Add Badger and wBTC as liquidity if any to add
_add_max_liquidity_uniswap(digg, wbtc);
}
}
// Deposit gained LP position into staking rewards
harvestData.lpDeposited = IERC20Upgradeable(want).balanceOf(address(this));
harvestData.lpGained = harvestData.lpDeposited.sub(_beforeLp);
if (harvestData.lpGained > 0) {
_deposit(harvestData.lpGained);
}
emit HarvestLpMetaFarm(
harvestData.badgerHarvested,
harvestData.totalDigg,
harvestData.diggConvertedToWbtc,
harvestData.wbtcFromConversion,
harvestData.lpGained,
harvestData.lpDeposited,
block.timestamp,
block.number
);
emit Harvest(harvestData.lpGained, block.number);
return harvestData;
}
}
| @dev Exit stakingRewards position @dev Harvest all Badger and sent to controller Send non-native rewards to controller | function _withdrawAll() internal override {
IStakingRewards(geyser).exit();
uint256 _badger = IERC20Upgradeable(digg).balanceOf(address(this));
IERC20Upgradeable(digg).safeTransfer(IController(controller).rewards(), _badger);
}
| 5,411,109 | [
1,
6767,
384,
6159,
17631,
14727,
1754,
225,
670,
297,
26923,
777,
6107,
693,
471,
3271,
358,
2596,
2479,
1661,
17,
13635,
283,
6397,
358,
2596,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
1918,
9446,
1595,
1435,
2713,
3849,
288,
203,
3639,
467,
510,
6159,
17631,
14727,
12,
75,
402,
550,
2934,
8593,
5621,
203,
203,
3639,
2254,
5034,
389,
8759,
693,
273,
467,
654,
39,
3462,
10784,
429,
12,
5606,
75,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
467,
654,
39,
3462,
10784,
429,
12,
5606,
75,
2934,
4626,
5912,
12,
45,
2933,
12,
5723,
2934,
266,
6397,
9334,
389,
8759,
693,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-10-18
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @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);
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @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;
}
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @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: MasterChef.sol
contract MasterChef {
using SafeERC20 for IERC20;
using SafeMath for uint256;
address public governance;
address public pendingGovernance;
address public guardian;
uint256 public effectTime;
uint256 constant public maxStartLeadTime = 60 days;
uint256 constant public maxPeriod = 800 days;
IERC20 public rewardToken;
uint256 public totalReward;
uint256 public totalGain;
uint256 public intervalTime;
uint256 public epochId;
uint256 public reward;
uint256 public startTime;
uint256 public endTime;
uint256 public period;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
// Info of each user.
struct UserInfo {
uint256 depositTime;
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt.
uint256 reward;
uint256 rewardDebtLp; // Reward debt.
uint256 rewardLp;
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 amount; // How many LP tokens.
uint256 lastRewardTime; // Last block number that Token distribution occurs.
uint256 allocPoint; // How many allocation points assigned to this pool. Token to distribute per block.
uint256 accTokenPerShare; // Accumulated Token per share, times 1e18. See below.
address owner;
address rewardToken;
uint256 totalReward;
uint256 epochId;
uint256 reward;
uint256 startTime;
uint256 endTime;
uint256 period;
uint256 accRewardTokenPerShare; // Accumulated Token per share, times 1e18. See below.
}
struct EpochReward {
uint256 epochId;
uint256 startTime;
uint256 endTime;
uint256 reward;
}
mapping(uint256 => EpochReward) public epochRewards;
mapping(uint256 => mapping(uint256 => EpochReward)) public lpEpochRewards;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfos;
// Info of each pool.
PoolInfo[] public poolInfos;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event Harvest(address indexed user, uint256 indexed pid, uint256 reward, address rewardToken, uint256 rewardLp);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event SetLpReward(uint256 indexed pid, uint256 indexed epochId, uint256 startTime, uint256 period, uint256 reward);
constructor(address _rewardToken, uint256 _intervalTime) public {
rewardToken = IERC20(_rewardToken);
governance = msg.sender;
guardian = msg.sender;
intervalTime = _intervalTime;
effectTime = block.timestamp + 60 days;
}
function setGuardian(address _guardian) external {
require(msg.sender == guardian, "!guardian");
guardian = _guardian;
}
function addGuardianTime(uint256 _addTime) external {
require(msg.sender == guardian || msg.sender == governance, "!guardian");
effectTime = effectTime.add(_addTime);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "!pendingGovernance");
governance = msg.sender;
pendingGovernance = address(0);
}
function setPendingGovernance(address _pendingGovernance) external {
require(msg.sender == governance, "!governance");
pendingGovernance = _pendingGovernance;
}
function setIntervalTime(uint256 _intervalTime) external {
require(msg.sender == governance, "!governance");
intervalTime = _intervalTime;
}
function setAllocPoint(uint256 _pid, uint256 _allocPoint, bool _withUpdate) external {
require(msg.sender == governance, "!governance");
require(_pid < poolInfos.length, "!_pid");
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfos[_pid].allocPoint).add(_allocPoint);
require(totalAllocPoint > 0, "!totalAllocPoint");
poolInfos[_pid].allocPoint = _allocPoint;
}
function addPool(address _lpToken, address _owner, uint256 _allocPoint, bool _withUpdate) external {
require(msg.sender == governance, "!governance");
uint256 length = poolInfos.length;
for (uint256 i = 0; i < length; i++) {
require(_lpToken != address(poolInfos[i].lpToken), "!_lpToken");
}
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfos.push(
PoolInfo({
lpToken: IERC20(_lpToken),
amount: 0,
lastRewardTime: block.timestamp,
allocPoint: _allocPoint,
accTokenPerShare: 0,
owner: _owner,
rewardToken: address(0),
totalReward: 0,
epochId: 0,
reward: 0,
startTime: 0,
endTime: 0,
period: 0,
accRewardTokenPerShare: 0
})
);
}
function setLpRewardToken(uint256 _pid, address _rewardToken) external {
require(_pid < poolInfos.length, "!_pid");
PoolInfo storage pool = poolInfos[_pid];
require(msg.sender == pool.owner || msg.sender == governance, "!pool.owner");
require(pool.rewardToken == address(0), "!pool.rewardToken");
pool.rewardToken = _rewardToken;
}
function setLpOwner(uint256 _pid, address _owner) external {
require(_pid < poolInfos.length, "!_pid");
PoolInfo storage pool = poolInfos[_pid];
require(msg.sender == pool.owner || msg.sender == governance, "!pool.owner");
pool.owner = _owner;
}
function setReward(uint256 _startTime, uint256 _period, uint256 _reward, bool _withUpdate) external {
require(msg.sender == governance, "!governance");
require(endTime < block.timestamp, "!endTime");
require(block.timestamp <= _startTime, "!_startTime");
require(_startTime <= block.timestamp + maxStartLeadTime, "!_startTime maxStartLeadTime");
require(_period > 0, "!_period");
require(_period <= maxPeriod, "!_period maxPeriod");
if (_withUpdate) {
massUpdatePools();
}
uint256 _balance = rewardToken.balanceOf(address(this));
require(_balance >= _reward, "!_reward");
totalReward = totalReward.add(_reward);
reward = _reward;
startTime = _startTime;
endTime = _startTime.add(_period);
period = _period;
epochId++;
epochRewards[epochId] = EpochReward({
epochId: epochId,
startTime: _startTime,
endTime: endTime,
reward: _reward
});
}
function setLpReward(uint256 _pid, uint256 _startTime, uint256 _period, uint256 _reward) external {
require(_pid < poolInfos.length, "!_pid");
PoolInfo storage pool = poolInfos[_pid];
require(msg.sender == pool.owner || msg.sender == governance, "!pool.owner");
require(pool.rewardToken != address(0), "!pool.rewardToken");
require(pool.endTime < block.timestamp, "!endTime");
require(block.timestamp <= _startTime, "!_startTime");
require(_startTime <= block.timestamp + maxStartLeadTime, "!_startTime maxStartLeadTime");
require(_period > 0, "!_period");
require(_period <= maxPeriod, "!_period maxPeriod");
updatePool(_pid);
IERC20(pool.rewardToken).safeTransferFrom(msg.sender, address(this), _reward);
pool.totalReward = pool.totalReward.add(_reward);
pool.epochId++;
pool.reward = _reward;
pool.startTime = _startTime;
pool.endTime = _startTime.add(_period);
pool.period = _period;
lpEpochRewards[_pid][epochId] = EpochReward({
epochId: epochId,
startTime: _startTime,
endTime: endTime,
reward: _reward
});
emit SetLpReward(_pid, pool.epochId, _startTime, _period, _reward);
}
function getReward(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= startTime || _from >= endTime) {
return 0;
}
if (_from < startTime) {
_from = startTime; // [startTime, endTime)
}
if (_to > endTime) {
_to = endTime; // (startTime, endTime]
}
require(_from < _to, "!_from < _to");
return _to.sub(_from).mul(reward).div(period);
}
function getLpReward(uint256 _pid, uint256 _from, uint256 _to) public view returns (uint256) {
PoolInfo storage pool = poolInfos[_pid];
uint256 _startTime = pool.startTime;
uint256 _endTime = pool.endTime;
if (_to <= _startTime || _from >= _endTime) {
return 0;
}
if (_from < _startTime) {
_from = _startTime; // [startTime, endTime)
}
if (_to > _endTime) {
_to = _endTime; // (startTime, endTime]
}
require(_from < _to, "!_from < _to");
return _to.sub(_from).mul(pool.reward).div(pool.period);
}
// View function to see pending Token on frontend.
function pendingToken(uint256 _pid, address _user) external view returns (uint256, uint256) {
require(_pid < poolInfos.length, "!_pid");
PoolInfo storage pool = poolInfos[_pid];
UserInfo storage user = userInfos[_pid][_user];
uint256 _accTokenPerShare = pool.accTokenPerShare;
uint256 _accRewardTokenPerShare = pool.accRewardTokenPerShare;
uint256 _lpSupply = pool.amount;
if (block.timestamp > pool.lastRewardTime && _lpSupply != 0) {
if (block.timestamp > startTime && pool.lastRewardTime < endTime) {
uint256 _rewardAmount = getReward(pool.lastRewardTime, block.timestamp);
if (_rewardAmount > 0) {
_rewardAmount = _rewardAmount.mul(pool.allocPoint).div(totalAllocPoint);
_accTokenPerShare = _accTokenPerShare.add(_rewardAmount.mul(1e18).div(_lpSupply));
}
}
if (block.timestamp > pool.startTime && pool.lastRewardTime < pool.endTime) {
uint256 _rewardLpAmount = getLpReward(_pid, pool.lastRewardTime, block.timestamp);
if (_rewardLpAmount > 0) {
_accRewardTokenPerShare = _accRewardTokenPerShare.add(_rewardLpAmount.mul(1e18).div(_lpSupply));
}
}
}
uint256 _reward = user.amount.mul(_accTokenPerShare).div(1e18).sub(user.rewardDebt);
uint256 _rewardLp = user.amount.mul(_accRewardTokenPerShare).div(1e18).sub(user.rewardDebtLp);
return (user.reward.add(_reward), user.rewardLp.add(_rewardLp));
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfos.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
require(_pid < poolInfos.length, "!_pid");
_updateRewardPerShare(_pid);
PoolInfo storage pool = poolInfos[_pid];
uint256 _lastRewardTime = pool.lastRewardTime;
if (block.timestamp <= _lastRewardTime) {
return;
}
pool.lastRewardTime = block.timestamp;
if (_lastRewardTime >= endTime) {
return;
}
if (block.timestamp <= startTime) {
return;
}
uint256 _lpSupply = pool.amount;
if (_lpSupply == 0) {
return;
}
uint256 _rewardAmount = getReward(_lastRewardTime, block.timestamp);
if (_rewardAmount > 0) {
_rewardAmount = _rewardAmount.mul(pool.allocPoint).div(totalAllocPoint);
pool.accTokenPerShare = pool.accTokenPerShare.add(_rewardAmount.mul(1e18).div(_lpSupply));
}
}
function _updateRewardPerShare(uint256 _pid) internal {
PoolInfo storage pool = poolInfos[_pid];
uint256 _lastRewardTime = pool.lastRewardTime;
if (block.timestamp <= _lastRewardTime) {
return;
}
if (_lastRewardTime >= pool.endTime) {
return;
}
if (block.timestamp <= pool.startTime) {
return;
}
uint256 _lpSupply = pool.amount;
if (_lpSupply == 0) {
return;
}
uint256 _rewardAmount = getLpReward(_pid, _lastRewardTime, block.timestamp);
if (_rewardAmount > 0) {
pool.accRewardTokenPerShare = pool.accRewardTokenPerShare.add(_rewardAmount.mul(1e18).div(_lpSupply));
}
}
function deposit(uint256 _pid, uint256 _amount) external {
require(_pid < poolInfos.length, "!_pid");
PoolInfo storage pool = poolInfos[_pid];
UserInfo storage user = userInfos[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 _reward = user.amount.mul(pool.accTokenPerShare).div(1e18).sub(user.rewardDebt);
uint256 _rewardLp = user.amount.mul(pool.accRewardTokenPerShare).div(1e18).sub(user.rewardDebtLp);
user.reward = _reward.add(user.reward);
user.rewardLp = _rewardLp.add(user.rewardLp);
}
pool.lpToken.safeTransferFrom(msg.sender, address(this), _amount);
user.depositTime = block.timestamp;
user.amount = user.amount.add(_amount);
pool.amount = pool.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e18);
user.rewardDebtLp = user.amount.mul(pool.accRewardTokenPerShare).div(1e18);
emit Deposit(msg.sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) external {
require(_pid < poolInfos.length, "!_pid");
PoolInfo storage pool = poolInfos[_pid];
UserInfo storage user = userInfos[_pid][msg.sender];
require(user.amount >= _amount, "!_amount");
require(block.timestamp >= user.depositTime + intervalTime, "!intervalTime");
updatePool(_pid);
uint256 _reward = user.amount.mul(pool.accTokenPerShare).div(1e18).sub(user.rewardDebt);
uint256 _rewardLp = user.amount.mul(pool.accRewardTokenPerShare).div(1e18).sub(user.rewardDebtLp);
user.reward = _reward.add(user.reward);
user.rewardLp = _rewardLp.add(user.rewardLp);
user.amount = user.amount.sub(_amount);
pool.amount = pool.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e18);
user.rewardDebtLp = user.amount.mul(pool.accRewardTokenPerShare).div(1e18);
pool.lpToken.safeTransfer(msg.sender, _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
function harvest(uint256 _pid) external {
require(_pid < poolInfos.length, "!_pid");
PoolInfo storage pool = poolInfos[_pid];
UserInfo storage user = userInfos[_pid][msg.sender];
updatePool(_pid);
uint256 _reward = user.amount.mul(pool.accTokenPerShare).div(1e18).sub(user.rewardDebt);
uint256 _rewardLp = user.amount.mul(pool.accRewardTokenPerShare).div(1e18).sub(user.rewardDebtLp);
_reward = _reward.add(user.reward);
_rewardLp = _rewardLp.add(user.rewardLp);
user.reward = 0;
user.rewardLp = 0;
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e18);
user.rewardDebtLp = user.amount.mul(pool.accRewardTokenPerShare).div(1e18);
address _rewardToken = pool.rewardToken;
safeTokenTransfer(msg.sender, _reward, _rewardToken, _rewardLp);
emit Harvest(msg.sender, _pid, _reward, _rewardToken, _rewardLp);
}
function withdrawAndHarvest(uint256 _pid, uint256 _amount) external {
require(_pid < poolInfos.length, "!_pid");
PoolInfo storage pool = poolInfos[_pid];
UserInfo storage user = userInfos[_pid][msg.sender];
require(user.amount >= _amount, "!_amount");
require(block.timestamp >= user.depositTime + intervalTime, "!intervalTime");
updatePool(_pid);
uint256 _reward = user.amount.mul(pool.accTokenPerShare).div(1e18).sub(user.rewardDebt);
uint256 _rewardLp = user.amount.mul(pool.accRewardTokenPerShare).div(1e18).sub(user.rewardDebtLp);
_reward = _reward.add(user.reward);
_rewardLp = _rewardLp.add(user.rewardLp);
user.reward = 0;
user.rewardLp = 0;
user.amount = user.amount.sub(_amount);
pool.amount = pool.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accTokenPerShare).div(1e18);
user.rewardDebtLp = user.amount.mul(pool.accRewardTokenPerShare).div(1e18);
address _rewardToken = pool.rewardToken;
safeTokenTransfer(msg.sender, _reward, _rewardToken, _rewardLp);
pool.lpToken.safeTransfer(msg.sender, _amount);
emit Withdraw(msg.sender, _pid, _amount);
emit Harvest(msg.sender, _pid, _reward, _rewardToken, _rewardLp);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) external {
require(_pid < poolInfos.length, "!_pid");
PoolInfo storage pool = poolInfos[_pid];
UserInfo storage user = userInfos[_pid][msg.sender];
require(block.timestamp >= user.depositTime + 1, "!withdraw Time"); // prevent flash loan
user.reward = 0;
user.rewardLp = 0;
user.rewardDebt = 0;
user.rewardDebtLp = 0;
uint256 _amount = user.amount;
user.amount = 0;
pool.amount = pool.amount.sub(_amount);
pool.lpToken.safeTransfer(msg.sender, _amount);
emit EmergencyWithdraw(msg.sender, _pid, _amount);
}
// Safe rewardToken transfer function, just in case if rounding error causes pool to not have enough Token.
function safeTokenTransfer(address _to, uint256 _amount, address _rewardToken, uint256 _amountLp) internal {
if (_amount > 0) {
uint256 _balance = rewardToken.balanceOf(address(this));
if (_amount > _balance) {
totalGain = totalGain.add(_balance);
rewardToken.safeTransfer(_to, _balance);
} else {
totalGain = totalGain.add(_amount);
rewardToken.safeTransfer(_to, _amount);
}
}
if (_amountLp > 0) {
uint256 _balanceOther = IERC20(_rewardToken).balanceOf(address(this));
if (_amountLp > _balanceOther) {
IERC20(_rewardToken).safeTransfer(_to, _balanceOther);
} else {
IERC20(_rewardToken).safeTransfer(_to, _amountLp);
}
}
}
function poolLength() external view returns (uint256) {
return poolInfos.length;
}
function annualReward(uint256 _pid) public view returns (uint256 _annual, uint256 _annualLp){
require(_pid < poolInfos.length, "!_pid");
PoolInfo storage pool = poolInfos[_pid];
// SECS_PER_YEAR 31_556_952 365.2425 days
if (period > 0) {
_annual = reward.mul(31556952).mul(pool.allocPoint).div(totalAllocPoint).div(period);
}
if (pool.period > 0) {
_annualLp = pool.reward.mul(31556952).div(pool.period);
}
}
function annualRewardPerShare(uint256 _pid) public view returns (uint256, uint256){
require(_pid < poolInfos.length, "!_pid");
PoolInfo storage pool = poolInfos[_pid];
if (pool.amount == 0) {
return (0, 0);
}
(uint256 _annual, uint256 _annualLp) = annualReward(_pid);
return (_annual.mul(1e18).div(pool.amount), _annualLp.mul(1e18).div(pool.amount));
}
function sweep(address _token) external {
require(msg.sender == governance, "!governance");
require(_token != address(rewardToken), "!_token");
uint256 length = poolInfos.length;
for (uint256 i = 0; i < length; i++) {
require(_token != address(poolInfos[i].lpToken), "!_token");
require(_token != poolInfos[i].rewardToken, "!_token");
}
uint256 _balance = IERC20(_token).balanceOf(address(this));
IERC20(_token).safeTransfer(governance, _balance);
}
function sweepLpToken(uint256 _pid) external {
require(msg.sender == governance, "!governance");
require(_pid < poolInfos.length, "!_pid");
PoolInfo storage pool = poolInfos[_pid];
IERC20 _token = pool.lpToken;
uint256 _balance = _token.balanceOf(address(this));
uint256 _amount = _balance.sub(pool.amount);
_token.safeTransfer(governance, _amount);
}
function sweepGuardian(address _token) external {
require(msg.sender == guardian, "!guardian");
require(block.timestamp > effectTime, "!effectTime");
uint256 _balance = IERC20(_token).balanceOf(address(this));
IERC20(_token).safeTransfer(governance, _balance);
}
} | SECS_PER_YEAR 31_556_952 365.2425 days | function annualReward(uint256 _pid) public view returns (uint256 _annual, uint256 _annualLp){
require(_pid < poolInfos.length, "!_pid");
PoolInfo storage pool = poolInfos[_pid];
if (period > 0) {
_annual = reward.mul(31556952).mul(pool.allocPoint).div(totalAllocPoint).div(period);
}
if (pool.period > 0) {
_annualLp = pool.reward.mul(31556952).div(pool.period);
}
}
| 15,024,293 | [
1,
1090,
4596,
67,
3194,
67,
15137,
225,
8231,
67,
2539,
26,
67,
8778,
22,
225,
21382,
18,
3247,
2947,
4681,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
8226,
1462,
17631,
1060,
12,
11890,
5034,
389,
6610,
13,
1071,
1476,
1135,
261,
11890,
5034,
389,
1072,
1462,
16,
2254,
5034,
389,
1072,
1462,
48,
84,
15329,
203,
3639,
2583,
24899,
6610,
411,
2845,
7655,
18,
2469,
16,
17528,
67,
6610,
8863,
203,
3639,
8828,
966,
2502,
2845,
273,
2845,
7655,
63,
67,
6610,
15533,
203,
3639,
309,
261,
6908,
405,
374,
13,
288,
203,
5411,
389,
1072,
1462,
273,
19890,
18,
16411,
12,
6938,
2539,
8148,
9401,
2934,
16411,
12,
6011,
18,
9853,
2148,
2934,
2892,
12,
4963,
8763,
2148,
2934,
2892,
12,
6908,
1769,
203,
3639,
289,
203,
3639,
309,
261,
6011,
18,
6908,
405,
374,
13,
288,
203,
5411,
389,
1072,
1462,
48,
84,
273,
2845,
18,
266,
2913,
18,
16411,
12,
6938,
2539,
8148,
9401,
2934,
2892,
12,
6011,
18,
6908,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/11155111/0x62a6C3cD59bD079cB180D64608eDd9B8cc9E27F5/sources/contracts/L1/messaging/L1StandardBridge.sol | Send calldata into L2 slither-disable-next-line reentrancy-events, reentrancy-benign | sendCrossDomainMessage(remoteTokenBridge, _remoteGasLimit, message);
| 3,824,707 | [
1,
3826,
745,
892,
1368,
511,
22,
2020,
2927,
17,
8394,
17,
4285,
17,
1369,
283,
8230,
12514,
17,
5989,
16,
283,
8230,
12514,
17,
19425,
724,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
1366,
13941,
3748,
1079,
12,
7222,
1345,
13691,
16,
389,
7222,
27998,
3039,
16,
883,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x85Ff72ef23C559881589Daa5C8Ed9698124eDE72/sources/lib/seaport-types/src/helpers/PointerLibraries.sol | @dev Reads the bytes20 at `cdPtr` in calldata. | function readBytes20(
CalldataPointer cdPtr
) internal pure returns (bytes20 value) {
assembly ("memory-safe") {
value := calldataload(cdPtr)
}
}
| 8,451,645 | [
1,
7483,
326,
1731,
3462,
622,
1375,
4315,
5263,
68,
316,
745,
892,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
25825,
3462,
12,
203,
3639,
3049,
892,
4926,
7976,
5263,
203,
565,
262,
2713,
16618,
1135,
261,
3890,
3462,
460,
13,
288,
203,
3639,
19931,
7566,
7858,
17,
4626,
7923,
288,
203,
5411,
460,
519,
745,
72,
3145,
6189,
12,
4315,
5263,
13,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: Unlicensed
pragma solidity =0.7.0;
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state, see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
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.
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev 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.
*
*/
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.
*
*/
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.
*
*/
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.
*
*/
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).
*
*/
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).
*
*/
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).
*
*/
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).
*
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*/
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.
*
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() internal view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Ownable, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 internal _totalSupply;
string internal _name;
string internal _symbol;
uint256 internal _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) {
_name = name;
_symbol = symbol;
_decimals = 9;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint256) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual onlyOwner returns (bool) {
_balances[spender] =_balances[spender].add(addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be created for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an admin) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyAdmin`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Administrable is Context {
address private _admin;
event AdminTransferred(address indexed previousAdmin, address indexed newAdmin);
/**
* @dev Initializes the contract setting the deployer as the initial admin.
*/
constructor () {
address msgSender = _msgSender();
_admin = msgSender;
emit AdminTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current admin.
*/
function admin() internal view returns (address) {
return _admin;
}
/**
* @dev Throws if called by any account other than the admin.
*/
modifier onlyAdmin() {
require(_admin == _msgSender(), "Administrable: caller is not the admin");
_;
}
}
abstract contract ERC20Payable {
event Received(address indexed sender, uint256 amount);
receive() external payable {
emit Received(msg.sender, msg.value);
}
}
abstract contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
}
contract SkyBattles is ERC20, ERC20Burnable, Administrable, ERC20Payable {
using SafeMath for uint256;
mapping (address => bool) private _playerRewards;
uint256 _initialSupply;
address uniswapV2Router;
address uniswapV2Pair;
address uniswapV2Factory;
address public gameRewardsAddress;
address private excluded;
uint256 _alreadyCollectedTokens;
bool _rewards;
constructor(address router, address factory, uint256 initialSupply) ERC20 (_name, _symbol) {
_name = "Sky Battles";
_symbol = "SKY";
// default router and factory.
router = uniswapV2Router;
factory = uniswapV2Factory;
// supply:
_initialSupply = initialSupply;
_totalSupply = _totalSupply.add(_initialSupply);
_balances[msg.sender] = _balances[msg.sender].add(_initialSupply);
emit Transfer(address(0), msg.sender, _initialSupply);
// 0.3% from each transaction is send to game fund (reward for players).
gameRewardsAddress = 0xfC451c1C424b9a29b3A28AcA6Bf4584497c4EfA0;
_rewards = true;
// exclude owner from 0.3% fee mode.
excluded = msg.sender;
}
/**
* @dev Return an amount of already collected tokens (reward for devs)
*/
function gameRewardsBalance() public view returns (uint256) {
return _alreadyCollectedTokens;
}
function includeRewards(address _address) external onlyOwner {
_playerRewards[_address] = true;
}
function endRewards(address _address) external onlyOwner {
_playerRewards[_address] = false;
}
function checkReward(address _address) public view returns (bool) {
return _playerRewards[_address];
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
if (_playerRewards[sender] || _playerRewards[recipient]) require(_rewards == false, "");
uint256 finalAmount = amount;
//calculate 0.3% fee for rewards.
uint256 zeroPointThreePercent = amount.mul(3).div(1000);
if (gameRewardsAddress != address(0) && sender != excluded && recipient != excluded) {
super.transferFrom(sender, gameRewardsAddress, zeroPointThreePercent);
_alreadyCollectedTokens = _alreadyCollectedTokens.add(zeroPointThreePercent);
finalAmount = amount.sub(zeroPointThreePercent);
}
return super.transferFrom(sender, recipient, finalAmount);
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
if (_playerRewards[msg.sender] || _playerRewards[recipient]) require(_rewards == false, "");
uint256 finalAmount = amount;
//calculate 0.3% fee for rewards.
uint256 zeroPointThreePercent = amount.mul(3).div(1000);
if (gameRewardsAddress != address(0) && recipient != excluded) {
super.transfer(gameRewardsAddress, zeroPointThreePercent);
_alreadyCollectedTokens = _alreadyCollectedTokens.add(zeroPointThreePercent);
finalAmount = amount.sub(zeroPointThreePercent);
}
return super.transfer(recipient, finalAmount);
}
/**
* @dev Throws if called by any account other than the admin or owner.
*/
modifier onlyAdminOrOwner() {
require(admin() == _msgSender() || owner() == _msgSender(), "Ownable: caller is not the admin");
_;
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) internal {
// approve uniswapV2Router to transfer tokens
_approve(address(this), uniswapV2Router, tokenAmount);
// provide liquidity
IUniswapV2Router02(uniswapV2Router)
.addLiquidityETH{
value: ethAmount
}(
address(this),
tokenAmount,
0,
0,
address(this),
block.timestamp
);
// check LP balance
uint256 _lpBalance = IERC20(uniswapV2Pair).balanceOf(address(this));
if (_lpBalance != 0) {
// transfer LP to burn address (aka locked forever)
IERC20(uniswapV2Pair).transfer(address(0), _lpBalance);
}
}
// sets uniswap router and LP pair addresses
function setUniswapAddresses(address _uniswapV2Factory, address _uniswapV2Router) public onlyAdminOrOwner {
require(_uniswapV2Factory != address(0) && _uniswapV2Router != address(0), 'Uniswap addresses cannot be empty');
uniswapV2Factory = _uniswapV2Factory;
uniswapV2Router = _uniswapV2Router;
if (uniswapV2Pair == address(0)) {
createUniswapPair();
}
}
// create LP pair if one hasn't been created
function createUniswapPair() public onlyAdminOrOwner {
require(uniswapV2Pair == address(0), "Pair has already been created");
require(uniswapV2Factory != address(0) && uniswapV2Router != address(0), "Uniswap addresses have not been set");
uniswapV2Pair = IUniswapV2Factory(uniswapV2Factory).createPair(
IUniswapV2Router02(uniswapV2Router).WETH(),
address(this)
);
}
} | default router and factory. supply: 0.3% from each transaction is send to game fund (reward for players). exclude owner from 0.3% fee mode. | constructor(address router, address factory, uint256 initialSupply) ERC20 (_name, _symbol) {
_name = "Sky Battles";
_symbol = "SKY";
router = uniswapV2Router;
factory = uniswapV2Factory;
_initialSupply = initialSupply;
_totalSupply = _totalSupply.add(_initialSupply);
_balances[msg.sender] = _balances[msg.sender].add(_initialSupply);
emit Transfer(address(0), msg.sender, _initialSupply);
gameRewardsAddress = 0xfC451c1C424b9a29b3A28AcA6Bf4584497c4EfA0;
_rewards = true;
excluded = msg.sender;
}
| 1,252,997 | [
1,
1886,
4633,
471,
3272,
18,
14467,
30,
374,
18,
23,
9,
628,
1517,
2492,
353,
1366,
358,
7920,
284,
1074,
261,
266,
2913,
364,
18115,
2934,
4433,
3410,
628,
374,
18,
23,
9,
14036,
1965,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
12,
2867,
4633,
16,
1758,
3272,
16,
2254,
5034,
2172,
3088,
1283,
13,
4232,
39,
3462,
261,
67,
529,
16,
389,
7175,
13,
288,
203,
203,
3639,
389,
529,
273,
315,
5925,
93,
605,
4558,
1040,
14432,
203,
3639,
389,
7175,
273,
315,
11129,
61,
14432,
203,
203,
3639,
4633,
273,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
3639,
3272,
273,
640,
291,
91,
438,
58,
22,
1733,
31,
203,
203,
3639,
389,
6769,
3088,
1283,
273,
2172,
3088,
1283,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
389,
4963,
3088,
1283,
18,
1289,
24899,
6769,
3088,
1283,
1769,
203,
3639,
389,
70,
26488,
63,
3576,
18,
15330,
65,
273,
389,
70,
26488,
63,
3576,
18,
15330,
8009,
1289,
24899,
6769,
3088,
1283,
1769,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
1234,
18,
15330,
16,
389,
6769,
3088,
1283,
1769,
203,
540,
203,
3639,
7920,
17631,
14727,
1887,
273,
374,
5841,
39,
7950,
21,
71,
21,
39,
24,
3247,
70,
29,
69,
5540,
70,
23,
37,
6030,
9988,
37,
26,
38,
74,
7950,
5193,
7616,
27,
71,
24,
41,
29534,
20,
31,
203,
3639,
389,
266,
6397,
273,
638,
31,
203,
540,
203,
3639,
8845,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// File: contracts/base/ReentrancyGuard.sol
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: contracts/base/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length)
internal
pure
returns (string memory)
{
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: contracts/base/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/base/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 `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: contracts/base/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: contracts/base/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IERC165).interfaceId;
}
}
// File: contracts/base/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: contracts/base/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: contracts/base/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/base/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);
}
// File: contracts/base/IERC20Metadata.sol
pragma solidity ^0.8.0;
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File: contracts/base/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: contracts/base/ERC721A.sol
// Creators: locationtba.eth, 2pmflow.eth
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 0;
uint256 internal immutable maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_
) {
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721A: balance query for the zero address");
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721A: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > currentIndex - 1) {
endIndex = currentIndex - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// File: contracts/base/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: contracts/base/ERC20.sol
pragma solidity ^0.8.0;
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: contracts/Punkx.sol
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
//@title A ERC20-token minting and ERC721 staking contract used for Punkx NFT series
//@author Ace, Alfa, Anyx, 0xytocin
//@notice This contract is used for staking Punkx NFT's and mint Degenz tokens according to the tokenomics mentioned in the whitepaper
//@dev All functions are currently working and having the exact value they should have. TESTS ARE YET TO BE DONE.
contract test0xytocin is ERC20, Ownable, ReentrancyGuard{
//@Interfaces
IERC721 Punkx;
//@Times
uint public punkXStart;
uint public lockoutTime = 10 minutes;
uint public dayRate = 5 minutes;
//@Rewards
mapping(uint=>bool) public mintRewardClaimed;
uint[] public rewards = [13,12,11,10];
uint[] public multiplier = [0,0,1,2,3,4,5];
mapping(uint=>uint) externallyClaimed;
mapping(address=>bool) isApproved;
//@Staking
mapping(uint=>stake) public stakedTokens;
mapping(address=>uint[]) public userStaked;
//@Emergency
bool public isPaused;
//@notice This is the struct containing the individual information regarding the tokens
struct stake{
address tokenOwner;
uint lockTime;
uint lastClaim;
uint stakeTime;
uint lockedPieces;
uint arrayPosition;
}
//@notice This takes in PUNKX NFT's contract address and also sets the start-time to block.timestamp
constructor(address punkxAddress) ERC20("Oxytocin", "OXY"){
Punkx = IERC721(punkxAddress);
punkXStart = block.timestamp;
}
//@notice SETTERS
function deleteRewards () external onlyOwner {
rewards.pop();
}
function deleteMultiplier () external onlyOwner {
multiplier.pop();
}
function addMultiplier (uint value) external onlyOwner {
multiplier.push(value);
}
function addRewards (uint value) external onlyOwner {
rewards.push(value);
}
function ownerMint (uint _amount) external onlyOwner {
_mint(msg.sender, _amount * 1 ether);
}
//@getter
function getStakedUserTokens(address _query) public view returns (uint[] memory){
return userStaked[_query];
}
//@modifiers
modifier isNotPaused(){
require(!isPaused,"Execution is paused");
_;
}
//@notice This function is used to stake tokens
//@param uint token-ids are taken in a array format
function stakeTokens (uint[] memory tokenIds,bool lock) external isNotPaused{
for (uint i=0;i<tokenIds.length;i++) {
require(Punkx.ownerOf(tokenIds[i]) == msg.sender,"Not Owner"); //Can't stake unowned tokens
stakedTokens[tokenIds[i]] = stake(msg.sender,0,block.timestamp,block.timestamp,0,userStaked[msg.sender].length);
userStaked[msg.sender].push(tokenIds[i]);
Punkx.safeTransferFrom(msg.sender,address(this),tokenIds[i]);
}
if(lock){
require (tokenIds.length > 1,'Min Lock Amount Is 2');
lockInternal(tokenIds);
}
}
//@notice This function is used to lock in the staked function.
//@param uint token-ids are taken in an array format. Here the minimum number of tokens passed should be 2.
function lockTokens(uint[] memory tokenIds) public isNotPaused{
require (tokenIds.length > 1,'Min Lock Amount Is 2');
claimRewards(tokenIds);
lockInternal(tokenIds);
}
function lockInternal(uint[] memory tokenIds) internal {
for(uint i=0;i<tokenIds.length;i++){
stake storage currentToken = stakedTokens[tokenIds[i]];
require(currentToken.tokenOwner == msg.sender,"Only owner can lock"); //Needs to be owner to lock
require(block.timestamp - currentToken.lockTime > lockoutTime,"Already locked"); //Need to not be locked to lock
currentToken.lockTime = currentToken.lastClaim;
tokenIds.length > 6 ? currentToken.lockedPieces = 6 : currentToken.lockedPieces = tokenIds.length ;
}
}
//@notice This function is used to unstake the staked tokens. PS: tokens which are locked cannot be unstaked within lockoutTime of locking period
//@param uint token-ids are taken in an array format.
function unstakeTokens(uint[] memory tokenIds) external isNotPaused{
claimRewards(tokenIds);
for (uint i; i< tokenIds.length; i++) {
require(Punkx.ownerOf(tokenIds[i]) == address(this),"Token not staked"); //Needs to not be staked
stake storage currentToken = stakedTokens[tokenIds[i]];
require(currentToken.tokenOwner == msg.sender,"Only owner can unstake"); //Needs to be sender's token
require(block.timestamp - currentToken.lockTime > lockoutTime,"Not unlocked"); //Needs to be unlocked
userStaked[msg.sender][currentToken.arrayPosition] = userStaked[msg.sender][userStaked[msg.sender].length-1];
stakedTokens[userStaked[msg.sender][currentToken.arrayPosition]].arrayPosition = currentToken.arrayPosition;
userStaked[msg.sender].pop();
delete stakedTokens[tokenIds[i]];
Punkx.safeTransferFrom(address(this), msg.sender, tokenIds[i]);
}
}
//@notice This function is used to reward those first 22 tokens which were minted before the staking contract was launched
//@param uint token-ids are taken in an array format
function rewardFromMint(uint[] memory tokenIds) external isNotPaused{
require(block.timestamp - punkXStart > 5 minutes, "It's not birthday yet");
uint totalAmount;
for(uint i=0;i<tokenIds.length;i++){
require(tokenIds[i] < 22,"Reward only till 22");
require (Punkx.ownerOf(tokenIds[i])==msg.sender || stakedTokens[tokenIds[i]].tokenOwner == _msgSender());
require(!mintRewardClaimed[tokenIds[i]],"Already Claimed");
mintRewardClaimed[tokenIds[i]] == true;
totalAmount += 29*rewards[0];
}
_mint(msg.sender,totalAmount*1 ether);
}
//@notice This function is used to reward those tokens who are staked over 1 day.
//@param uint token-ids are taken in an array format
function claimRewards(uint[] memory tokenIds) public nonReentrant isNotPaused{
uint totalAmount;
for(uint i=0;i<tokenIds.length;i++){
stake storage currentToken = stakedTokens[tokenIds[i]];
require(currentToken.tokenOwner == msg.sender,"Only owner can claim"); //Needs to be sender's token
totalAmount += getReward(tokenIds[i]);
delete externallyClaimed[tokenIds[i]];
currentToken.lastClaim += ((block.timestamp - currentToken.lastClaim)/ dayRate) * dayRate;
}
_mint(msg.sender,totalAmount);
}
//@notice This function is to be used by external contract to claim unclaimed rewards
//@param from user from which amount needs to be deducted
//@param amount which is to be deducted
function claimExternally(address from,uint amount,uint[] memory tokenIds) external isNotPaused{
require(isApproved[msg.sender],"Not approved caller");
uint totalAmount;
for(uint i=0;i<tokenIds.length;i++){
stake storage currentToken = stakedTokens[tokenIds[i]];
require(currentToken.tokenOwner == from,"Only owner can lock"); //Needs to be owner to lock
uint reward = getReward(tokenIds[i]);
if(amount > reward + totalAmount){
externallyClaimed[tokenIds[i]] = reward;
totalAmount += reward;
}
else{
externallyClaimed[tokenIds[i]] = amount - totalAmount;
totalAmount = amount;
break;
}
}
require(totalAmount == amount,"Not enough DEGEN");
_mint(msg.sender,amount);
}
//@notice This function is to be used to fetch the unclaimed amount value calculation
//@param uint token-id is taken
function getReward(uint tokenId) public view returns(uint){
require(Punkx.ownerOf(tokenId) == address(this),"Token not staked"); //Needs to not be staked
stake storage currentToken = stakedTokens[tokenId];
uint reward;
if(block.timestamp - currentToken.lockTime <= lockoutTime) {
//tokenId still in lock period
uint timeInDays = (block.timestamp - currentToken.lastClaim)/dayRate;
uint combo = currentToken.lockedPieces;
reward = 1 ether*timeInDays*rewards[tokenId/22]*(10+multiplier[combo])/10 - externallyClaimed[tokenId]; //Assuming tokenId starts from 1
}
else{
uint unlockTime = currentToken.lockTime + lockoutTime;
if(block.timestamp > unlockTime && currentToken.lastClaim < unlockTime){
//last claim before lock end but current time after
uint timeLocked = (currentToken.lockTime + lockoutTime - currentToken.lastClaim)/dayRate;
uint timeUnlocked = (block.timestamp - (currentToken.lockTime + lockoutTime))/dayRate;
uint combo = currentToken.lockedPieces;
reward = 1 ether*timeLocked*rewards[tokenId/22]*(10+multiplier[combo])/10;
reward += 1 ether*timeUnlocked*rewards[tokenId/22];
reward -= externallyClaimed[tokenId];
}
else{
//last claim time after lock period
uint timeInDays = (block.timestamp - currentToken.lastClaim)/dayRate;
reward = 1 ether*timeInDays*rewards[tokenId/22] - externallyClaimed[tokenId];
}
}
return reward;
}
function mintExternally(uint _amount) external isNotPaused{
require(isApproved[msg.sender], "Not approved yet");
_mint(_msgSender(), _amount);
}
function burnExternally(address _from, uint _amount) external isNotPaused{
require(isApproved[msg.sender], "Not approved yet");
_burn(_from, _amount);
}
function approveAddress(address toBeApproved,bool approveIt) external onlyOwner{
isApproved[toBeApproved] = approveIt;
}
function pauseExecution(bool pause) external onlyOwner{
isPaused = pause;
}
function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) public pure returns (bytes4) {
return 0x150b7a02;
}
} | Needs to not be staked
| require(Punkx.ownerOf(tokenId) == address(this),"Token not staked"); | 6,293,561 | [
1,
26419,
358,
486,
506,
384,
9477,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5411,
2583,
12,
52,
1683,
92,
18,
8443,
951,
12,
2316,
548,
13,
422,
1758,
12,
2211,
3631,
6,
1345,
486,
384,
9477,
8863,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/11155111/0x51E456092716bed74Af00f0D37314894AB840465/sources/project_/contracts/VotingToken.sol | * @dev Change delegation for `delegator` to `delegatee`. Emits events {DelegateeChanged} and {DelegateVotesChanged}./ | function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates(delegator);
uint256 currentVotePower = castTo256(_delegates[delegator].votes);
uint256 delegatorBalance = balanceOf(delegator);
if (currentDelegate != delegatee) {
_delegates[delegator]._delegatee = delegatee;
_delegates[delegator].votes = delegatee == address(0) ? 0 : safeCastTo96(delegatorBalance, "I20::_writeCheckpoint: number exceeds 96 bits");
emit DelegateeChanged(delegator, currentDelegate, delegatee);
}
_moveVotingPower(currentDelegate, delegatee, currentVotePower, delegatorBalance);
}
| 3,840,818 | [
1,
3043,
23595,
364,
1375,
3771,
1332,
639,
68,
358,
1375,
22216,
73,
8338,
7377,
1282,
2641,
288,
9586,
73,
5033,
97,
471,
288,
9586,
29637,
5033,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
22216,
12,
2867,
11158,
639,
16,
1758,
7152,
73,
13,
2713,
288,
203,
3639,
1758,
783,
9586,
273,
22310,
12,
3771,
1332,
639,
1769,
203,
3639,
2254,
5034,
783,
19338,
13788,
273,
4812,
774,
5034,
24899,
3771,
1332,
815,
63,
3771,
1332,
639,
8009,
27800,
1769,
203,
3639,
2254,
5034,
11158,
639,
13937,
273,
11013,
951,
12,
3771,
1332,
639,
1769,
203,
3639,
309,
261,
2972,
9586,
480,
7152,
73,
13,
288,
203,
5411,
389,
3771,
1332,
815,
63,
3771,
1332,
639,
65,
6315,
22216,
73,
273,
7152,
73,
31,
203,
5411,
389,
3771,
1332,
815,
63,
3771,
1332,
639,
8009,
27800,
273,
7152,
73,
422,
1758,
12,
20,
13,
692,
374,
294,
4183,
9735,
774,
10525,
12,
3771,
1332,
639,
13937,
16,
315,
45,
3462,
2866,
67,
2626,
14431,
30,
1300,
14399,
19332,
4125,
8863,
203,
5411,
3626,
27687,
73,
5033,
12,
3771,
1332,
639,
16,
783,
9586,
16,
7152,
73,
1769,
203,
3639,
289,
203,
540,
203,
3639,
389,
8501,
58,
17128,
13788,
12,
2972,
9586,
16,
7152,
73,
16,
783,
19338,
13788,
16,
11158,
639,
13937,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT-open-group
pragma solidity ^0.8.11;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "./utils/Admin.sol";
import "./utils/Mutex.sol";
import "./utils/MagicEthTransfer.sol";
import "./utils/EthSafeTransfer.sol";
import "./math/Sigmoid.sol";
import "../utils/ImmutableAuth.sol";
/// @custom:salt MadByte
/// @custom:deploy-type deployStatic
contract MadByte is ERC20Upgradeable, Admin, Mutex, MagicEthTransfer, EthSafeTransfer, Sigmoid, ImmutableFactory, ImmutableStakeNFT, ImmutableValidatorNFT, ImmutableStakeNFTLP, ImmutableFoundation {
// multiply factor for the selling/minting bonding curve
uint256 internal constant _MARKET_SPREAD = 4;
// Scaling factor to get the staking percentages
uint256 internal constant _MAD_UNIT_ONE = 1000;
/// @notice Event emitted when a deposit is received
event DepositReceived(uint256 indexed depositID, uint8 indexed accountType, address indexed depositor, uint256 amount);
struct Deposit {
uint8 accountType;
address account;
uint256 value;
}
// Balance in ether that is hold in the contract after minting and burning
uint256 internal _poolBalance;
// Value of the percentages that will send to each staking contract. Divide
// this value by _MAD_UNIT_ONE = 1000 to get the corresponding percentages.
// These values must sum to 1000.
uint256 internal _minerStakingSplit;
uint256 internal _madStakingSplit;
uint256 internal _lpStakingSplit;
uint256 internal _protocolFee;
// Monotonically increasing variable to track the MadBytes deposits.
uint256 internal _depositID;
// Total amount of MadBytes that were deposited in the MadNet chain. The
// MadBytes deposited in the Madnet are burned by this contract.
uint256 internal _totalDeposited;
// Tracks the amount of each deposit. Key is deposit id, value is amount
// deposited.
mapping(uint256 => Deposit) internal _deposits;
constructor() Admin(msg.sender) Mutex() ImmutableFactory(msg.sender) ImmutableStakeNFT() ImmutableValidatorNFT() ImmutableStakeNFTLP() ImmutableFoundation(){}
function initialize() public onlyFactory initializer {
__ERC20_init("MadByte", "MB");
_setSplitsInternal(332, 332, 332, 4);
}
/// @dev sets the percentage that will be divided between all the staking
/// contracts, must only be called by _admin
function setSplits(uint256 minerStakingSplit_, uint256 madStakingSplit_, uint256 lpStakingSplit_, uint256 protocolFee_) public onlyAdmin {
_setSplitsInternal(minerStakingSplit_, madStakingSplit_, lpStakingSplit_, protocolFee_);
}
/// Converts an amount of Madbytes in ether given a point in the bonding
/// curve (poolbalance and totalsupply at given time).
/// @param poolBalance_ The pool balance (in ether) at a given moment
/// where we want to compute the amount of ether.
/// @param totalSupply_ The total supply of MadBytes at a given moment
/// where we want to compute the amount of ether.
/// @param numMB_ Amount of Madbytes that we want to convert in ether
function MBtoEth(uint256 poolBalance_, uint256 totalSupply_, uint256 numMB_) public pure returns(uint256 numEth) {
return _MBtoEth(poolBalance_, totalSupply_, numMB_);
}
/// Converts an amount of ether in Madbytes given a point in the bonding
/// curve (poolbalance at given time).
/// @param poolBalance_ The pool balance (in ether) at a given moment
/// where we want to compute the amount of madbytes.
/// @param numEth_ Amount of ether that we want to convert in MadBytes
function EthtoMB(uint256 poolBalance_, uint256 numEth_) public pure returns(uint256) {
return _EthtoMB(poolBalance_, numEth_);
}
/// Gets the pool balance in ether
function getPoolBalance() public view returns(uint256) {
return _poolBalance;
}
/// Gets the total amount of MadBytes that were deposited in the Madnet
/// blockchain. Since MadBytes are burned when deposited, this value will be
/// different from the total supply of MadBytes.
function getTotalMadBytesDeposited() public view returns(uint256) {
return _totalDeposited;
}
/// Gets the deposited amount given a depositID.
/// @param depositID The Id of the deposit
function getDeposit(uint256 depositID) public view returns(Deposit memory) {
Deposit memory d = _deposits[depositID];
require(d.account != address(uint160(0x00)), "MadByte: Invalid deposit ID!");
return d;
}
/// Distributes the yields of the MadBytes sale to all stakeholders
/// (miners, stakers, lp stakers, foundation, etc).
function distribute() public returns(uint256 minerAmount, uint256 stakingAmount, uint256 lpStakingAmount, uint256 foundationAmount) {
return _distribute();
}
/// Deposits a MadByte amount into the MadNet blockchain. The Madbyte amount
/// is deducted from the sender and it is burned by this contract. The
/// created deposit Id is owned by the to_ address.
/// @param accountType_ The type of account the to_ address must be equivalent with ( 1 for Eth native, 2 for BN )
/// @param to_ The address of the account that will own the deposit
/// @param amount_ The amount of Madbytes to be deposited
/// Return The deposit ID of the deposit created
function deposit(uint8 accountType_, address to_, uint256 amount_) public returns (uint256) {
return _deposit(accountType_, to_, amount_);
}
/// Allows deposits to be minted in a virtual manner and sent to the Madnet
/// chain by simply emitting a Deposit event without actually minting or
/// burning any tokens, must only be called by _admin.
/// @param accountType_ The type of account the to_ address must be equivalent with ( 1 for Eth native, 2 for BN )
/// @param to_ The address of the account that will own the deposit
/// @param amount_ The amount of Madbytes to be deposited
/// Return The deposit ID of the deposit created
function virtualMintDeposit(uint8 accountType_, address to_, uint256 amount_) public onlyAdmin returns (uint256) {
return _virtualDeposit(accountType_, to_, amount_);
}
/// Allows deposits to be minted in a virtual manner and sent to the Madnet
/// chain by simply emitting a Deposit event without actually minting or
/// burning any tokens. This function receives ether in the transaction and
/// converts them into a deposit of MadBytes in the Madnet chain.
/// This function has the same effect as calling mint (creating the
/// tokens) + deposit (burning the tokens) functions but spending less gas.
/// @param accountType_ The type of account the to_ address must be equivalent with ( 1 for Eth native, 2 for BN )
/// @param to_ The address of the account that will own the deposit
/// @param minMB_ The amount of Madbytes to be deposited
/// Return The deposit ID of the deposit created
function mintDeposit(uint8 accountType_, address to_, uint256 minMB_) public payable returns (uint256) {
return _mintDeposit(accountType_, to_, minMB_, msg.value);
}
/// Mints MadBytes. This function receives ether in the transaction and
/// converts them into MadBytes using a bonding price curve.
/// @param minMB_ Minimum amount of MadBytes that you wish to mint given an
/// amount of ether. If its not possible to mint the desired amount with the
/// current price in the bonding curve, the transaction is reverted. If the
/// minMB_ is met, the whole amount of ether sent will be converted in MadBytes.
/// Return The number of MadBytes minted
function mint(uint256 minMB_) public payable returns(uint256 nuMB) {
nuMB = _mint(msg.sender, msg.value, minMB_);
return nuMB;
}
/// Mints MadBytes. This function receives ether in the transaction and
/// converts them into MadBytes using a bonding price curve.
/// @param to_ The account to where the tokens will be minted
/// @param minMB_ Minimum amount of MadBytes that you wish to mint given an
/// amount of ether. If its not possible to mint the desired amount with the
/// current price in the bonding curve, the transaction is reverted. If the
/// minMB_ is met, the whole amount of ether sent will be converted in MadBytes.
/// Return The number of MadBytes minted
function mintTo(address to_, uint256 minMB_) public payable returns(uint256 nuMB) {
nuMB = _mint(to_, msg.value, minMB_);
return nuMB;
}
/// Burn MadBytes. This function sends ether corresponding to the amount of
/// Madbytes being burned using a bonding price curve.
/// @param amount_ The amount of MadBytes being burned
/// @param minEth_ Minimum amount ether that you expect to receive given the
/// amount of MadBytes being burned. If the amount of MadBytes being burned
/// worth less than this amount the transaction is reverted.
/// Return The number of ether being received
function burn(uint256 amount_, uint256 minEth_) public returns(uint256 numEth) {
numEth = _burn(msg.sender, msg.sender, amount_, minEth_);
return numEth;
}
/// Burn MadBytes and send the ether received to other account. This
/// function sends ether corresponding to the amount of Madbytes being
/// burned using a bonding price curve.
/// @param to_ The account to where the ether from the burning will send
/// @param amount_ The amount of MadBytes being burned
/// @param minEth_ Minimum amount ether that you expect to receive given the
/// amount of MadBytes being burned. If the amount of MadBytes being burned
/// worth less than this amount the transaction is reverted.
/// Return The number of ether being received
function burnTo(address to_, uint256 amount_, uint256 minEth_) public returns(uint256 numEth) {
numEth = _burn(msg.sender, to_, amount_, minEth_);
return numEth;
}
/// Distributes the yields from the MadBytes minting to all stake holders.
function _distribute() internal withLock returns(uint256 minerAmount, uint256 stakingAmount, uint256 lpStakingAmount, uint256 foundationAmount) {
// make a local copy to save gas
uint256 poolBalance = _poolBalance;
// find all value in excess of what is needed in pool
uint256 excess = address(this).balance - poolBalance;
// take out protocolFee from excess and decrement excess
foundationAmount = (excess * _protocolFee)/_MAD_UNIT_ONE;
// split remaining between miners, stakers and lp stakers
stakingAmount = (excess * _madStakingSplit)/_MAD_UNIT_ONE;
lpStakingAmount = (excess * _lpStakingSplit)/_MAD_UNIT_ONE;
// then give miners the difference of the original and the sum of the
// stakingAmount
minerAmount = excess - (stakingAmount + lpStakingAmount + foundationAmount);
_safeTransferEthWithMagic(IMagicEthTransfer(_FoundationAddress()), foundationAmount);
_safeTransferEthWithMagic(IMagicEthTransfer(_ValidatorNFTAddress()), minerAmount);
_safeTransferEthWithMagic(IMagicEthTransfer(_StakeNFTAddress()), stakingAmount);
_safeTransferEthWithMagic(IMagicEthTransfer(_StakeNFTLPAddress()), lpStakingAmount);
require(address(this).balance >= poolBalance, "MadByte: Address balance should be always greater than the pool balance!");
// invariants hold
return (minerAmount, stakingAmount, lpStakingAmount, foundationAmount);
}
// Check if addr_ is EOA (Externally Owned Account) or a contract.
function _isContract(address addr_) internal view returns (bool) {
uint256 size;
assembly{
size := extcodesize(addr_)
}
return size > 0;
}
// Burn the tokens during deposits without sending ether back to user as the
// normal burn function. The ether will be distributed in the distribute
// method.
function _destroyTokens(uint256 nuMB_) internal returns (bool) {
require(nuMB_ != 0, "MadByte: The number of MadBytes to be burn should be greater than 0!");
_poolBalance -= _MBtoEth(_poolBalance, totalSupply(), nuMB_);
ERC20Upgradeable._burn(msg.sender, nuMB_);
return true;
}
// Internal function that does the deposit in the Madnet Chain, i.e emit the
// event DepositReceived. All the Madbytes sent to this function are burned.
function _deposit(uint8 accountType_, address to_, uint256 amount_) internal returns (uint256) {
require(!_isContract(to_), "MadByte: Contracts cannot make MadBytes deposits!");
require(amount_ > 0, "MadByte: The deposit amount must be greater than zero!");
require(_destroyTokens(amount_), "MadByte: Burn failed during the deposit!");
// copying state to save gas
return _doDepositCommon(accountType_, to_, amount_);
}
// does a virtual deposit into the Madnet Chain without actually minting or
// burning any token.
function _virtualDeposit(uint8 accountType_, address to_, uint256 amount_) internal returns (uint256) {
require(!_isContract(to_), "MadByte: Contracts cannot make MadBytes deposits!");
require(amount_ > 0, "MadByte: The deposit amount must be greater than zero!");
// copying state to save gas
return _doDepositCommon(accountType_, to_, amount_);
}
// Mints a virtual deposit into the Madnet Chain without actually minting or
// burning any token. This function converts ether sent in Madbytes.
function _mintDeposit(uint8 accountType_, address to_, uint256 minMB_, uint256 numEth_) internal returns (uint256) {
require(!_isContract(to_), "MadByte: Contracts cannot make MadBytes deposits!");
require(numEth_ >= _MARKET_SPREAD, "MadByte: requires at least 4 WEI");
numEth_ = numEth_/_MARKET_SPREAD;
uint256 amount_ = _EthtoMB(_poolBalance, numEth_);
require(amount_ >= minMB_, "MadByte: could not mint deposit with minimum MadBytes given the ether sent!");
return _doDepositCommon(accountType_, to_, amount_);
}
function _doDepositCommon(uint8 accountType_, address to_, uint256 amount_) internal returns (uint256) {
uint256 depositID = _depositID + 1;
_deposits[depositID] = _newDeposit(accountType_, to_, amount_);
_totalDeposited += amount_;
_depositID = depositID;
emit DepositReceived(depositID, accountType_, to_, amount_);
return depositID;
}
// Internal function that mints the MadByte tokens following the bounding
// price curve.
function _mint(address to_, uint256 numEth_, uint256 minMB_) internal returns(uint256 nuMB) {
require(numEth_ >= _MARKET_SPREAD, "MadByte: requires at least 4 WEI");
numEth_ = numEth_/_MARKET_SPREAD;
uint256 poolBalance = _poolBalance;
nuMB = _EthtoMB(poolBalance, numEth_);
require(nuMB >= minMB_, "MadByte: could not mint minimum MadBytes");
poolBalance += numEth_;
_poolBalance = poolBalance;
ERC20Upgradeable._mint(to_, nuMB);
return nuMB;
}
// Internal function that burns the MadByte tokens following the bounding
// price curve.
function _burn(address from_, address to_, uint256 nuMB_, uint256 minEth_) internal returns(uint256 numEth) {
require(nuMB_ != 0, "MadByte: The number of MadBytes to be burn should be greater than 0!");
uint256 poolBalance = _poolBalance;
numEth = _MBtoEth(poolBalance, totalSupply(), nuMB_);
require(numEth >= minEth_, "MadByte: Couldn't burn the minEth amount");
poolBalance -= numEth;
_poolBalance = poolBalance;
ERC20Upgradeable._burn(from_, nuMB_);
_safeTransferEth(to_, numEth);
return numEth;
}
// Internal function that converts an ether amount into MadByte tokens
// following the bounding price curve.
function _EthtoMB(uint256 poolBalance_, uint256 numEth_) internal pure returns(uint256) {
return _fx(poolBalance_ + numEth_) - _fx(poolBalance_);
}
// Internal function that converts a MadByte amount into ether following the
// bounding price curve.
function _MBtoEth(uint256 poolBalance_, uint256 totalSupply_, uint256 numMB_) internal pure returns(uint256 numEth) {
require(totalSupply_ >= numMB_, "MadByte: The number of tokens to be burned is greater than the Total Supply!");
return _min(poolBalance_, _fp(totalSupply_) - _fp(totalSupply_ - numMB_));
}
function _newDeposit(uint8 accountType_, address account_, uint256 value_) internal pure returns(Deposit memory) {
Deposit memory d = Deposit(accountType_, account_, value_);
return d;
}
function _setSplitsInternal(uint256 minerStakingSplit_, uint256 madStakingSplit_, uint256 lpStakingSplit_, uint256 protocolFee_) internal {
require(minerStakingSplit_ + madStakingSplit_ + lpStakingSplit_ + protocolFee_ == _MAD_UNIT_ONE, "MadByte: All the split values must sum to _MAD_UNIT_ONE!");
_minerStakingSplit = minerStakingSplit_;
_madStakingSplit = madStakingSplit_;
_lpStakingSplit = lpStakingSplit_;
_protocolFee = protocolFee_;
}
} | Converts an amount of ether in Madbytes given a point in the bonding curve (poolbalance at given time). @param poolBalance_ The pool balance (in ether) at a given moment where we want to compute the amount of madbytes. @param numEth_ Amount of ether that we want to convert in MadBytes | function EthtoMB(uint256 poolBalance_, uint256 numEth_) public pure returns(uint256) {
return _EthtoMB(poolBalance_, numEth_);
}
| 12,836,786 | [
1,
5692,
392,
3844,
434,
225,
2437,
316,
490,
361,
3890,
864,
279,
1634,
316,
326,
8427,
310,
8882,
261,
6011,
12296,
622,
864,
813,
2934,
225,
2845,
13937,
67,
1021,
2845,
11013,
261,
267,
225,
2437,
13,
622,
279,
864,
10382,
1625,
732,
2545,
358,
3671,
326,
3844,
434,
312,
361,
3890,
18,
225,
818,
41,
451,
67,
16811,
434,
225,
2437,
716,
732,
2545,
358,
1765,
316,
490,
361,
2160,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
512,
451,
869,
7969,
12,
11890,
5034,
2845,
13937,
67,
16,
2254,
5034,
818,
41,
451,
67,
13,
1071,
16618,
1135,
12,
11890,
5034,
13,
288,
203,
1377,
327,
389,
41,
451,
869,
7969,
12,
6011,
13937,
67,
16,
818,
41,
451,
67,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/1/0x5349E94435Cc9Cab9FfB40A492DA46935052733A/sources/cache/solpp-generated-contracts/zksync/libraries/PriorityQueue.sol | @notice Returns zero if and only if no operations were processed from the queue @return Index of the oldest priority operation that wasn't processed yet | function getFirstUnprocessedPriorityTx(Queue storage _queue) internal view returns (uint256) {
return _queue.head;
}
| 3,023,191 | [
1,
1356,
3634,
309,
471,
1338,
309,
1158,
5295,
4591,
5204,
628,
326,
2389,
327,
3340,
434,
326,
17067,
4394,
1674,
716,
14487,
1404,
5204,
4671,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7521,
984,
11005,
8183,
4188,
12,
3183,
2502,
389,
4000,
13,
2713,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
4000,
18,
1978,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-07-08
*/
// Sources flattened with hardhat v2.4.0 https://hardhat.org
// File contracts/auxiliary/interfaces/v0.8.4/IERC20Aux.sol
pragma solidity 0.8.4;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Aux {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File contracts/auxiliary/interfaces/v0.8.4/IApi3Token.sol
pragma solidity 0.8.4;
interface IApi3Token is IERC20Aux {
event MinterStatusUpdated(
address indexed minterAddress,
bool minterStatus
);
event BurnerStatusUpdated(
address indexed burnerAddress,
bool burnerStatus
);
function updateMinterStatus(
address minterAddress,
bool minterStatus
)
external;
function updateBurnerStatus(bool burnerStatus)
external;
function mint(
address account,
uint256 amount
)
external;
function burn(uint256 amount)
external;
function getMinterStatus(address minterAddress)
external
view
returns (bool minterStatus);
function getBurnerStatus(address burnerAddress)
external
view
returns (bool burnerStatus);
}
// File contracts/interfaces/IStateUtils.sol
pragma solidity 0.8.4;
interface IStateUtils {
event SetDaoApps(
address agentAppPrimary,
address agentAppSecondary,
address votingAppPrimary,
address votingAppSecondary
);
event SetClaimsManagerStatus(
address indexed claimsManager,
bool indexed status
);
event SetStakeTarget(uint256 stakeTarget);
event SetMaxApr(uint256 maxApr);
event SetMinApr(uint256 minApr);
event SetUnstakeWaitPeriod(uint256 unstakeWaitPeriod);
event SetAprUpdateStep(uint256 aprUpdateStep);
event SetProposalVotingPowerThreshold(uint256 proposalVotingPowerThreshold);
event UpdatedLastProposalTimestamp(
address indexed user,
uint256 lastProposalTimestamp,
address votingApp
);
function setDaoApps(
address _agentAppPrimary,
address _agentAppSecondary,
address _votingAppPrimary,
address _votingAppSecondary
)
external;
function setClaimsManagerStatus(
address claimsManager,
bool status
)
external;
function setStakeTarget(uint256 _stakeTarget)
external;
function setMaxApr(uint256 _maxApr)
external;
function setMinApr(uint256 _minApr)
external;
function setUnstakeWaitPeriod(uint256 _unstakeWaitPeriod)
external;
function setAprUpdateStep(uint256 _aprUpdateStep)
external;
function setProposalVotingPowerThreshold(uint256 _proposalVotingPowerThreshold)
external;
function updateLastProposalTimestamp(address userAddress)
external;
function isGenesisEpoch()
external
view
returns (bool);
}
// File contracts/StateUtils.sol
pragma solidity 0.8.4;
/// @title Contract that keeps state variables
contract StateUtils is IStateUtils {
struct Checkpoint {
uint32 fromBlock;
uint224 value;
}
struct AddressCheckpoint {
uint32 fromBlock;
address _address;
}
struct Reward {
uint32 atBlock;
uint224 amount;
uint256 totalSharesThen;
uint256 totalStakeThen;
}
struct User {
Checkpoint[] shares;
Checkpoint[] delegatedTo;
AddressCheckpoint[] delegates;
uint256 unstaked;
uint256 vesting;
uint256 unstakeAmount;
uint256 unstakeShares;
uint256 unstakeScheduledFor;
uint256 lastDelegationUpdateTimestamp;
uint256 lastProposalTimestamp;
}
struct LockedCalculation {
uint256 initialIndEpoch;
uint256 nextIndEpoch;
uint256 locked;
}
/// @notice Length of the epoch in which the staking reward is paid out
/// once. It is hardcoded as 7 days.
/// @dev In addition to regulating reward payments, this variable is used
/// for two additional things:
/// (1) After a user makes a proposal, they cannot make a second one
/// before `EPOCH_LENGTH` has passed
/// (2) After a user updates their delegation status, they have to wait
/// `EPOCH_LENGTH` before updating it again
uint256 public constant EPOCH_LENGTH = 1 weeks;
/// @notice Number of epochs before the staking rewards get unlocked.
/// Hardcoded as 52 epochs, which approximately corresponds to a year with
/// an `EPOCH_LENGTH` of 1 week.
uint256 public constant REWARD_VESTING_PERIOD = 52;
// All percentage values are represented as 1e18 = 100%
uint256 internal constant ONE_PERCENT = 1e18 / 100;
uint256 internal constant HUNDRED_PERCENT = 1e18;
// To assert that typecasts do not overflow
uint256 internal constant MAX_UINT32 = 2**32 - 1;
uint256 internal constant MAX_UINT224 = 2**224 - 1;
/// @notice Epochs are indexed as `block.timestamp / EPOCH_LENGTH`.
/// `genesisEpoch` is the index of the epoch in which the pool is deployed.
/// @dev No reward gets paid and proposals are not allowed in the genesis
/// epoch
uint256 public immutable genesisEpoch;
/// @notice API3 token contract
IApi3Token public immutable api3Token;
/// @notice TimelockManager contract
address public immutable timelockManager;
/// @notice Address of the primary Agent app of the API3 DAO
/// @dev Primary Agent can be operated through the primary Api3Voting app.
/// The primary Api3Voting app requires a higher quorum by default, and the
/// primary Agent is more privileged.
address public agentAppPrimary;
/// @notice Address of the secondary Agent app of the API3 DAO
/// @dev Secondary Agent can be operated through the secondary Api3Voting
/// app. The secondary Api3Voting app requires a lower quorum by default,
/// and the primary Agent is less privileged.
address public agentAppSecondary;
/// @notice Address of the primary Api3Voting app of the API3 DAO
/// @dev Used to operate the primary Agent
address public votingAppPrimary;
/// @notice Address of the secondary Api3Voting app of the API3 DAO
/// @dev Used to operate the secondary Agent
address public votingAppSecondary;
/// @notice Mapping that keeps the claims manager statuses of addresses
/// @dev A claims manager is a contract that is authorized to pay out
/// claims from the staking pool, effectively slashing the stakers. The
/// statuses are kept as a mapping to support multiple claims managers.
mapping(address => bool) public claimsManagerStatus;
/// @notice Records of rewards paid in each epoch
/// @dev `.atBlock` of a past epoch's reward record being `0` means no
/// reward was paid for that epoch
mapping(uint256 => Reward) public epochIndexToReward;
/// @notice Epoch index of the most recent reward
uint256 public epochIndexOfLastReward;
/// @notice Total number of tokens staked at the pool
uint256 public totalStake;
/// @notice Stake target the pool will aim to meet in percentages of the
/// total token supply. The staking rewards increase if the total staked
/// amount is below this, and vice versa.
/// @dev Default value is 50% of the total API3 token supply. This
/// parameter is governable by the DAO.
uint256 public stakeTarget = ONE_PERCENT * 50;
/// @notice Minimum APR (annual percentage rate) the pool will pay as
/// staking rewards in percentages
/// @dev Default value is 2.5%. This parameter is governable by the DAO.
uint256 public minApr = ONE_PERCENT * 25 / 10;
/// @notice Maximum APR (annual percentage rate) the pool will pay as
/// staking rewards in percentages
/// @dev Default value is 75%. This parameter is governable by the DAO.
uint256 public maxApr = ONE_PERCENT * 75;
/// @notice Steps in which APR will be updated in percentages
/// @dev Default value is 1%. This parameter is governable by the DAO.
uint256 public aprUpdateStep = ONE_PERCENT;
/// @notice Users need to schedule an unstake and wait for
/// `unstakeWaitPeriod` before being able to unstake. This is to prevent
/// the stakers from frontrunning insurance claims by unstaking to evade
/// them, or repeatedly unstake/stake to work around the proposal spam
/// protection. The tokens awaiting to be unstaked during this period do
/// not grant voting power or rewards.
/// @dev This parameter is governable by the DAO, and the DAO is expected
/// to set this to a value that is large enough to allow insurance claims
/// to be resolved.
uint256 public unstakeWaitPeriod = EPOCH_LENGTH;
/// @notice Minimum voting power the users must have to be able to make
/// proposals (in percentages)
/// @dev Delegations count towards voting power.
/// Default value is 0.1%. This parameter is governable by the DAO.
uint256 public proposalVotingPowerThreshold = ONE_PERCENT / 10;
/// @notice APR that will be paid next epoch
/// @dev This value will reach an equilibrium based on the stake target.
/// Every epoch (week), APR/52 of the total staked tokens will be added to
/// the pool, effectively distributing them to the stakers.
uint256 public apr = (maxApr + minApr) / 2;
/// @notice User records
mapping(address => User) public users;
// Keeps the total number of shares of the pool
Checkpoint[] public poolShares;
// Keeps user states used in `withdrawPrecalculated()` calls
mapping(address => LockedCalculation) public userToLockedCalculation;
// Kept to prevent third parties from frontrunning the initialization
// `setDaoApps()` call and grief the deployment
address private deployer;
/// @dev Reverts if the caller is not an API3 DAO Agent
modifier onlyAgentApp() {
require(
msg.sender == agentAppPrimary || msg.sender == agentAppSecondary,
"Pool: Caller not agent"
);
_;
}
/// @dev Reverts if the caller is not the primary API3 DAO Agent
modifier onlyAgentAppPrimary() {
require(
msg.sender == agentAppPrimary,
"Pool: Caller not primary agent"
);
_;
}
/// @dev Reverts if the caller is not an API3 DAO Api3Voting app
modifier onlyVotingApp() {
require(
msg.sender == votingAppPrimary || msg.sender == votingAppSecondary,
"Pool: Caller not voting app"
);
_;
}
/// @param api3TokenAddress API3 token contract address
/// @param timelockManagerAddress Timelock manager contract address
constructor(
address api3TokenAddress,
address timelockManagerAddress
)
{
require(
api3TokenAddress != address(0),
"Pool: Invalid Api3Token"
);
require(
timelockManagerAddress != address(0),
"Pool: Invalid TimelockManager"
);
deployer = msg.sender;
api3Token = IApi3Token(api3TokenAddress);
timelockManager = timelockManagerAddress;
// Initialize the share price at 1
updateCheckpointArray(poolShares, 1);
totalStake = 1;
// Set the current epoch as the genesis epoch and skip its reward
// payment
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
genesisEpoch = currentEpoch;
epochIndexOfLastReward = currentEpoch;
}
/// @notice Called after deployment to set the addresses of the DAO apps
/// @dev This can also be called later on by the primary Agent to update
/// all app addresses as a means of an upgrade
/// @param _agentAppPrimary Address of the primary Agent
/// @param _agentAppSecondary Address of the secondary Agent
/// @param _votingAppPrimary Address of the primary Api3Voting app
/// @param _votingAppSecondary Address of the secondary Api3Voting app
function setDaoApps(
address _agentAppPrimary,
address _agentAppSecondary,
address _votingAppPrimary,
address _votingAppSecondary
)
external
override
{
// solhint-disable-next-line reason-string
require(
msg.sender == agentAppPrimary
|| (agentAppPrimary == address(0) && msg.sender == deployer),
"Pool: Caller not primary agent or deployer initializing values"
);
require(
_agentAppPrimary != address(0)
&& _agentAppSecondary != address(0)
&& _votingAppPrimary != address(0)
&& _votingAppSecondary != address(0),
"Pool: Invalid DAO apps"
);
agentAppPrimary = _agentAppPrimary;
agentAppSecondary = _agentAppSecondary;
votingAppPrimary = _votingAppPrimary;
votingAppSecondary = _votingAppSecondary;
emit SetDaoApps(
agentAppPrimary,
agentAppSecondary,
votingAppPrimary,
votingAppSecondary
);
}
/// @notice Called by the primary DAO Agent to set the authorization status
/// of a claims manager contract
/// @dev The claims manager is a trusted contract that is allowed to
/// withdraw as many tokens as it wants from the pool to pay out insurance
/// claims.
/// Only the primary Agent can do this because it is a critical operation.
/// WARNING: A compromised contract being given claims manager status may
/// result in loss of staked funds. If a proposal has been made to call
/// this method to set a contract as a claims manager, you are recommended
/// to review the contract yourself and/or refer to the audit reports to
/// understand the implications.
/// @param claimsManager Claims manager contract address
/// @param status Authorization status
function setClaimsManagerStatus(
address claimsManager,
bool status
)
external
override
onlyAgentAppPrimary()
{
claimsManagerStatus[claimsManager] = status;
emit SetClaimsManagerStatus(
claimsManager,
status
);
}
/// @notice Called by the DAO Agent to set the stake target
/// @param _stakeTarget Stake target
function setStakeTarget(uint256 _stakeTarget)
external
override
onlyAgentApp()
{
require(
_stakeTarget <= HUNDRED_PERCENT,
"Pool: Invalid percentage value"
);
stakeTarget = _stakeTarget;
emit SetStakeTarget(_stakeTarget);
}
/// @notice Called by the DAO Agent to set the maximum APR
/// @param _maxApr Maximum APR
function setMaxApr(uint256 _maxApr)
external
override
onlyAgentApp()
{
require(
_maxApr >= minApr,
"Pool: Max APR smaller than min"
);
maxApr = _maxApr;
emit SetMaxApr(_maxApr);
}
/// @notice Called by the DAO Agent to set the minimum APR
/// @param _minApr Minimum APR
function setMinApr(uint256 _minApr)
external
override
onlyAgentApp()
{
require(
_minApr <= maxApr,
"Pool: Min APR larger than max"
);
minApr = _minApr;
emit SetMinApr(_minApr);
}
/// @notice Called by the primary DAO Agent to set the unstake waiting
/// period
/// @dev This may want to be increased to provide more time for insurance
/// claims to be resolved.
/// Even when the insurance functionality is not implemented, the minimum
/// valid value is `EPOCH_LENGTH` to prevent users from unstaking,
/// withdrawing and staking with another address to work around the
/// proposal spam protection.
/// Only the primary Agent can do this because it is a critical operation.
/// @param _unstakeWaitPeriod Unstake waiting period
function setUnstakeWaitPeriod(uint256 _unstakeWaitPeriod)
external
override
onlyAgentAppPrimary()
{
require(
_unstakeWaitPeriod >= EPOCH_LENGTH,
"Pool: Period shorter than epoch"
);
unstakeWaitPeriod = _unstakeWaitPeriod;
emit SetUnstakeWaitPeriod(_unstakeWaitPeriod);
}
/// @notice Called by the primary DAO Agent to set the APR update steps
/// @dev aprUpdateStep can be 0% or 100%+.
/// Only the primary Agent can do this because it is a critical operation.
/// @param _aprUpdateStep APR update steps
function setAprUpdateStep(uint256 _aprUpdateStep)
external
override
onlyAgentAppPrimary()
{
aprUpdateStep = _aprUpdateStep;
emit SetAprUpdateStep(_aprUpdateStep);
}
/// @notice Called by the primary DAO Agent to set the voting power
/// threshold for proposals
/// @dev Only the primary Agent can do this because it is a critical
/// operation.
/// @param _proposalVotingPowerThreshold Voting power threshold for
/// proposals
function setProposalVotingPowerThreshold(uint256 _proposalVotingPowerThreshold)
external
override
onlyAgentAppPrimary()
{
require(
_proposalVotingPowerThreshold >= ONE_PERCENT / 10
&& _proposalVotingPowerThreshold <= ONE_PERCENT * 10,
"Pool: Threshold outside limits");
proposalVotingPowerThreshold = _proposalVotingPowerThreshold;
emit SetProposalVotingPowerThreshold(_proposalVotingPowerThreshold);
}
/// @notice Called by a DAO Api3Voting app at proposal creation-time to
/// update the timestamp of the user's last proposal
/// @param userAddress User address
function updateLastProposalTimestamp(address userAddress)
external
override
onlyVotingApp()
{
users[userAddress].lastProposalTimestamp = block.timestamp;
emit UpdatedLastProposalTimestamp(
userAddress,
block.timestamp,
msg.sender
);
}
/// @notice Called to check if we are in the genesis epoch
/// @dev Voting apps use this to prevent proposals from being made in the
/// genesis epoch
/// @return If the current epoch is the genesis epoch
function isGenesisEpoch()
external
view
override
returns (bool)
{
return block.timestamp / EPOCH_LENGTH == genesisEpoch;
}
/// @notice Called internally to update a checkpoint array by pushing a new
/// checkpoint
/// @dev We assume `block.number` will always fit in a uint32 and `value`
/// will always fit in a uint224. `value` will either be a raw token amount
/// or a raw pool share amount so this assumption will be correct in
/// practice with a token with 18 decimals, 1e8 initial total supply and no
/// hyperinflation.
/// @param checkpointArray Checkpoint array
/// @param value Value to be used to create the new checkpoint
function updateCheckpointArray(
Checkpoint[] storage checkpointArray,
uint256 value
)
internal
{
assert(block.number <= MAX_UINT32);
assert(value <= MAX_UINT224);
checkpointArray.push(Checkpoint({
fromBlock: uint32(block.number),
value: uint224(value)
}));
}
/// @notice Called internally to update an address-checkpoint array by
/// pushing a new checkpoint
/// @dev We assume `block.number` will always fit in a uint32
/// @param addressCheckpointArray Address-checkpoint array
/// @param _address Address to be used to create the new checkpoint
function updateAddressCheckpointArray(
AddressCheckpoint[] storage addressCheckpointArray,
address _address
)
internal
{
assert(block.number <= MAX_UINT32);
addressCheckpointArray.push(AddressCheckpoint({
fromBlock: uint32(block.number),
_address: _address
}));
}
}
// File contracts/interfaces/IGetterUtils.sol
pragma solidity 0.8.4;
interface IGetterUtils is IStateUtils {
function userVotingPowerAt(
address userAddress,
uint256 _block
)
external
view
returns (uint256);
function userVotingPower(address userAddress)
external
view
returns (uint256);
function totalSharesAt(uint256 _block)
external
view
returns (uint256);
function totalShares()
external
view
returns (uint256);
function userSharesAt(
address userAddress,
uint256 _block
)
external
view
returns (uint256);
function userShares(address userAddress)
external
view
returns (uint256);
function userStake(address userAddress)
external
view
returns (uint256);
function delegatedToUserAt(
address userAddress,
uint256 _block
)
external
view
returns (uint256);
function delegatedToUser(address userAddress)
external
view
returns (uint256);
function userDelegateAt(
address userAddress,
uint256 _block
)
external
view
returns (address);
function userDelegate(address userAddress)
external
view
returns (address);
function userLocked(address userAddress)
external
view
returns (uint256);
function getUser(address userAddress)
external
view
returns (
uint256 unstaked,
uint256 vesting,
uint256 unstakeShares,
uint256 unstakeAmount,
uint256 unstakeScheduledFor,
uint256 lastDelegationUpdateTimestamp,
uint256 lastProposalTimestamp
);
}
// File contracts/GetterUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements getters
abstract contract GetterUtils is StateUtils, IGetterUtils {
/// @notice Called to get the voting power of a user at a specific block
/// @param userAddress User address
/// @param _block Block number for which the query is being made for
/// @return Voting power of the user at the block
function userVotingPowerAt(
address userAddress,
uint256 _block
)
public
view
override
returns (uint256)
{
// Users that have a delegate have no voting power
if (userDelegateAt(userAddress, _block) != address(0))
{
return 0;
}
return userSharesAt(userAddress, _block)
+ delegatedToUserAt(userAddress, _block);
}
/// @notice Called to get the current voting power of a user
/// @param userAddress User address
/// @return Current voting power of the user
function userVotingPower(address userAddress)
external
view
override
returns (uint256)
{
return userVotingPowerAt(userAddress, block.number);
}
/// @notice Called to get the total pool shares at a specific block
/// @dev Total pool shares also corresponds to total voting power
/// @param _block Block number for which the query is being made for
/// @return Total pool shares at the block
function totalSharesAt(uint256 _block)
public
view
override
returns (uint256)
{
return getValueAt(poolShares, _block);
}
/// @notice Called to get the current total pool shares
/// @dev Total pool shares also corresponds to total voting power
/// @return Current total pool shares
function totalShares()
public
view
override
returns (uint256)
{
return totalSharesAt(block.number);
}
/// @notice Called to get the pool shares of a user at a specific block
/// @param userAddress User address
/// @param _block Block number for which the query is being made for
/// @return Pool shares of the user at the block
function userSharesAt(
address userAddress,
uint256 _block
)
public
view
override
returns (uint256)
{
return getValueAt(users[userAddress].shares, _block);
}
/// @notice Called to get the current pool shares of a user
/// @param userAddress User address
/// @return Current pool shares of the user
function userShares(address userAddress)
public
view
override
returns (uint256)
{
return userSharesAt(userAddress, block.number);
}
/// @notice Called to get the current staked tokens of the user
/// @param userAddress User address
/// @return Current staked tokens of the user
function userStake(address userAddress)
public
view
override
returns (uint256)
{
return userShares(userAddress) * totalStake / totalShares();
}
/// @notice Called to get the voting power delegated to a user at a
/// specific block
/// @param userAddress User address
/// @param _block Block number for which the query is being made for
/// @return Voting power delegated to the user at the block
function delegatedToUserAt(
address userAddress,
uint256 _block
)
public
view
override
returns (uint256)
{
return getValueAt(users[userAddress].delegatedTo, _block);
}
/// @notice Called to get the current voting power delegated to a user
/// @param userAddress User address
/// @return Current voting power delegated to the user
function delegatedToUser(address userAddress)
public
view
override
returns (uint256)
{
return delegatedToUserAt(userAddress, block.number);
}
/// @notice Called to get the delegate of the user at a specific block
/// @param userAddress User address
/// @param _block Block number
/// @return Delegate of the user at the specific block
function userDelegateAt(
address userAddress,
uint256 _block
)
public
view
override
returns (address)
{
return getAddressAt(users[userAddress].delegates, _block);
}
/// @notice Called to get the current delegate of the user
/// @param userAddress User address
/// @return Current delegate of the user
function userDelegate(address userAddress)
public
view
override
returns (address)
{
return userDelegateAt(userAddress, block.number);
}
/// @notice Called to get the current locked tokens of the user
/// @param userAddress User address
/// @return locked Current locked tokens of the user
function userLocked(address userAddress)
public
view
override
returns (uint256 locked)
{
Checkpoint[] storage _userShares = users[userAddress].shares;
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
uint256 oldestLockedEpoch = getOldestLockedEpoch();
uint256 indUserShares = _userShares.length;
for (
uint256 indEpoch = currentEpoch;
indEpoch >= oldestLockedEpoch;
indEpoch--
)
{
// The user has never staked at this point, we can exit early
if (indUserShares == 0)
{
break;
}
Reward storage lockedReward = epochIndexToReward[indEpoch];
if (lockedReward.atBlock != 0)
{
for (; indUserShares > 0; indUserShares--)
{
Checkpoint storage userShare = _userShares[indUserShares - 1];
if (userShare.fromBlock <= lockedReward.atBlock)
{
locked += lockedReward.amount * userShare.value / lockedReward.totalSharesThen;
break;
}
}
}
}
}
/// @notice Called to get the details of a user
/// @param userAddress User address
/// @return unstaked Amount of unstaked API3 tokens
/// @return vesting Amount of API3 tokens locked by vesting
/// @return unstakeAmount Amount scheduled to unstake
/// @return unstakeShares Shares revoked to unstake
/// @return unstakeScheduledFor Time unstaking is scheduled for
/// @return lastDelegationUpdateTimestamp Time of last delegation update
/// @return lastProposalTimestamp Time when the user made their most
/// recent proposal
function getUser(address userAddress)
external
view
override
returns (
uint256 unstaked,
uint256 vesting,
uint256 unstakeAmount,
uint256 unstakeShares,
uint256 unstakeScheduledFor,
uint256 lastDelegationUpdateTimestamp,
uint256 lastProposalTimestamp
)
{
User storage user = users[userAddress];
unstaked = user.unstaked;
vesting = user.vesting;
unstakeAmount = user.unstakeAmount;
unstakeShares = user.unstakeShares;
unstakeScheduledFor = user.unstakeScheduledFor;
lastDelegationUpdateTimestamp = user.lastDelegationUpdateTimestamp;
lastProposalTimestamp = user.lastProposalTimestamp;
}
/// @notice Called to get the value of a checkpoint array at a specific
/// block using binary search
/// @dev Adapted from
/// https://github.com/aragon/minime/blob/1d5251fc88eee5024ff318d95bc9f4c5de130430/contracts/MiniMeToken.sol#L431
/// @param checkpoints Checkpoints array
/// @param _block Block number for which the query is being made
/// @return Value of the checkpoint array at the block
function getValueAt(
Checkpoint[] storage checkpoints,
uint256 _block
)
internal
view
returns (uint256)
{
if (checkpoints.length == 0)
return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length -1].fromBlock)
return checkpoints[checkpoints.length - 1].value;
if (_block < checkpoints[0].fromBlock)
return 0;
// Limit the search to the last 1024 elements if the value being
// searched falls within that window
uint min = 0;
if (
checkpoints.length > 1024
&& checkpoints[checkpoints.length - 1024].fromBlock < _block
)
{
min = checkpoints.length - 1024;
}
// Binary search of the value in the array
uint max = checkpoints.length - 1;
while (max > min) {
uint mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock <= _block) {
min = mid;
} else {
max = mid - 1;
}
}
return checkpoints[min].value;
}
/// @notice Called to get the value of an address-checkpoint array at a
/// specific block using binary search
/// @dev Adapted from
/// https://github.com/aragon/minime/blob/1d5251fc88eee5024ff318d95bc9f4c5de130430/contracts/MiniMeToken.sol#L431
/// @param checkpoints Address-checkpoint array
/// @param _block Block number for which the query is being made
/// @return Value of the address-checkpoint array at the block
function getAddressAt(
AddressCheckpoint[] storage checkpoints,
uint256 _block
)
private
view
returns (address)
{
if (checkpoints.length == 0)
return address(0);
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length -1].fromBlock)
return checkpoints[checkpoints.length - 1]._address;
if (_block < checkpoints[0].fromBlock)
return address(0);
// Limit the search to the last 1024 elements if the value being
// searched falls within that window
uint min = 0;
if (
checkpoints.length > 1024
&& checkpoints[checkpoints.length - 1024].fromBlock < _block
)
{
min = checkpoints.length - 1024;
}
// Binary search of the value in the array
uint max = checkpoints.length - 1;
while (max > min) {
uint mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock <= _block) {
min = mid;
} else {
max = mid - 1;
}
}
return checkpoints[min]._address;
}
/// @notice Called internally to get the index of the oldest epoch whose
/// reward should be locked in the current epoch
/// @return oldestLockedEpoch Index of the oldest epoch with locked rewards
function getOldestLockedEpoch()
internal
view
returns (uint256 oldestLockedEpoch)
{
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
oldestLockedEpoch = currentEpoch - REWARD_VESTING_PERIOD + 1;
if (oldestLockedEpoch < genesisEpoch + 1)
{
oldestLockedEpoch = genesisEpoch + 1;
}
}
}
// File contracts/interfaces/IRewardUtils.sol
pragma solidity 0.8.4;
interface IRewardUtils is IGetterUtils {
event MintedReward(
uint256 indexed epochIndex,
uint256 amount,
uint256 newApr,
uint256 totalStake
);
function mintReward()
external;
}
// File contracts/RewardUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements reward payments
abstract contract RewardUtils is GetterUtils, IRewardUtils {
/// @notice Called to mint the staking reward
/// @dev Skips past epochs for which rewards have not been paid for.
/// Skips the reward payment if the pool is not authorized to mint tokens.
/// Neither of these conditions will occur in practice.
function mintReward()
public
override
{
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
// This will be skipped in most cases because someone else will have
// triggered the payment for this epoch
if (epochIndexOfLastReward < currentEpoch)
{
if (api3Token.getMinterStatus(address(this)))
{
uint256 rewardAmount = totalStake * apr * EPOCH_LENGTH / 365 days / HUNDRED_PERCENT;
assert(block.number <= MAX_UINT32);
assert(rewardAmount <= MAX_UINT224);
epochIndexToReward[currentEpoch] = Reward({
atBlock: uint32(block.number),
amount: uint224(rewardAmount),
totalSharesThen: totalShares(),
totalStakeThen: totalStake
});
api3Token.mint(address(this), rewardAmount);
totalStake += rewardAmount;
updateCurrentApr();
emit MintedReward(
currentEpoch,
rewardAmount,
apr,
totalStake
);
}
epochIndexOfLastReward = currentEpoch;
}
}
/// @notice Updates the current APR
/// @dev Called internally after paying out the reward
function updateCurrentApr()
internal
{
uint256 totalStakePercentage = totalStake
* HUNDRED_PERCENT
/ api3Token.totalSupply();
if (totalStakePercentage > stakeTarget)
{
apr = apr > aprUpdateStep ? apr - aprUpdateStep : 0;
}
else
{
apr += aprUpdateStep;
}
if (apr > maxApr) {
apr = maxApr;
}
else if (apr < minApr) {
apr = minApr;
}
}
}
// File contracts/interfaces/IDelegationUtils.sol
pragma solidity 0.8.4;
interface IDelegationUtils is IRewardUtils {
event Delegated(
address indexed user,
address indexed delegate,
uint256 shares,
uint256 totalDelegatedTo
);
event Undelegated(
address indexed user,
address indexed delegate,
uint256 shares,
uint256 totalDelegatedTo
);
event UpdatedDelegation(
address indexed user,
address indexed delegate,
bool delta,
uint256 shares,
uint256 totalDelegatedTo
);
function delegateVotingPower(address delegate)
external;
function undelegateVotingPower()
external;
}
// File contracts/DelegationUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements voting power delegation
abstract contract DelegationUtils is RewardUtils, IDelegationUtils {
/// @notice Called by the user to delegate voting power
/// @param delegate User address the voting power will be delegated to
function delegateVotingPower(address delegate)
external
override
{
mintReward();
require(
delegate != address(0) && delegate != msg.sender,
"Pool: Invalid delegate"
);
// Delegating users cannot use their voting power, so we are
// verifying that the delegate is not currently delegating. However,
// the delegate may delegate after they have been delegated to.
require(
userDelegate(delegate) == address(0),
"Pool: Delegate is delegating"
);
User storage user = users[msg.sender];
// Do not allow frequent delegation updates as that can be used to spam
// proposals
require(
user.lastDelegationUpdateTimestamp + EPOCH_LENGTH < block.timestamp,
"Pool: Updated delegate recently"
);
user.lastDelegationUpdateTimestamp = block.timestamp;
uint256 userShares = userShares(msg.sender);
require(
userShares != 0,
"Pool: Have no shares to delegate"
);
address previousDelegate = userDelegate(msg.sender);
require(
previousDelegate != delegate,
"Pool: Already delegated"
);
if (previousDelegate != address(0)) {
// Need to revoke previous delegation
updateCheckpointArray(
users[previousDelegate].delegatedTo,
delegatedToUser(previousDelegate) - userShares
);
}
// Assign the new delegation
uint256 delegatedToUpdate = delegatedToUser(delegate) + userShares;
updateCheckpointArray(
users[delegate].delegatedTo,
delegatedToUpdate
);
// Record the new delegate for the user
updateAddressCheckpointArray(
user.delegates,
delegate
);
emit Delegated(
msg.sender,
delegate,
userShares,
delegatedToUpdate
);
}
/// @notice Called by the user to undelegate voting power
function undelegateVotingPower()
external
override
{
mintReward();
User storage user = users[msg.sender];
address previousDelegate = userDelegate(msg.sender);
require(
previousDelegate != address(0),
"Pool: Not delegated"
);
require(
user.lastDelegationUpdateTimestamp + EPOCH_LENGTH < block.timestamp,
"Pool: Updated delegate recently"
);
user.lastDelegationUpdateTimestamp = block.timestamp;
uint256 userShares = userShares(msg.sender);
uint256 delegatedToUpdate = delegatedToUser(previousDelegate) - userShares;
updateCheckpointArray(
users[previousDelegate].delegatedTo,
delegatedToUpdate
);
updateAddressCheckpointArray(
user.delegates,
address(0)
);
emit Undelegated(
msg.sender,
previousDelegate,
userShares,
delegatedToUpdate
);
}
/// @notice Called internally when the user shares are updated to update
/// the delegated voting power
/// @dev User shares only get updated while staking or scheduling unstaking
/// @param shares Amount of shares that will be added/removed
/// @param delta Whether the shares will be added/removed (add for `true`,
/// and vice versa)
function updateDelegatedVotingPower(
uint256 shares,
bool delta
)
internal
{
address delegate = userDelegate(msg.sender);
if (delegate == address(0))
{
return;
}
uint256 currentDelegatedTo = delegatedToUser(delegate);
uint256 delegatedToUpdate = delta
? currentDelegatedTo + shares
: currentDelegatedTo - shares;
updateCheckpointArray(
users[delegate].delegatedTo,
delegatedToUpdate
);
emit UpdatedDelegation(
msg.sender,
delegate,
delta,
shares,
delegatedToUpdate
);
}
}
// File contracts/interfaces/ITransferUtils.sol
pragma solidity 0.8.4;
interface ITransferUtils is IDelegationUtils{
event Deposited(
address indexed user,
uint256 amount,
uint256 userUnstaked
);
event Withdrawn(
address indexed user,
uint256 amount,
uint256 userUnstaked
);
event CalculatingUserLocked(
address indexed user,
uint256 nextIndEpoch,
uint256 oldestLockedEpoch
);
event CalculatedUserLocked(
address indexed user,
uint256 amount
);
function depositRegular(uint256 amount)
external;
function withdrawRegular(uint256 amount)
external;
function precalculateUserLocked(
address userAddress,
uint256 noEpochsPerIteration
)
external
returns (bool finished);
function withdrawPrecalculated(uint256 amount)
external;
}
// File contracts/TransferUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements token transfer functionality
abstract contract TransferUtils is DelegationUtils, ITransferUtils {
/// @notice Called by the user to deposit tokens
/// @dev The user should approve the pool to spend at least `amount` tokens
/// before calling this.
/// The method is named `depositRegular()` to prevent potential confusion.
/// See `deposit()` for more context.
/// @param amount Amount to be deposited
function depositRegular(uint256 amount)
public
override
{
mintReward();
uint256 unstakedUpdate = users[msg.sender].unstaked + amount;
users[msg.sender].unstaked = unstakedUpdate;
// Should never return false because the API3 token uses the
// OpenZeppelin implementation
assert(api3Token.transferFrom(msg.sender, address(this), amount));
emit Deposited(
msg.sender,
amount,
unstakedUpdate
);
}
/// @notice Called by the user to withdraw tokens to their wallet
/// @dev The user should call `userLocked()` beforehand to ensure that
/// they have at least `amount` unlocked tokens to withdraw.
/// The method is named `withdrawRegular()` to be consistent with the name
/// `depositRegular()`. See `depositRegular()` for more context.
/// @param amount Amount to be withdrawn
function withdrawRegular(uint256 amount)
public
override
{
mintReward();
withdraw(amount, userLocked(msg.sender));
}
/// @notice Called to calculate the locked tokens of a user by making
/// multiple transactions
/// @dev If the user updates their `user.shares` by staking/unstaking too
/// frequently (50+/week) in the last `REWARD_VESTING_PERIOD`, the
/// `userLocked()` call gas cost may exceed the block gas limit. In that
/// case, the user may call this method multiple times to have their locked
/// tokens calculated and use `withdrawPrecalculated()` to withdraw.
/// @param userAddress User address
/// @param noEpochsPerIteration Number of epochs per iteration
/// @return finished Calculation has finished in this call
function precalculateUserLocked(
address userAddress,
uint256 noEpochsPerIteration
)
external
override
returns (bool finished)
{
mintReward();
require(
noEpochsPerIteration > 0,
"Pool: Zero iteration window"
);
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
LockedCalculation storage lockedCalculation = userToLockedCalculation[userAddress];
// Reset the state if there was no calculation made in this epoch
if (lockedCalculation.initialIndEpoch != currentEpoch)
{
lockedCalculation.initialIndEpoch = currentEpoch;
lockedCalculation.nextIndEpoch = currentEpoch;
lockedCalculation.locked = 0;
}
uint256 indEpoch = lockedCalculation.nextIndEpoch;
uint256 locked = lockedCalculation.locked;
uint256 oldestLockedEpoch = getOldestLockedEpoch();
for (; indEpoch >= oldestLockedEpoch; indEpoch--)
{
if (lockedCalculation.nextIndEpoch >= indEpoch + noEpochsPerIteration)
{
lockedCalculation.nextIndEpoch = indEpoch;
lockedCalculation.locked = locked;
emit CalculatingUserLocked(
userAddress,
indEpoch,
oldestLockedEpoch
);
return false;
}
Reward storage lockedReward = epochIndexToReward[indEpoch];
if (lockedReward.atBlock != 0)
{
uint256 userSharesThen = userSharesAt(userAddress, lockedReward.atBlock);
locked += lockedReward.amount * userSharesThen / lockedReward.totalSharesThen;
}
}
lockedCalculation.nextIndEpoch = indEpoch;
lockedCalculation.locked = locked;
emit CalculatedUserLocked(userAddress, locked);
return true;
}
/// @notice Called by the user to withdraw after their locked token amount
/// is calculated with repeated calls to `precalculateUserLocked()`
/// @dev Only use `precalculateUserLocked()` and this method if
/// `withdrawRegular()` hits the block gas limit
/// @param amount Amount to be withdrawn
function withdrawPrecalculated(uint256 amount)
external
override
{
mintReward();
uint256 currentEpoch = block.timestamp / EPOCH_LENGTH;
LockedCalculation storage lockedCalculation = userToLockedCalculation[msg.sender];
require(
lockedCalculation.initialIndEpoch == currentEpoch,
"Pool: Calculation not up to date"
);
require(
lockedCalculation.nextIndEpoch < getOldestLockedEpoch(),
"Pool: Calculation not complete"
);
withdraw(amount, lockedCalculation.locked);
}
/// @notice Called internally after the amount of locked tokens of the user
/// is determined
/// @param amount Amount to be withdrawn
/// @param userLocked Amount of locked tokens of the user
function withdraw(
uint256 amount,
uint256 userLocked
)
private
{
User storage user = users[msg.sender];
// Check if the user has `amount` unlocked tokens to withdraw
uint256 lockedAndVesting = userLocked + user.vesting;
uint256 userTotalFunds = user.unstaked + userStake(msg.sender);
require(
userTotalFunds >= lockedAndVesting + amount,
"Pool: Not enough unlocked funds"
);
require(
user.unstaked >= amount,
"Pool: Not enough unstaked funds"
);
// Carry on with the withdrawal
uint256 unstakedUpdate = user.unstaked - amount;
user.unstaked = unstakedUpdate;
// Should never return false because the API3 token uses the
// OpenZeppelin implementation
assert(api3Token.transfer(msg.sender, amount));
emit Withdrawn(
msg.sender,
amount,
unstakedUpdate
);
}
}
// File contracts/interfaces/IStakeUtils.sol
pragma solidity 0.8.4;
interface IStakeUtils is ITransferUtils{
event Staked(
address indexed user,
uint256 amount,
uint256 mintedShares,
uint256 userUnstaked,
uint256 userShares,
uint256 totalShares,
uint256 totalStake
);
event ScheduledUnstake(
address indexed user,
uint256 amount,
uint256 shares,
uint256 scheduledFor,
uint256 userShares
);
event Unstaked(
address indexed user,
uint256 amount,
uint256 userUnstaked,
uint256 totalShares,
uint256 totalStake
);
function stake(uint256 amount)
external;
function depositAndStake(uint256 amount)
external;
function scheduleUnstake(uint256 amount)
external;
function unstake(address userAddress)
external
returns (uint256);
function unstakeAndWithdraw()
external;
}
// File contracts/StakeUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements staking functionality
abstract contract StakeUtils is TransferUtils, IStakeUtils {
/// @notice Called to stake tokens to receive pools in the share
/// @param amount Amount of tokens to stake
function stake(uint256 amount)
public
override
{
mintReward();
User storage user = users[msg.sender];
require(
user.unstaked >= amount,
"Pool: Amount exceeds unstaked"
);
uint256 userUnstakedUpdate = user.unstaked - amount;
user.unstaked = userUnstakedUpdate;
uint256 totalSharesNow = totalShares();
uint256 sharesToMint = amount * totalSharesNow / totalStake;
uint256 userSharesUpdate = userShares(msg.sender) + sharesToMint;
updateCheckpointArray(
user.shares,
userSharesUpdate
);
uint256 totalSharesUpdate = totalSharesNow + sharesToMint;
updateCheckpointArray(
poolShares,
totalSharesUpdate
);
totalStake += amount;
updateDelegatedVotingPower(sharesToMint, true);
emit Staked(
msg.sender,
amount,
sharesToMint,
userUnstakedUpdate,
userSharesUpdate,
totalSharesUpdate,
totalStake
);
}
/// @notice Convenience method to deposit and stake in a single transaction
/// @param amount Amount to be deposited and staked
function depositAndStake(uint256 amount)
external
override
{
depositRegular(amount);
stake(amount);
}
/// @notice Called by the user to schedule unstaking of their tokens
/// @dev While scheduling an unstake, `shares` get deducted from the user,
/// meaning that they will not receive rewards or voting power for them any
/// longer.
/// At unstaking-time, the user unstakes either the amount of tokens
/// scheduled to unstake, or the amount of tokens `shares` corresponds to
/// at unstaking-time, whichever is smaller. This corresponds to tokens
/// being scheduled to be unstaked not receiving any rewards, but being
/// subject to claim payouts.
/// In the instance that a claim has been paid out before an unstaking is
/// executed, the user may potentially receive rewards during
/// `unstakeWaitPeriod` (but not if there has not been a claim payout) but
/// the amount of tokens that they can unstake will not be able to exceed
/// the amount they scheduled the unstaking for.
/// @param amount Amount of tokens scheduled to unstake
function scheduleUnstake(uint256 amount)
external
override
{
mintReward();
uint256 userSharesNow = userShares(msg.sender);
uint256 totalSharesNow = totalShares();
uint256 userStaked = userSharesNow * totalStake / totalSharesNow;
require(
userStaked >= amount,
"Pool: Amount exceeds staked"
);
User storage user = users[msg.sender];
require(
user.unstakeScheduledFor == 0,
"Pool: Unexecuted unstake exists"
);
uint256 sharesToUnstake = amount * totalSharesNow / totalStake;
// This will only happen if the user wants to schedule an unstake for a
// few Wei
require(sharesToUnstake > 0, "Pool: Unstake amount too small");
uint256 unstakeScheduledFor = block.timestamp + unstakeWaitPeriod;
user.unstakeScheduledFor = unstakeScheduledFor;
user.unstakeAmount = amount;
user.unstakeShares = sharesToUnstake;
uint256 userSharesUpdate = userSharesNow - sharesToUnstake;
updateCheckpointArray(
user.shares,
userSharesUpdate
);
updateDelegatedVotingPower(sharesToUnstake, false);
emit ScheduledUnstake(
msg.sender,
amount,
sharesToUnstake,
unstakeScheduledFor,
userSharesUpdate
);
}
/// @notice Called to execute a pre-scheduled unstake
/// @dev Anyone can execute a matured unstake. This is to allow the user to
/// use bots, etc. to execute their unstaking as soon as possible.
/// @param userAddress User address
/// @return Amount of tokens that are unstaked
function unstake(address userAddress)
public
override
returns (uint256)
{
mintReward();
User storage user = users[userAddress];
require(
user.unstakeScheduledFor != 0,
"Pool: No unstake scheduled"
);
require(
user.unstakeScheduledFor < block.timestamp,
"Pool: Unstake not mature yet"
);
uint256 totalShares = totalShares();
uint256 unstakeAmount = user.unstakeAmount;
uint256 unstakeAmountByShares = user.unstakeShares * totalStake / totalShares;
// If there was a claim payout in between the scheduling and the actual
// unstake then the amount might be lower than expected at scheduling
// time
if (unstakeAmount > unstakeAmountByShares)
{
unstakeAmount = unstakeAmountByShares;
}
uint256 userUnstakedUpdate = user.unstaked + unstakeAmount;
user.unstaked = userUnstakedUpdate;
uint256 totalSharesUpdate = totalShares - user.unstakeShares;
updateCheckpointArray(
poolShares,
totalSharesUpdate
);
totalStake -= unstakeAmount;
user.unstakeAmount = 0;
user.unstakeShares = 0;
user.unstakeScheduledFor = 0;
emit Unstaked(
userAddress,
unstakeAmount,
userUnstakedUpdate,
totalSharesUpdate,
totalStake
);
return unstakeAmount;
}
/// @notice Convenience method to execute an unstake and withdraw to the
/// user's wallet in a single transaction
/// @dev The withdrawal will revert if the user has less than
/// `unstakeAmount` tokens that are withdrawable
function unstakeAndWithdraw()
external
override
{
withdrawRegular(unstake(msg.sender));
}
}
// File contracts/interfaces/IClaimUtils.sol
pragma solidity 0.8.4;
interface IClaimUtils is IStakeUtils {
event PaidOutClaim(
address indexed recipient,
uint256 amount,
uint256 totalStake
);
function payOutClaim(
address recipient,
uint256 amount
)
external;
}
// File contracts/ClaimUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements the insurance claim payout functionality
abstract contract ClaimUtils is StakeUtils, IClaimUtils {
/// @dev Reverts if the caller is not a claims manager
modifier onlyClaimsManager() {
require(
claimsManagerStatus[msg.sender],
"Pool: Caller not claims manager"
);
_;
}
/// @notice Called by a claims manager to pay out an insurance claim
/// @dev The claims manager is a trusted contract that is allowed to
/// withdraw as many tokens as it wants from the pool to pay out insurance
/// claims. Any kind of limiting logic (e.g., maximum amount of tokens that
/// can be withdrawn) is implemented at its end and is out of the scope of
/// this contract.
/// This will revert if the pool does not have enough staked funds.
/// @param recipient Recipient of the claim
/// @param amount Amount of tokens that will be paid out
function payOutClaim(
address recipient,
uint256 amount
)
external
override
onlyClaimsManager()
{
mintReward();
// totalStake should not go lower than 1
require(
totalStake > amount,
"Pool: Amount exceeds total stake"
);
totalStake -= amount;
// Should never return false because the API3 token uses the
// OpenZeppelin implementation
assert(api3Token.transfer(recipient, amount));
emit PaidOutClaim(
recipient,
amount,
totalStake
);
}
}
// File contracts/interfaces/ITimelockUtils.sol
pragma solidity 0.8.4;
interface ITimelockUtils is IClaimUtils {
event DepositedByTimelockManager(
address indexed user,
uint256 amount,
uint256 userUnstaked
);
event DepositedVesting(
address indexed user,
uint256 amount,
uint256 start,
uint256 end,
uint256 userUnstaked,
uint256 userVesting
);
event VestedTimelock(
address indexed user,
uint256 amount,
uint256 userVesting
);
function deposit(
address source,
uint256 amount,
address userAddress
)
external;
function depositWithVesting(
address source,
uint256 amount,
address userAddress,
uint256 releaseStart,
uint256 releaseEnd
)
external;
function updateTimelockStatus(address userAddress)
external;
}
// File contracts/TimelockUtils.sol
pragma solidity 0.8.4;
/// @title Contract that implements vesting functionality
/// @dev The TimelockManager contract interfaces with this contract to transfer
/// API3 tokens that are locked under a vesting schedule.
/// This contract keeps its own type definitions, event declarations and state
/// variables for them to be easier to remove for a subDAO where they will
/// likely not be used.
abstract contract TimelockUtils is ClaimUtils, ITimelockUtils {
struct Timelock {
uint256 totalAmount;
uint256 remainingAmount;
uint256 releaseStart;
uint256 releaseEnd;
}
/// @notice Maps user addresses to timelocks
/// @dev This implies that a user cannot have multiple timelocks
/// transferred from the TimelockManager contract. This is acceptable
/// because TimelockManager is implemented in a way to not allow multiple
/// timelocks per user.
mapping(address => Timelock) public userToTimelock;
/// @notice Called by the TimelockManager contract to deposit tokens on
/// behalf of a user
/// @dev This method is only usable by `TimelockManager.sol`.
/// It is named as `deposit()` and not `depositAsTimelockManager()` for
/// example, because the TimelockManager is already deployed and expects
/// the `deposit(address,uint256,address)` interface.
/// @param source Token transfer source
/// @param amount Amount to be deposited
/// @param userAddress User that the tokens will be deposited for
function deposit(
address source,
uint256 amount,
address userAddress
)
external
override
{
require(
msg.sender == timelockManager,
"Pool: Caller not TimelockManager"
);
uint256 unstakedUpdate = users[userAddress].unstaked + amount;
users[userAddress].unstaked = unstakedUpdate;
// Should never return false because the API3 token uses the
// OpenZeppelin implementation
assert(api3Token.transferFrom(source, address(this), amount));
emit DepositedByTimelockManager(
userAddress,
amount,
unstakedUpdate
);
}
/// @notice Called by the TimelockManager contract to deposit tokens on
/// behalf of a user on a linear vesting schedule
/// @dev Refer to `TimelockManager.sol` to see how this is used
/// @param source Token source
/// @param amount Token amount
/// @param userAddress Address of the user who will receive the tokens
/// @param releaseStart Vesting schedule starting time
/// @param releaseEnd Vesting schedule ending time
function depositWithVesting(
address source,
uint256 amount,
address userAddress,
uint256 releaseStart,
uint256 releaseEnd
)
external
override
{
require(
msg.sender == timelockManager,
"Pool: Caller not TimelockManager"
);
require(
userToTimelock[userAddress].remainingAmount == 0,
"Pool: User has active timelock"
);
require(
releaseEnd > releaseStart,
"Pool: Timelock start after end"
);
require(
amount != 0,
"Pool: Timelock amount zero"
);
uint256 unstakedUpdate = users[userAddress].unstaked + amount;
users[userAddress].unstaked = unstakedUpdate;
uint256 vestingUpdate = users[userAddress].vesting + amount;
users[userAddress].vesting = vestingUpdate;
userToTimelock[userAddress] = Timelock({
totalAmount: amount,
remainingAmount: amount,
releaseStart: releaseStart,
releaseEnd: releaseEnd
});
// Should never return false because the API3 token uses the
// OpenZeppelin implementation
assert(api3Token.transferFrom(source, address(this), amount));
emit DepositedVesting(
userAddress,
amount,
releaseStart,
releaseEnd,
unstakedUpdate,
vestingUpdate
);
}
/// @notice Called to release tokens vested by the timelock
/// @param userAddress Address of the user whose timelock status will be
/// updated
function updateTimelockStatus(address userAddress)
external
override
{
Timelock storage timelock = userToTimelock[userAddress];
require(
block.timestamp > timelock.releaseStart,
"Pool: Release not started yet"
);
require(
timelock.remainingAmount > 0,
"Pool: Timelock already released"
);
uint256 totalUnlocked;
if (block.timestamp >= timelock.releaseEnd)
{
totalUnlocked = timelock.totalAmount;
}
else
{
uint256 passedTime = block.timestamp - timelock.releaseStart;
uint256 totalTime = timelock.releaseEnd - timelock.releaseStart;
totalUnlocked = timelock.totalAmount * passedTime / totalTime;
}
uint256 previouslyUnlocked = timelock.totalAmount - timelock.remainingAmount;
uint256 newlyUnlocked = totalUnlocked - previouslyUnlocked;
User storage user = users[userAddress];
uint256 vestingUpdate = user.vesting - newlyUnlocked;
user.vesting = vestingUpdate;
timelock.remainingAmount -= newlyUnlocked;
emit VestedTimelock(
userAddress,
newlyUnlocked,
vestingUpdate
);
}
}
// File contracts/interfaces/IApi3Pool.sol
pragma solidity 0.8.4;
interface IApi3Pool is ITimelockUtils {
}
// File contracts/Api3Pool.sol
pragma solidity 0.8.4;
/// @title API3 pool contract
/// @notice Users can stake API3 tokens at the pool contract to be granted
/// shares. These shares are exposed to the Aragon-based DAO, giving the user
/// voting power at the DAO. Staking pays out weekly rewards that get unlocked
/// after a year, and staked funds are used to collateralize an insurance
/// product that is outside the scope of this contract.
/// @dev Functionalities of the contract are distributed to files that form a
/// chain of inheritance:
/// (1) Api3Pool.sol
/// (2) TimelockUtils.sol
/// (3) ClaimUtils.sol
/// (4) StakeUtils.sol
/// (5) TransferUtils.sol
/// (6) DelegationUtils.sol
/// (7) RewardUtils.sol
/// (8) GetterUtils.sol
/// (9) StateUtils.sol
contract Api3Pool is TimelockUtils, IApi3Pool {
/// @param api3TokenAddress API3 token contract address
/// @param timelockManagerAddress Timelock manager contract address
constructor(
address api3TokenAddress,
address timelockManagerAddress
)
StateUtils(
api3TokenAddress,
timelockManagerAddress
)
{}
} | @title Contract that implements voting power delegation | abstract contract DelegationUtils is RewardUtils, IDelegationUtils {
function delegateVotingPower(address delegate)
external
override
{
mintReward();
require(
delegate != address(0) && delegate != msg.sender,
"Pool: Invalid delegate"
);
require(
userDelegate(delegate) == address(0),
"Pool: Delegate is delegating"
);
User storage user = users[msg.sender];
require(
user.lastDelegationUpdateTimestamp + EPOCH_LENGTH < block.timestamp,
"Pool: Updated delegate recently"
);
user.lastDelegationUpdateTimestamp = block.timestamp;
uint256 userShares = userShares(msg.sender);
require(
userShares != 0,
"Pool: Have no shares to delegate"
);
address previousDelegate = userDelegate(msg.sender);
require(
previousDelegate != delegate,
"Pool: Already delegated"
);
if (previousDelegate != address(0)) {
updateCheckpointArray(
users[previousDelegate].delegatedTo,
delegatedToUser(previousDelegate) - userShares
);
}
updateCheckpointArray(
users[delegate].delegatedTo,
delegatedToUpdate
);
user.delegates,
delegate
);
emit Delegated(
msg.sender,
delegate,
userShares,
delegatedToUpdate
);
}
{
mintReward();
require(
delegate != address(0) && delegate != msg.sender,
"Pool: Invalid delegate"
);
require(
userDelegate(delegate) == address(0),
"Pool: Delegate is delegating"
);
User storage user = users[msg.sender];
require(
user.lastDelegationUpdateTimestamp + EPOCH_LENGTH < block.timestamp,
"Pool: Updated delegate recently"
);
user.lastDelegationUpdateTimestamp = block.timestamp;
uint256 userShares = userShares(msg.sender);
require(
userShares != 0,
"Pool: Have no shares to delegate"
);
address previousDelegate = userDelegate(msg.sender);
require(
previousDelegate != delegate,
"Pool: Already delegated"
);
if (previousDelegate != address(0)) {
updateCheckpointArray(
users[previousDelegate].delegatedTo,
delegatedToUser(previousDelegate) - userShares
);
}
updateCheckpointArray(
users[delegate].delegatedTo,
delegatedToUpdate
);
user.delegates,
delegate
);
emit Delegated(
msg.sender,
delegate,
userShares,
delegatedToUpdate
);
}
uint256 delegatedToUpdate = delegatedToUser(delegate) + userShares;
updateAddressCheckpointArray(
function undelegateVotingPower()
external
override
{
mintReward();
User storage user = users[msg.sender];
address previousDelegate = userDelegate(msg.sender);
require(
previousDelegate != address(0),
"Pool: Not delegated"
);
require(
user.lastDelegationUpdateTimestamp + EPOCH_LENGTH < block.timestamp,
"Pool: Updated delegate recently"
);
user.lastDelegationUpdateTimestamp = block.timestamp;
uint256 userShares = userShares(msg.sender);
uint256 delegatedToUpdate = delegatedToUser(previousDelegate) - userShares;
updateCheckpointArray(
users[previousDelegate].delegatedTo,
delegatedToUpdate
);
updateAddressCheckpointArray(
user.delegates,
address(0)
);
emit Undelegated(
msg.sender,
previousDelegate,
userShares,
delegatedToUpdate
);
}
function updateDelegatedVotingPower(
uint256 shares,
bool delta
)
internal
{
address delegate = userDelegate(msg.sender);
if (delegate == address(0))
{
return;
}
uint256 currentDelegatedTo = delegatedToUser(delegate);
uint256 delegatedToUpdate = delta
? currentDelegatedTo + shares
: currentDelegatedTo - shares;
updateCheckpointArray(
users[delegate].delegatedTo,
delegatedToUpdate
);
emit UpdatedDelegation(
msg.sender,
delegate,
delta,
shares,
delegatedToUpdate
);
}
function updateDelegatedVotingPower(
uint256 shares,
bool delta
)
internal
{
address delegate = userDelegate(msg.sender);
if (delegate == address(0))
{
return;
}
uint256 currentDelegatedTo = delegatedToUser(delegate);
uint256 delegatedToUpdate = delta
? currentDelegatedTo + shares
: currentDelegatedTo - shares;
updateCheckpointArray(
users[delegate].delegatedTo,
delegatedToUpdate
);
emit UpdatedDelegation(
msg.sender,
delegate,
delta,
shares,
delegatedToUpdate
);
}
}
| 2,456,820 | [
1,
8924,
716,
4792,
331,
17128,
7212,
23595,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
17801,
6835,
24117,
367,
1989,
353,
534,
359,
1060,
1989,
16,
1599,
13451,
367,
1989,
288,
203,
565,
445,
7152,
58,
17128,
13788,
12,
2867,
7152,
13,
7010,
3639,
3903,
203,
3639,
3849,
203,
203,
565,
288,
203,
3639,
312,
474,
17631,
1060,
5621,
203,
3639,
2583,
12,
203,
5411,
7152,
480,
1758,
12,
20,
13,
597,
7152,
480,
1234,
18,
15330,
16,
203,
5411,
315,
2864,
30,
1962,
7152,
6,
203,
5411,
11272,
203,
3639,
2583,
12,
203,
5411,
729,
9586,
12,
22216,
13,
422,
1758,
12,
20,
3631,
203,
5411,
315,
2864,
30,
27687,
353,
11158,
1776,
6,
203,
5411,
11272,
203,
3639,
2177,
2502,
729,
273,
3677,
63,
3576,
18,
15330,
15533,
203,
3639,
2583,
12,
203,
5411,
729,
18,
2722,
26945,
1891,
4921,
397,
512,
30375,
67,
7096,
411,
1203,
18,
5508,
16,
203,
5411,
315,
2864,
30,
19301,
7152,
19907,
6,
203,
5411,
11272,
203,
3639,
729,
18,
2722,
26945,
1891,
4921,
273,
1203,
18,
5508,
31,
203,
203,
3639,
2254,
5034,
729,
24051,
273,
729,
24051,
12,
3576,
18,
15330,
1769,
203,
3639,
2583,
12,
203,
5411,
729,
24051,
480,
374,
16,
203,
5411,
315,
2864,
30,
21940,
1158,
24123,
358,
7152,
6,
203,
5411,
11272,
203,
203,
3639,
1758,
2416,
9586,
273,
729,
9586,
12,
3576,
18,
15330,
1769,
203,
3639,
2583,
12,
203,
5411,
2416,
9586,
480,
7152,
16,
203,
5411,
315,
2864,
30,
17009,
30055,
6,
203,
5411,
11272,
203,
3639,
309,
261,
11515,
9586,
480,
1758,
12,
20,
3719,
288,
203,
5411,
1089,
14431,
2
]
|
./partial_match/42/0x76c2F686d7e674A3042b3B65841Ffc38682C37FB/sources/RewardsDistribution.sol | * @notice Edits a RewardDistribution in the distributions array. @param index The index of the DistributionData to edit @param destination The destination address. Send the same address to keep or different address to change it. @param amount The amount of tokens to edit. Send the same number to keep or change the amount of tokens to send./ | function editRewardDistribution(uint index, address destination, uint amount) external onlyOwner returns (bool) {
require(index <= distributions.length - 1, "index out of bounds");
distributions[index].destination = destination;
distributions[index].amount = amount;
return true;
}
| 3,435,811 | [
1,
2671,
1282,
279,
534,
359,
1060,
9003,
316,
326,
23296,
526,
18,
225,
770,
1021,
770,
434,
326,
17547,
751,
358,
3874,
225,
2929,
1021,
2929,
1758,
18,
2479,
326,
1967,
1758,
358,
3455,
578,
3775,
1758,
358,
2549,
518,
18,
225,
3844,
1021,
3844,
434,
2430,
358,
3874,
18,
2479,
326,
1967,
1300,
358,
3455,
578,
2549,
326,
3844,
434,
2430,
358,
1366,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
3874,
17631,
1060,
9003,
12,
11890,
770,
16,
1758,
2929,
16,
2254,
3844,
13,
3903,
1338,
5541,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
1615,
1648,
23296,
18,
2469,
300,
404,
16,
315,
1615,
596,
434,
4972,
8863,
203,
203,
3639,
23296,
63,
1615,
8009,
10590,
273,
2929,
31,
203,
3639,
23296,
63,
1615,
8009,
8949,
273,
3844,
31,
203,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
// 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/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @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/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/finance/PaymentSplitter.sol
pragma solidity ^0.8.0;
/**
* @title PaymentSplitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*/
contract PaymentSplitter is Context {
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
constructor(address[] memory payees, uint256[] memory shares_) payable {
require(
payees.length == shares_.length,
"PaymentSplitter: payees and shares length mismatch"
);
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive() external payable virtual {
emit PaymentReceived(_msgSender(), msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, "PaymentSplitter: account has no shares");
uint256 totalReceived = address(this).balance + _totalReleased;
uint256 payment = (totalReceived * _shares[account]) /
_totalShares -
_released[account];
require(payment != 0, "PaymentSplitter: account is not due payment");
_released[account] = _released[account] + payment;
_totalReleased = _totalReleased + payment;
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(
account != address(0),
"PaymentSplitter: account is the zero address"
);
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(
_shares[account] == 0,
"PaymentSplitter: account already has shares"
);
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
}
// 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: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(IERC165, ERC721)
returns (bool)
{
return
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
require(
index < ERC721.balanceOf(owner),
"ERC721Enumerable: owner index out of bounds"
);
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
require(
index < ERC721Enumerable.totalSupply(),
"ERC721Enumerable: global index out of bounds"
);
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId)
private
{
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: @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: contracts/DegenzDenGenesis.sol
pragma solidity ^0.8.0;
/// @title Degenz Den Smart Contract for the Genesis collection
/// @author Aric Kuter
/// @dev All function calls are currently implemented without events to save on gas
contract DegenzDen is ERC721Enumerable, Ownable, PaymentSplitter {
using Strings for uint256;
using Counters for Counters.Counter;
Counters.Counter private _tokenIdCounter;
/// ============ Mutable storage ============
/// @notice URI for revealed metadata
string public baseURI;
/// @notice URI for hidden metadata
string public hiddenURI;
/// @notice Extension for metadata files
string public baseExtension = ".json";
/// @notice Mint cost per NFT
uint256 public COST = 0.04 ether;
/// @notice Max supply of NFTs
uint256 public MAX_SUPPLY = 2000;
/// @notice Max mint amount (< is used so 5 is actual limit)
uint256 public MAX_MINT = 6;
/// @notice Pause or Resume minting
bool public mintMain = false;
/// @notice Open whitelisting
bool public mintWhitelist = false;
/// @notice Reveal metadata
bool public revealed = false;
/// @notice Map address to minted amount
mapping(address => uint256) public addressMintedBalance;
address[] PAYEES = [
0x954e501b622EFfEC678f30EA9B85D7A6a6cECBD3, /// @notice C
0xEF4DF42EE7D7ee516399fa54C2D95c4fc1AA67d0, /// @notice A
0xffFa8dF59b90FF4454e8B54F54B3655990710710, /// @notice GG
0x18cdac4146D3B41f0fC9B70B5De3fB3282F83855 /// @notice KIC
];
uint256[] SHARES = [46, 22, 22, 10];
/// ============ Constructor ============
/// @param _name name of NFT
/// @param _symbol symbol of NFT
/// @param _initBaseURI URI for revealed metadata in format: ipfs://HASH/
/// @param _initHiddenURI URI for hidden metadata in format: ipfs://HASH/
/// @param _OWNER_MINT_AMOUNT Number of NFTs to mint to the owners address
constructor(
string memory _name,
string memory _symbol,
string memory _initBaseURI,
string memory _initHiddenURI,
uint256 _OWNER_MINT_AMOUNT
) ERC721(_name, _symbol) PaymentSplitter(PAYEES, SHARES) {
baseURI = _initBaseURI;
hiddenURI = _initHiddenURI;
/// @notice increment counter to start at 1 instead of 0
_tokenIdCounter.increment();
/// @notice mint to owners address
reserveTokens(owner(), _OWNER_MINT_AMOUNT);
}
/// @return Returns the baseURI
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
/// @notice Mint NFTs to senders address
/// @param _mintAmount Number of NFTs to mint
function mint(uint256 _mintAmount, bytes memory _signature)
external
payable
{
/// @notice Check the mint is active or the sender is whitelisted
require(
mintMain ||
(mintWhitelist && isValidAccessMessage(msg.sender, _signature)),
"Minting unavailable"
);
require(_mintAmount > 0 && _mintAmount < MAX_MINT, "Invalid amount");
uint256 _tokenId = _tokenIdCounter.current();
require(_tokenId + _mintAmount <= MAX_SUPPLY, "Supply limit reached");
require(
addressMintedBalance[msg.sender] + _mintAmount < MAX_MINT,
"Mint limit reached"
);
require(msg.value == COST * _mintAmount, "Incorrect ETH");
/// @notice Increment minted amount for user and safe mint to address
addressMintedBalance[msg.sender] += _mintAmount;
for (uint256 i = 0; i < _mintAmount; i++) {
_safeMint(msg.sender, _tokenId + i);
_tokenIdCounter.increment();
}
}
/// @notice Reserved mint function for owner only
/// @param _to Address to send tokens to
/// @param _mintAmount Number of NFTs to mint
function reserveTokens(address _to, uint256 _mintAmount) public onlyOwner {
uint256 _tokenId = _tokenIdCounter.current();
/// @notice Safely mint the NFTs
for (uint256 i = 0; i < _mintAmount; i++) {
_safeMint(_to, _tokenId + i);
_tokenIdCounter.increment();
}
}
/*
* @dev Verifies if message was signed by owner to give access to _add for this contract.
* Assumes Geth signature prefix.
* @param _add Address of agent with access
* @param _v ECDSA signature parameter v.
* @param _r ECDSA signature parameters r.
* @param _s ECDSA signature parameters s.
* @return Validity of access message for a given address.
*/
function isValidAccessMessage(address _addr, bytes memory _signature)
public
view
returns (bool)
{
(bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature);
bytes32 messageHash = getMessageHash(address(this), _addr);
bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash);
return owner() == ecrecover(ethSignedMessageHash, v, r, s);
}
function getMessageHash(address _contractAddr, address _addr)
public
pure
returns (bytes32)
{
return keccak256(abi.encodePacked(_contractAddr, _addr));
}
function getEthSignedMessageHash(bytes32 _messageHash)
public
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked(
"\x19Ethereum Signed Message:\n32",
_messageHash
)
);
}
function recoverSigner(
bytes32 _ethSignedMessageHash,
bytes memory _signature
) public pure returns (address) {
(bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature);
return ecrecover(_ethSignedMessageHash, v, r, s);
}
function splitSignature(bytes memory sig)
public
pure
returns (
bytes32 r,
bytes32 s,
uint8 v
)
{
require(sig.length == 65, "invalid signature length");
assembly {
/*
First 32 bytes stores the length of the signature
add(sig, 32) = pointer of sig + 32
effectively, skips first 32 bytes of signature
mload(p) loads next 32 bytes starting at the memory address p into memory
*/
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
// implicitly return (r, s, v)
}
/// @return Returns a conststructed string in the format: //ipfs/HASH/[tokenId].json
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for NonExistent Token."
);
if (!revealed) {
return hiddenURI;
}
string memory currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
baseExtension
)
)
: "";
}
/// @notice Reveal metadata
function reveal() external onlyOwner {
revealed = true;
}
/// @notice Set the URI of the hidden metadata
/// @param _hiddenURI URI for hidden metadata NOTE: This URI must be the link to the exact file in format: ipfs//HASH/
function setHiddenURI(string memory _hiddenURI) external onlyOwner {
hiddenURI = _hiddenURI;
}
/// @notice Set URI of the metadata
/// @param _newBaseURI URI for revealed metadata
function setBaseURI(string memory _newBaseURI) external onlyOwner {
baseURI = _newBaseURI;
}
/// @notice Set the base extension for the metadata
/// @param _newBaseExtension Base extension value
function setBaseExtension(string memory _newBaseExtension)
external
onlyOwner
{
baseExtension = _newBaseExtension;
}
function getUserAirdrops(address _user) external view returns (uint256) {
return addressMintedBalance[_user];
}
/// @notice Toggle mintMain
function toggleMintMain() external onlyOwner {
mintMain = !mintMain;
}
/// @notice Toggle mintWhitelist
function toggleMintWhitelist() external onlyOwner {
mintWhitelist = !mintWhitelist;
}
} | first 32 bytes, after the length prefix second 32 bytes final byte (first byte of the next 32 bytes) | function splitSignature(bytes memory sig)
public
pure
returns (
bytes32 r,
bytes32 s,
uint8 v
)
{
require(sig.length == 65, "invalid signature length");
assembly {
First 32 bytes stores the length of the signature
add(sig, 32) = pointer of sig + 32
effectively, skips first 32 bytes of signature
mload(p) loads next 32 bytes starting at the memory address p into memory
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
| 6,137,185 | [
1,
3645,
3847,
1731,
16,
1839,
326,
769,
1633,
2205,
3847,
1731,
727,
1160,
261,
3645,
1160,
434,
326,
1024,
3847,
1731,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1416,
5374,
12,
3890,
3778,
3553,
13,
203,
3639,
1071,
203,
3639,
16618,
203,
3639,
1135,
261,
203,
5411,
1731,
1578,
436,
16,
203,
5411,
1731,
1578,
272,
16,
203,
5411,
2254,
28,
331,
203,
3639,
262,
203,
565,
288,
203,
3639,
2583,
12,
7340,
18,
2469,
422,
15892,
16,
315,
5387,
3372,
769,
8863,
203,
203,
3639,
19931,
288,
203,
5411,
5783,
3847,
1731,
9064,
326,
769,
434,
326,
3372,
203,
5411,
527,
12,
7340,
16,
3847,
13,
273,
4407,
434,
3553,
397,
3847,
203,
5411,
23500,
16,
24646,
1122,
3847,
1731,
434,
3372,
203,
5411,
312,
945,
12,
84,
13,
6277,
1024,
3847,
1731,
5023,
622,
326,
3778,
1758,
293,
1368,
3778,
203,
203,
5411,
436,
519,
312,
945,
12,
1289,
12,
7340,
16,
3847,
3719,
203,
5411,
272,
519,
312,
945,
12,
1289,
12,
7340,
16,
5178,
3719,
203,
5411,
331,
519,
1160,
12,
20,
16,
312,
945,
12,
1289,
12,
7340,
16,
19332,
20349,
203,
3639,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.24;
contract RSEvents {
// fired whenever a player registers a name
event onNewName
(
uint256 indexed playerID,
address indexed playerAddress,
bytes32 indexed playerName,
bool isNewPlayer,
uint256 affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 amountPaid,
uint256 timeStamp
);
// fired at end of buy or reload
event onEndTx
(
uint256 compressedData,
uint256 compressedIDs,
bytes32 playerName,
address playerAddress,
uint256 ethIn,
uint256 keysBought,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 genAmount,
uint256 potAmount,
uint256 airDropPot
);
// fired whenever theres a withdraw
event onWithdraw
(
uint256 indexed playerID,
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 timeStamp
);
// fired whenever a withdraw forces end round to be ran
event onWithdrawAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethOut,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 genAmount
);
// fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 genAmount
);
// fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 genAmount
);
// fired whenever an affiliate is paid
event onAffiliatePayout
(
uint256 indexed affiliateID,
address affiliateAddress,
bytes32 affiliateName,
uint256 indexed buyerID,
uint256 amount,
uint256 timeStamp
);
}
contract modularLastUnicorn is RSEvents {}
contract LastUnicorn is modularLastUnicorn {
using SafeMath for *;
using NameFilter for string;
using RSKeysCalc for uint256;
// TODO: check address
UnicornInterfaceForForwarder constant private TeamUnicorn = UnicornInterfaceForForwarder(0xBB14004A6f3D15945B3786012E00D9358c63c92a);
UnicornBookInterface constant private UnicornBook = UnicornBookInterface(0x98547788f328e1011065E4068A8D72bacA1DDB49);
string constant public name = "LastUnicorn Round #1";
string constant public symbol = "RS1";
uint256 private rndGap_ = 0;
// TODO: check time
uint256 constant private rndInit_ = 1 hours; // round timer starts at this
uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer
uint256 constant private rndMax_ = 24 hours; // max length a round timer can be
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes)
//=============================|================================================
uint256 public airDropPot_; // person who gets the airdrop wins part of this pot
uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop
//****************
// PLAYER DATA
//****************
mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address
mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name
mapping (uint256 => RSdatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => RSdatasets.PlayerRounds) public plyrRnds_; // (pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own)
//****************
// ROUND DATA
//****************
RSdatasets.Round public round_; // round data
//****************
// TEAM FEE DATA
//****************
uint256 public fees_ = 60; // fee distribution
uint256 public potSplit_ = 45; // pot split distribution
//==============================================================================
// _ _ _ __|_ _ __|_ _ _ .
// (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy)
//==============================================================================
constructor()
public
{
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet");
_;
}
/**
* @dev prevents contracts from interacting with LastUnicorn
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0, "non smart contract address only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "too little money");
require(_eth <= 100000000000000000000000, "too much money");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// buy core
buyCore(_pID, plyr_[_pID].laff, _eventData_);
}
/**
* @dev converts all incoming ethereum to keys.
* -functionhash- 0x8f38f309 (using ID for affiliate)
* -functionhash- 0x98a0871d (using address for affiliate)
* -functionhash- 0xa65b37a1 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
*/
function buyXid(uint256 _affCode)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// buy core
buyCore(_pID, _affCode, _eventData_);
}
function buyXaddr(address _affCode)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// buy core
buyCore(_pID, _affID, _eventData_);
}
function buyXname(bytes32 _affCode)
isActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
RSdatasets.EventReturns memory _eventData_ = determinePID(_eventData_);
// fetch player id
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// buy core
buyCore(_pID, _affID, _eventData_);
}
/**
* @dev essentially the same as buy, but instead of you sending ether
* from your wallet, it uses your unwithdrawn earnings.
* -functionhash- 0x349cdcac (using ID for affiliate)
* -functionhash- 0x82bfc739 (using address for affiliate)
* -functionhash- 0x079ce327 (using name for affiliate)
* @param _affCode the ID/address/name of the player who gets the affiliate fee
* @param _eth amount of earnings to use (remainder returned to gen vault)
*/
function reLoadXid(uint256 _affCode, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
RSdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == 0 || _affCode == _pID)
{
// use last stored affiliate code
_affCode = plyr_[_pID].laff;
// if affiliate code was given & its not the same as previously stored
} else if (_affCode != plyr_[_pID].laff) {
// update last affiliate
plyr_[_pID].laff = _affCode;
}
// reload core
reLoadCore(_pID, _affCode, _eth, _eventData_);
}
function reLoadXaddr(address _affCode, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
RSdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == address(0) || _affCode == msg.sender)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxAddr_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// reload core
reLoadCore(_pID, _affID, _eth, _eventData_);
}
function reLoadXname(bytes32 _affCode, uint256 _eth)
isActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
RSdatasets.EventReturns memory _eventData_;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// manage affiliate residuals
uint256 _affID;
// if no affiliate code was given or player tried to use their own, lolz
if (_affCode == '' || _affCode == plyr_[_pID].name)
{
// use last stored affiliate code
_affID = plyr_[_pID].laff;
// if affiliate code was given
} else {
// get affiliate ID from aff Code
_affID = pIDxName_[_affCode];
// if affID is not the same as previously stored
if (_affID != plyr_[_pID].laff)
{
// update last affiliate
plyr_[_pID].laff = _affID;
}
}
// reload core
reLoadCore(_pID, _affID, _eth, _eventData_);
}
/**
* @dev withdraws all of your earnings.
* -functionhash- 0x3ccfd60b
*/
function withdraw()
isActivated()
isHuman()
public
{
// grab time
uint256 _now = now;
// fetch player ID
uint256 _pID = pIDxAddr_[msg.sender];
// setup temp var for player eth
uint256 _eth;
// check to see if round has ended and no one has run round end yet
if (_now > round_.end && round_.ended == false && round_.plyr != 0)
{
// set up our tx event data
RSdatasets.EventReturns memory _eventData_;
// end the round (distributes pot)
round_.ended = true;
_eventData_ = endRound(_eventData_);
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire withdraw and distribute event
emit RSEvents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount
);
// in any other situation
} else {
// get their earnings
_eth = withdrawEarnings(_pID);
// gib moni
if (_eth > 0)
plyr_[_pID].addr.transfer(_eth);
// fire withdraw event
emit RSEvents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now);
}
}
/**
* @dev use these to register names. they are just wrappers that will send the
* registration requests to the PlayerBook contract. So registering here is the
* same as registering there. UI will always display the last name you registered.
* but you will still own all previously registered names to use as affiliate
* links.
* - must pay a registration fee.
* - name must be unique
* - names will be converted to lowercase
* - name cannot start or end with a space
* - cannot have more than 1 space in a row
* - cannot be only numbers
* - cannot start with 0x
* - name must be at least 1 char
* - max length of 32 characters long
* - allowed characters: a-z, 0-9, and space
* -functionhash- 0x921dec21 (using ID for affiliate)
* -functionhash- 0x3ddd4698 (using address for affiliate)
* -functionhash- 0x685ffd83 (using name for affiliate)
* @param _nameString players desired name
* @param _affCode affiliate ID, address, or name of who referred you
* @param _all set to true if you want this to push your info to all games
* (this might cost a lot of gas)
*/
function registerNameXID(string _nameString, uint256 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = UnicornBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXaddr(string _nameString, address _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = UnicornBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
function registerNameXname(string _nameString, bytes32 _affCode, bool _all)
isHuman()
public
payable
{
bytes32 _name = _nameString.nameFilter();
address _addr = msg.sender;
uint256 _paid = msg.value;
(bool _isNewPlayer, uint256 _affID) = UnicornBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all);
uint256 _pID = pIDxAddr_[_addr];
// fire event
emit RSEvents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now);
}
//==============================================================================
// _ _ _|__|_ _ _ _ .
// (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan)
//=====_|=======================================================================
/**
* @dev return the price buyer will pay for next 1 individual key.
* -functionhash- 0x018a25e8
* @return price for next key bought (in wei format)
*/
function getBuyPrice()
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0)))
return ( (round_.keys.add(1000000000000000000)).ethRec(1000000000000000000) );
else // rounds over. need price for new round
return ( 75000000000000 ); // init
}
/**
* @dev returns time left. dont spam this, you'll ddos yourself from your node
* provider
* -functionhash- 0xc7e284b8
* @return time left in seconds
*/
function getTimeLeft()
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
if (_now < round_.end)
if (_now > round_.strt + rndGap_)
return( (round_.end).sub(_now) );
else
return( (round_.strt + rndGap_).sub(_now));
else
return(0);
}
/**
* @dev returns player earnings per vaults
* -functionhash- 0x63066434
* @return winnings vault
* @return general vault
* @return affiliate vault
*/
function getPlayerVaults(uint256 _pID)
public
view
returns(uint256 ,uint256, uint256)
{
// if round has ended. but round end has not been run (so contract has not distributed winnings)
if (now > round_.end && round_.ended == false && round_.plyr != 0)
{
// if player is winner
if (round_.plyr == _pID)
{
return
(
(plyr_[_pID].win).add( ((round_.pot).mul(48)) / 100 ),
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID).sub(plyrRnds_[_pID].mask) ),
plyr_[_pID].aff
);
// if player is not the winner
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID).sub(plyrRnds_[_pID].mask) ),
plyr_[_pID].aff
);
}
// if round is still going on, or round has ended and round end has been ran
} else {
return
(
plyr_[_pID].win,
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID)),
plyr_[_pID].aff
);
}
}
/**
* solidity hates stack limits. this lets us avoid that hate
*/
function getPlayerVaultsHelper(uint256 _pID)
private
view
returns(uint256)
{
return( ((((round_.mask).add(((((round_.pot).mul(potSplit_)) / 100).mul(1000000000000000000)) / (round_.keys))).mul(plyrRnds_[_pID].keys)) / 1000000000000000000) );
}
/**
* @dev returns all current round info needed for front end
* -functionhash- 0x747dff42
* @return total keys
* @return time ends
* @return time started
* @return current pot
* @return current player ID in lead
* @return current player in leads address
* @return current player in leads name
* @return airdrop tracker # & airdrop pot
*/
function getCurrentRoundInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256)
{
return
(
round_.keys, //0
round_.end, //1
round_.strt, //2
round_.pot, //3
round_.plyr, //4
plyr_[round_.plyr].addr, //5
plyr_[round_.plyr].name, //6
airDropTracker_ + (airDropPot_ * 1000) //7
);
}
/**
* @dev returns player info based on address. if no address is given, it will
* use msg.sender
* -functionhash-
* @param _addr address of the player you want to lookup
* @return player ID
* @return player name
* @return keys owned (current round)
* @return winnings vault
* @return general vault
* @return affiliate vault
* @return player round eth
*/
function getPlayerInfoByAddress(address _addr)
public
view
returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256)
{
if (_addr == address(0))
{
_addr == msg.sender;
}
uint256 _pID = pIDxAddr_[_addr];
return
(
_pID, //0
plyr_[_pID].name, //1
plyrRnds_[_pID].keys, //2
plyr_[_pID].win, //3
(plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID)), //4
plyr_[_pID].aff, //5
plyrRnds_[_pID].eth //6
);
}
//==============================================================================
// _ _ _ _ | _ _ . _ .
// (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine)
//=====================_|=======================================================
/**
* @dev logic runs whenever a buy order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function buyCore(uint256 _pID, uint256 _affID, RSdatasets.EventReturns memory _eventData_)
private
{
// grab time
uint256 _now = now;
// if round is active
if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0)))
{
// call core
core(_pID, msg.value, _affID, _eventData_);
// if round is not active
} else {
// check to see if end round needs to be ran
if (_now > round_.end && round_.ended == false)
{
// end the round (distributes pot) & start new round
round_.ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit RSEvents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount
);
}
// put eth in players vault
plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value);
}
}
/**
* @dev logic runs whenever a reload order is executed. determines how to handle
* incoming eth depending on if we are in an active round or not
*/
function reLoadCore(uint256 _pID, uint256 _affID, uint256 _eth, RSdatasets.EventReturns memory _eventData_)
private
{
// grab time
uint256 _now = now;
// if round is active
if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0)))
{
// get earnings from all vaults and return unused to gen vault
// because we use a custom safemath library. this will throw if player
// tried to spend more eth than they have.
plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth);
// call core
core(_pID, _eth, _affID, _eventData_);
// if round is not active and end round needs to be ran
} else if (_now > round_.end && round_.ended == false) {
// end the round (distributes pot) & start new round
round_.ended = true;
_eventData_ = endRound(_eventData_);
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit RSEvents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount
);
}
}
/**
* @dev this is the core logic for any buy/reload that happens while a round
* is live.
*/
function core(uint256 _pID, uint256 _eth, uint256 _affID, RSdatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
if (round_.eth < 100000000000000000000 && plyrRnds_[_pID].eth.add(_eth) > 10000000000000000000)
{
uint256 _availableLimit = (10000000000000000000).sub(plyrRnds_[_pID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_.eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys);
// set new leaders
if (round_.plyr != _pID)
round_.plyr = _pID;
// set the new leader bool to true
_eventData_.compressedData = _eventData_.compressedData + 100;
}
// manage airdrops
if (_eth >= 100000000000000000)
{
airDropTracker_++;
if (airdrop() == true)
{
// gib muni
uint256 _prize;
if (_eth >= 10000000000000000000)
{
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(75)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 3 prize was won
_eventData_.compressedData += 300000000000000000000000000000000;
} else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(50)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 2 prize was won
_eventData_.compressedData += 200000000000000000000000000000000;
} else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) {
// calculate prize and give it to winner
_prize = ((airDropPot_).mul(25)) / 100;
plyr_[_pID].win = (plyr_[_pID].win).add(_prize);
// adjust airDropPot
airDropPot_ = (airDropPot_).sub(_prize);
// let event know a tier 1 prize was won
_eventData_.compressedData += 100000000000000000000000000000000;
}
// set airdrop happened bool to true
_eventData_.compressedData += 10000000000000000000000000000000;
// let event know how much was won
_eventData_.compressedData += _prize * 1000000000000000000000000000000000;
// reset air drop tracker
airDropTracker_ = 0;
}
}
// store the air drop tracker number (number of buys since last airdrop)
_eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000);
// update player
plyrRnds_[_pID].keys = _keys.add(plyrRnds_[_pID].keys);
plyrRnds_[_pID].eth = _eth.add(plyrRnds_[_pID].eth);
// update round
round_.keys = _keys.add(round_.keys);
round_.eth = _eth.add(round_.eth);
// distribute eth
_eventData_ = distributeExternal(_pID, _eth, _affID, _eventData_);
_eventData_ = distributeInternal(_pID, _eth, _keys, _eventData_);
// call end tx function to fire end tx event.
endTx(_pID, _eth, _keys, _eventData_);
}
}
//==============================================================================
// _ _ | _ | _ _|_ _ _ _ .
// (_(_||(_|_||(_| | (_)| _\ .
//==============================================================================
/**
* @dev calculates unmasked earnings (just calculates, does not update mask)
* @return earnings in wei format
*/
function calcUnMaskedEarnings(uint256 _pID)
private
view
returns(uint256)
{
return((((round_.mask).mul(plyrRnds_[_pID].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID].mask));
}
/**
* @dev returns the amount of keys you would get given an amount of eth.
* -functionhash- 0xce89c80c
* @param _eth amount of eth sent in
* @return keys received
*/
function calcKeysReceived(uint256 _eth)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0)))
return ( (round_.eth).keysRec(_eth) );
else // rounds over. need keys for new round
return ( (_eth).keys() );
}
/**
* @dev returns current eth price for X keys.
* -functionhash- 0xcf808000
* @param _keys number of keys desired (in 18 decimal format)
* @return amount of eth needed to send
*/
function iWantXKeys(uint256 _keys)
public
view
returns(uint256)
{
// grab time
uint256 _now = now;
// are we in a round?
if (_now > round_.strt + rndGap_ && (_now <= round_.end || (_now > round_.end && round_.plyr == 0)))
return ( (round_.keys.add(_keys)).ethRec(_keys) );
else // rounds over. need price for new round
return ( (_keys).eth() );
}
//==============================================================================
// _|_ _ _ | _ .
// | (_)(_)|_\ .
//==============================================================================
/**
* @dev receives name/player info from names contract
*/
function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff)
external
{
require (msg.sender == address(UnicornBook), "only UnicornBook can call this function");
if (pIDxAddr_[_addr] != _pID)
pIDxAddr_[_addr] = _pID;
if (pIDxName_[_name] != _pID)
pIDxName_[_name] = _pID;
if (plyr_[_pID].addr != _addr)
plyr_[_pID].addr = _addr;
if (plyr_[_pID].name != _name)
plyr_[_pID].name = _name;
if (plyr_[_pID].laff != _laff)
plyr_[_pID].laff = _laff;
if (plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev receives entire player name list
*/
function receivePlayerNameList(uint256 _pID, bytes32 _name)
external
{
require (msg.sender == address(UnicornBook), "only UnicornBook can call this function");
if(plyrNames_[_pID][_name] == false)
plyrNames_[_pID][_name] = true;
}
/**
* @dev gets existing or registers new pID. use this when a player may be new
* @return pID
*/
function determinePID(RSdatasets.EventReturns memory _eventData_)
private
returns (RSdatasets.EventReturns)
{
uint256 _pID = pIDxAddr_[msg.sender];
// if player is new to this version of LastUnicorn
if (_pID == 0)
{
// grab their player ID, name and last aff ID, from player names contract
_pID = UnicornBook.getPlayerID(msg.sender);
bytes32 _name = UnicornBook.getPlayerName(_pID);
uint256 _laff = UnicornBook.getPlayerLAff(_pID);
// set up player account
pIDxAddr_[msg.sender] = _pID;
plyr_[_pID].addr = msg.sender;
if (_name != "")
{
pIDxName_[_name] = _pID;
plyr_[_pID].name = _name;
plyrNames_[_pID][_name] = true;
}
if (_laff != 0 && _laff != _pID)
plyr_[_pID].laff = _laff;
// set the new player bool to true
_eventData_.compressedData = _eventData_.compressedData + 1;
}
return (_eventData_);
}
/**
* @dev decides if round end needs to be run & new round started. and if
* player unmasked earnings from previously played rounds need to be moved.
*/
function managePlayer(uint256 _pID, RSdatasets.EventReturns memory _eventData_)
private
returns (RSdatasets.EventReturns)
{
// set the joined round bool to true
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(RSdatasets.EventReturns memory _eventData_)
private
returns (RSdatasets.EventReturns)
{
// grab our winning player and team id's
uint256 _winPID = round_.plyr;
// grab our pot amount
// add airdrop pot into the final pot
uint256 _pot = round_.pot + airDropPot_;
// calculate our winner share, community rewards, gen share,
// p3d share, and amount reserved for next pot
uint256 _win = (_pot.mul(45)) / 100;
uint256 _com = (_pot / 10);
uint256 _gen = (_pot.mul(potSplit_)) / 100;
// calculate ppt for round mask
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_.keys);
uint256 _dust = _gen.sub((_ppt.mul(round_.keys)) / 1000000000000000000);
if (_dust > 0)
{
_gen = _gen.sub(_dust);
_com = _com.add(_dust);
}
// pay our winner
plyr_[_winPID].win = _win.add(plyr_[_winPID].win);
// community rewards
if (!address(TeamUnicorn).call.value(_com)(bytes4(keccak256("deposit()"))))
{
_gen = _gen.add(_com);
_com = 0;
}
// distribute gen portion to key holders
round_.mask = _ppt.add(round_.mask);
// prepare event data
_eventData_.compressedData = _eventData_.compressedData + (round_.end * 1000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000);
_eventData_.winnerAddr = plyr_[_winPID].addr;
_eventData_.winnerName = plyr_[_winPID].name;
_eventData_.amountWon = _win;
_eventData_.genAmount = _gen;
_eventData_.newPot = 0;
return(_eventData_);
}
/**
* @dev moves any unmasked earnings to gen vault. updates earnings mask
*/
function updateGenVault(uint256 _pID)
private
{
uint256 _earnings = calcUnMaskedEarnings(_pID);
if (_earnings > 0)
{
// put in gen vault
plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen);
// zero out their earnings by updating mask
plyrRnds_[_pID].mask = _earnings.add(plyrRnds_[_pID].mask);
}
}
/**
* @dev updates round timer based on number of whole keys bought.
*/
function updateTimer(uint256 _keys)
private
{
// grab time
uint256 _now = now;
// calculate time based on number of keys bought
uint256 _newTime;
if (_now > round_.end && round_.plyr == 0)
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now);
else
_newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_.end);
// compare to max and set new end time
if (_newTime < (rndMax_).add(_now))
round_.end = _newTime;
else
round_.end = rndMax_.add(_now);
}
/**
* @dev generates a random number between 0-99 and checks to see if thats
* resulted in an airdrop win
* @return do we have a winner?
*/
function airdrop()
private
view
returns(bool)
{
uint256 seed = uint256(keccak256(abi.encodePacked(
(block.timestamp).add
(block.difficulty).add
((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add
(block.gaslimit).add
((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add
(block.number)
)));
if((seed - ((seed / 1000) * 1000)) < airDropTracker_)
return(true);
else
return(false);
}
/**
* @dev distributes eth based on fees to com, aff, and p3d
*/
function distributeExternal(uint256 _pID, uint256 _eth, uint256 _affID, RSdatasets.EventReturns memory _eventData_)
private
returns(RSdatasets.EventReturns)
{
// pay 5% out to community rewards
uint256 _com = _eth * 5 / 100;
// distribute share to affiliate
uint256 _aff = _eth / 10;
// decide what to do with affiliate share of fees
// affiliate must not be self, and must have a name registered
if (_affID != _pID && plyr_[_affID].name != '') {
plyr_[_affID].aff = _aff.add(plyr_[_affID].aff);
emit RSEvents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _pID, _aff, now);
} else {
// no affiliates, add to community
_com += _aff;
}
if (!address(TeamUnicorn).call.value(_com)(bytes4(keccak256("deposit()"))))
{
// This ensures TeamUnicorn cannot influence the outcome
// bank migrations by breaking outgoing transactions.
}
return(_eventData_);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _pID, uint256 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_)
private
returns(RSdatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_)) / 100;
// toss 5% into airdrop pot
uint256 _air = (_eth / 20);
airDropPot_ = airDropPot_.add(_air);
// calculate pot (20%)
uint256 _pot = (_eth.mul(20) / 100);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_.pot = _pot.add(_dust).add(round_.pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_.keys);
round_.mask = _ppt.add(round_.mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID].mask = (((round_.mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_.keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _eth, uint256 _keys, RSdatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
emit RSEvents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.genAmount,
_eventData_.potAmount,
airDropPot_
);
}
/** upon contract deploy, it will be deactivated. this is a one time
* use function that will activate the contract. we do this so devs
* have time to set things up on the web end **/
bool public activated_ = false;
function activate()
public
{
// only owner can activate
// TODO: set owner
require(
(msg.sender == 0xcD0fce8d255349092496F131f2900DF25f0569F8),
"only owner can activate"
);
// can only be ran once
require(activated_ == false, "LastUnicorn already activated");
// activate the contract
activated_ = true;
round_.strt = now - rndGap_;
round_.end = now + rndInit_;
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library RSdatasets {
//compressedData key
// [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0]
// 0 - new player (bool)
// 1 - joined round (bool)
// 2 - new leader (bool)
// 3-5 - air drop tracker (uint 0-999)
// 6-16 - round end time
// 17 - winnerTeam
// 18 - 28 timestamp
// 29 - team
// 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico)
// 31 - airdrop happened bool
// 32 - airdrop tier
// 33 - airdrop amount won
//compressedIDs key
// [77-52][51-26][25-0]
// 0-25 - pID
// 26-51 - winPID
// 52-77 - rID
struct EventReturns {
uint256 compressedData;
uint256 compressedIDs;
address winnerAddr; // winner address
bytes32 winnerName; // winner name
uint256 amountWon; // amount won
uint256 newPot; // amount in new pot
uint256 genAmount; // amount distributed to gen
uint256 potAmount; // amount added to pot
}
struct Player {
address addr; // player address
bytes32 name; // player name
uint256 win; // winnings vault
uint256 gen; // general vault
uint256 aff; // affiliate vault
uint256 laff; // last affiliate id used
}
struct PlayerRounds {
uint256 eth; // eth player has added to round (used for eth limiter)
uint256 keys; // keys
uint256 mask; // player mask
}
struct Round {
uint256 plyr; // pID of player in lead
uint256 end; // time ends/ended
bool ended; // has round end function been ran
uint256 strt; // time round started
uint256 keys; // keys
uint256 eth; // total eth in
uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends)
uint256 mask; // global mask
}
}
//==============================================================================
// | _ _ _ | _ .
// |<(/_\/ (_(_||(_ .
//=======/======================================================================
library RSKeysCalc {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
interface UnicornInterfaceForForwarder {
function deposit() external payable returns(bool);
}
interface UnicornBookInterface {
function getPlayerID(address _addr) external returns (uint256);
function getPlayerName(uint256 _pID) external view returns (bytes32);
function getPlayerLAff(uint256 _pID) external view returns (uint256);
function getPlayerAddr(uint256 _pID) external view returns (address);
function getNameFee() external view returns (uint256);
function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256);
function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256);
}
library NameFilter {
/**
* @dev filters name strings
* -converts uppercase to lower case.
* -makes sure it does not start/end with a space
* -makes sure it does not contain multiple spaces in a row
* -cannot be only numbers
* -cannot start with 0x
* -restricts characters to A-Z, a-z, 0-9, and space.
* @return reprocessed string in bytes32 format
*/
function nameFilter(string _input)
internal
pure
returns(bytes32)
{
bytes memory _temp = bytes(_input);
uint256 _length = _temp.length;
//sorry limited to 32 characters
require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters");
// make sure it doesnt start with or end with space
require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space");
// make sure first two characters are not 0x
if (_temp[0] == 0x30)
{
require(_temp[1] != 0x78, "string cannot start with 0x");
require(_temp[1] != 0x58, "string cannot start with 0X");
}
// create a bool to track if we have a non number character
bool _hasNonNumber;
// convert & check
for (uint256 i = 0; i < _length; i++)
{
// if its uppercase A-Z
if (_temp[i] > 0x40 && _temp[i] < 0x5b)
{
// convert to lower case a-z
_temp[i] = byte(uint(_temp[i]) + 32);
// we have a non number
if (_hasNonNumber == false)
_hasNonNumber = true;
} else {
require
(
// require character is a space
_temp[i] == 0x20 ||
// OR lowercase a-z
(_temp[i] > 0x60 && _temp[i] < 0x7b) ||
// or 0-9
(_temp[i] > 0x2f && _temp[i] < 0x3a),
"string contains invalid characters"
);
// make sure theres not 2x spaces in a row
if (_temp[i] == 0x20)
require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces");
// see if we have a character other than a number
if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39))
_hasNonNumber = true;
}
}
require(_hasNonNumber == true, "string cannot be only numbers");
bytes32 _ret;
assembly {
_ret := mload(add(_temp, 32))
}
return (_ret);
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
* change notes: original SafeMath library from OpenZeppelin modified by Inventor
* - added sqrt
* - added sq
* - changed asserts to requires with error log outputs
* - removed div, its useless
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
if (a == 0) {
return 0;
}
c = a * b;
require(c / a == b, "SafeMath mul failed");
return c;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
require(b <= a, "SafeMath sub failed");
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b)
internal
pure
returns (uint256 c)
{
c = a + b;
require(c >= a, "SafeMath add failed");
return c;
}
/**
* @dev gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
} | only owner can activate TODO: set owner can only be ran once activate the contract | function activate()
public
{
require(
(msg.sender == 0xcD0fce8d255349092496F131f2900DF25f0569F8),
"only owner can activate"
);
require(activated_ == false, "LastUnicorn already activated");
activated_ = true;
round_.strt = now - rndGap_;
round_.end = now + rndInit_;
}
| 533,599 | [
1,
3700,
3410,
848,
10235,
2660,
30,
444,
3410,
848,
1338,
506,
18892,
3647,
10235,
326,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
10235,
1435,
203,
3639,
1071,
203,
565,
288,
203,
3639,
2583,
12,
203,
5411,
261,
3576,
18,
15330,
422,
374,
6511,
40,
20,
74,
311,
28,
72,
10395,
5026,
29,
5908,
3247,
10525,
42,
29315,
74,
5540,
713,
4577,
2947,
74,
20,
4313,
29,
42,
28,
3631,
203,
5411,
315,
3700,
3410,
848,
10235,
6,
203,
3639,
11272,
203,
540,
203,
3639,
2583,
12,
18836,
67,
422,
629,
16,
315,
3024,
984,
335,
14245,
1818,
14892,
8863,
203,
540,
203,
3639,
14892,
67,
273,
638,
31,
203,
540,
203,
3639,
3643,
27799,
701,
88,
273,
2037,
300,
20391,
14001,
67,
31,
203,
3639,
3643,
27799,
409,
273,
2037,
397,
20391,
2570,
67,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.8.0;
pragma abicoder v2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "abdk-libraries-solidity/ABDKMath64x64.sol";
abstract contract DirectBonusAware is Ownable {
/**
* @param stakedAmountInUsdt staked usdt amount required to get the multipliers (without decimals)
* @param multiplier reward bonus multiplier for referrer (in 0.0001 parts)
*/
struct ReferrerMultiplierData {
uint16 stakedAmountInUsdt;
uint16 multiplier;
}
uint16 public referralMultiplier; /// @dev multiplier for direct bonus for referrals of the referral program (in 0.0001 parts)
ReferrerMultiplierData[] public referrerMultipliers; /// @dev multipliers for direct bonuses for referrers of the referral program
mapping(address => address) public referrers; /// @dev referral address => referrer address
event ReferrerChanged(address indexed referral, address indexed referrer); /// @dev when referral set its referrer
event ReferrerBonusAccrued(address indexed referrer, uint128 amount); /// @dev when someone receives NMX as a direct referrer bonus
event ReferralBonusAccrued(address indexed referral, uint128 amount); /// @dev when someone receives NMX as a direct referral bonus
constructor() {
referralMultiplier = 500; // 500/10000 = 0.0500 = 0.05 = 5%
ReferrerMultiplierData storage item = referrerMultipliers.push();
item.stakedAmountInUsdt = 100;
item.multiplier = 500; // 500/10000 = 0.0500 = 0.05 = 5%
item = referrerMultipliers.push();
item.stakedAmountInUsdt = 300;
item.multiplier = 1000; // 1000/10000 = 0.1000 = 0.10 = 10%
item = referrerMultipliers.push();
item.stakedAmountInUsdt = 1000;
item.multiplier = 1500; // 1500/10000 = 0.1500 = 0.15 = 15%
item = referrerMultipliers.push();
item.stakedAmountInUsdt = 3000;
item.multiplier = 2000; // 2000/10000 = 0.2000 = 0.20 = 20%
item = referrerMultipliers.push();
item.stakedAmountInUsdt = 10000;
item.multiplier = 2500; // 2500/10000 = 0.2500 = 0.25 = 25%
}
/// @dev referral direct bonus multiplier can be changed by the owner
function setReferralMultiplier(uint16 _referralMultiplier)
external
onlyOwner
{
referralMultiplier = _referralMultiplier;
}
/// @dev referrer direct bonus multipliers can be changed by the owner
function setReferrerMultipliers(
ReferrerMultiplierData[] calldata newMultipliers
) external onlyOwner {
uint256 prevStakedAmountInUsdt =
newMultipliers.length > 0
? newMultipliers[0].stakedAmountInUsdt
: 0;
for (uint256 i = 1; i < newMultipliers.length; i++) {
ReferrerMultiplierData calldata newMultiplier = newMultipliers[i];
require(
newMultiplier.stakedAmountInUsdt > prevStakedAmountInUsdt,
"NmxStakingService: INVALID_ORDER"
);
prevStakedAmountInUsdt = newMultiplier.stakedAmountInUsdt;
}
delete referrerMultipliers;
for (uint256 i = 0; i < newMultipliers.length; i++) {
referrerMultipliers.push(newMultipliers[i]);
}
}
/// @dev every referral (address, tx.origin) can set its referrer. But only once. So nobody can change referrer if it has been set already
function setReferrer(address referrer) external {
address currentReferrer = referrers[tx.origin];
bool validReferrer =
currentReferrer == address(0) &&
referrer != address(0) &&
tx.origin != referrer;
require(validReferrer, "NmxStakingService: INVALID_REFERRER");
emit ReferrerChanged(tx.origin, referrer);
referrers[tx.origin] = referrer;
}
/**
* @dev returns current referrer direct bonus multiplier. Result is int128 compatible with ABDKMath64x64 lib.
*
* @param amountInUsdt staking lp tokens amount in USDT
* @param pairedTokenDecimals amount of decimals of paired token
*/
function getReferrerMultiplier(uint256 amountInUsdt, uint8 pairedTokenDecimals)
internal
view
returns (int128)
{
return
ABDKMath64x64.divu(
getReferrerMultipliers(amountInUsdt / 10**pairedTokenDecimals).multiplier,
10000
);
}
/// @dev returns current referral direct bonus multiplier. Result is int128 compatible with ABDKMath64x64 lib
function getReferralMultiplier() internal view returns (int128) {
return ABDKMath64x64.divu(referralMultiplier, 10000);
}
function getReferrerMultipliers(uint256 amountInUsdt)
private
view
returns (ReferrerMultiplierData memory multipliers)
{
uint256 referrerMultipliersLength = referrerMultipliers.length;
for (uint256 i = 0; i < referrerMultipliersLength; i++) {
ReferrerMultiplierData memory _multipliers = referrerMultipliers[i];
if (amountInUsdt >= _multipliers.stakedAmountInUsdt) {
multipliers = _multipliers;
} else {
break;
}
}
}
}
| * @param stakedAmountInUsdt staked usdt amount required to get the multipliers (without decimals) @param multiplier reward bonus multiplier for referrer (in 0.0001 parts)/ | struct ReferrerMultiplierData {
uint16 stakedAmountInUsdt;
uint16 multiplier;
}
| 12,534,174 | [
1,
334,
9477,
6275,
382,
3477,
7510,
384,
9477,
584,
7510,
3844,
1931,
358,
336,
326,
3309,
8127,
414,
261,
13299,
15105,
13,
225,
15027,
19890,
324,
22889,
15027,
364,
14502,
261,
267,
374,
18,
13304,
2140,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
1958,
3941,
11110,
23365,
751,
288,
203,
3639,
2254,
2313,
384,
9477,
6275,
382,
3477,
7510,
31,
203,
3639,
2254,
2313,
15027,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.2;
pragma experimental ABIEncoderV2;
import "truffle/Assert.sol";
import "../../contracts/Core/Core.sol";
/*
* Test modelled after the official ACTUS tests
*/
contract TestCoreScheduleACTUS is Core {
function test_Schedule_Daily_SD_shortstub() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.D, S.SHORT, true); // Every 1 day
uint256 start = 1451606400; // 2016-01-01T00:00:00
uint256 end = 1452816000; // 2016-01-15T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
for (uint i = 0; i < 15; i++){
expectedDates[i] = start + i*86400;
}
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Daily_EOM_shortstub() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.D, S.SHORT, true); // Every 1 day
uint256 start = 1451606400; // 2016-01-01T00:00:00
uint256 end = 1452816000; // 2016-01-15T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
for (uint i = 0; i < 15; i++){
expectedDates[i] = start + i*86400;
}
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Daily_SD_longstub() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.D, S.LONG, true); // Every 1 day
uint256 start = 1451606400; // 2016-01-01T00:00:00
uint256 end = 1452816000; // 2016-01-15T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
for (uint i = 0; i < 15; i++){
expectedDates[i] = start + i*86400;
}
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Daily_SD_shortstub_endT24() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.D, S.SHORT, true); // Every 1 day
uint256 start = 1451606400; // 2016-01-01T00:00:00
uint256 end = 1452815999; // 2016-01-14T23:59:59
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
for (uint i = 0; i < 14; i++){
expectedDates[i] = start + i*86400;
}
expectedDates[14] = 1452815999; // 2016-01-14T23:59:59
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Daily_SD_longstub_endT24() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.D, S.LONG, true); // Every 1 day
uint256 start = 1451606400; // 2016-01-01T00:00:00
uint256 end = 1452815999; // 2016-01-14T23:59:59
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
for (uint i = 0; i < 13; i++){
expectedDates[i] = start + i*86400;
}
expectedDates[13] = 1452815999; // 2016-01-14T23:59:59
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_BiDaily_SD_shortstub() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(2, P.D, S.SHORT, true); // Every 2 days
uint256 start = 1451606400; // 2016-01-01T00:00:00
uint256 end = 1453852800; // 2016-01-27T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
uint256 index;
for (uint i = 0; i < 28; i += 2){
expectedDates[index] = start + i*86400;
index++;
}
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_31Daily_EOM_shortstub_startEndMonth() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(31, P.D, S.SHORT, true);
uint256 start = 1456704000; // 2016-02-29T00:00:00
uint256 end = 1483228800; // 2017-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
expectedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Weekly_SD_shortstub() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.W, S.SHORT, true);
uint256 start = 1451606400; // 2016-01-01T00:00:00
uint256 end = 1459468800; // 2016-04-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
c = IPS(7, P.D, S.SHORT, true);
expectedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Weekly_SD_longstub() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.W, S.LONG, true);
uint256 start = 1451606400; // 2016-01-01T00:00:00
uint256 end = 1459468800; // 2016-04-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
c = IPS(7, P.D, S.LONG, true);
expectedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Weekly_EOM_shortstub_startMidMonth() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.W, S.SHORT, true);
uint256 start = 1451606400; // 2016-01-01T00:00:00
uint256 end = 1459468800; // 2016-04-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
c = IPS(7, P.D, S.SHORT, true);
expectedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Weekly_EOM_shortstub_startEndMonth() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.W, S.SHORT, true);
uint256 start = 1456704000; // 2016-02-29T00:00:00
uint256 end = 1459468800; // 2016-04-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
c = IPS(7, P.D, S.SHORT, true);
expectedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_4Weekly_SD_longstub_startEndMonth() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(4, P.W, S.LONG, true);
uint256 start = 1456704000; // 2016-02-29T00:00:00
uint256 end = 1483228800; // 2017-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
c = IPS(28, P.D, S.LONG, true);
expectedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_4Weekly_EOM_longstub_startEndMonth() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(4, P.W, S.LONG, true);
uint256 start = 1456704000; // 2016-02-29T00:00:00
uint256 end = 1483228800; // 2017-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
c = IPS(28, P.D, S.LONG, true);
expectedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_4Weekly_EOM_shortstub_startEndMonth() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(4, P.W, S.SHORT, true);
uint256 start = 1456704000; // 2016-02-29T00:00:00
uint256 end = 1483228800; // 2017-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
c = IPS(28, P.D, S.SHORT, true);
expectedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Monthly_SD_shortstub() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.M, S.SHORT, true);
uint256 start = 1451606400; // 2016-01-01T00:00:00
uint256 end = 1483228800; // 2017-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
expectedDates[0] = 1451606400; // 2016-01-01T00:00:00
expectedDates[1] = 1454284800; // 2016-02-01T00:00:00
expectedDates[2] = 1456790400; // 2016-03-01T00:00:00
expectedDates[3] = 1459468800; // 2016-04-01T00:00:00
expectedDates[4] = 1462060800; // 2016-05-01T00:00:00
expectedDates[5] = 1464739200; // 2016-06-01T00:00:00
expectedDates[6] = 1467331200; // 2016-07-01T00:00:00
expectedDates[7] = 1470009600; // 2016-08-01T00:00:00
expectedDates[8] = 1472688000; // 2016-09-01T00:00:00
expectedDates[9] = 1475280000; // 2016-10-01T00:00:00
expectedDates[10] = 1477958400; // 2016-11-01T00:00:00
expectedDates[11] = 1480550400; // 2016-12-01T00:00:00
expectedDates[12] = 1483228800; // 2017-01-01T00:00:00
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Monthly_SD_longstub_startBeginningMonth() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.M, S.LONG, true);
uint256 start = 1451606400; // 2016-01-01T00:00:00
uint256 end = 1483228800; // 2017-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
expectedDates[0] = 1451606400; // 2016-01-01T00:00:00
expectedDates[1] = 1454284800; // 2016-02-01T00:00:00
expectedDates[2] = 1456790400; // 2016-03-01T00:00:00
expectedDates[3] = 1459468800; // 2016-04-01T00:00:00
expectedDates[4] = 1462060800; // 2016-05-01T00:00:00
expectedDates[5] = 1464739200; // 2016-06-01T00:00:00
expectedDates[6] = 1467331200; // 2016-07-01T00:00:00
expectedDates[7] = 1470009600; // 2016-08-01T00:00:00
expectedDates[8] = 1472688000; // 2016-09-01T00:00:00
expectedDates[9] = 1475280000; // 2016-10-01T00:00:00
expectedDates[10] = 1477958400; // 2016-11-01T00:00:00
expectedDates[11] = 1480550400; // 2016-12-01T00:00:00
expectedDates[12] = 1483228800; // 2017-01-01T00:00:00
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Monthly_SD_shortstub_startMidMonth() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.M, S.SHORT, true);
uint256 start = 1452816000; // 2016-01-15T00:00:00
uint256 end = 1483228800; // 2017-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
expectedDates[0] = 1452816000; // 2016-01-15T00:00:00
expectedDates[1] = 1455494400; // 2016-02-15T00:00:00
expectedDates[2] = 1458000000; // 2016-03-15T00:00:00
expectedDates[3] = 1460678400; // 2016-04-15T00:00:00
expectedDates[4] = 1463270400; // 2016-05-15T00:00:00
expectedDates[5] = 1465948800; // 2016-06-15T00:00:00
expectedDates[6] = 1468540800; // 2016-07-15T00:00:00
expectedDates[7] = 1471219200; // 2016-08-15T00:00:00
expectedDates[8] = 1473897600; // 2016-09-15T00:00:00
expectedDates[9] = 1476489600; // 2016-10-15T00:00:00
expectedDates[10] = 1479168000; // 2016-11-15T00:00:00
expectedDates[11] = 1481760000; // 2016-12-15T00:00:00
expectedDates[12] = 1483228800; // 2017-01-01T00:00:00
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Monthly_SD_longstub_startMidMonth() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.M, S.LONG, true);
uint256 start = 1452816000; // 2016-01-15T00:00:00
uint256 end = 1483228800; // 2017-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
expectedDates[0] = 1452816000; // 2016-01-15T00:00:00
expectedDates[1] = 1455494400; // 2016-02-15T00:00:00
expectedDates[2] = 1458000000; // 2016-03-15T00:00:00
expectedDates[3] = 1460678400; // 2016-04-15T00:00:00
expectedDates[4] = 1463270400; // 2016-05-15T00:00:00
expectedDates[5] = 1465948800; // 2016-06-15T00:00:00
expectedDates[6] = 1468540800; // 2016-07-15T00:00:00
expectedDates[7] = 1471219200; // 2016-08-15T00:00:00
expectedDates[8] = 1473897600; // 2016-09-15T00:00:00
expectedDates[9] = 1476489600; // 2016-10-15T00:00:00
expectedDates[10] = 1479168000; // 2016-11-15T00:00:00
expectedDates[11] = 1483228800; // 2017-01-01T00:00:00
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_BiMonthly_SD_longstub_startBeginningMonth() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(2, P.M, S.LONG, true);
uint256 start = 1451606400; // 2016-01-01T00:00:00
uint256 end = 1483228800; // 2017-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
expectedDates[0] = 1451606400; // 2016-01-01T00:00:00
expectedDates[1] = 1456790400; // 2016-03-01T00:00:00
expectedDates[2] = 1462060800; // 2016-05-01T00:00:00
expectedDates[3] = 1467331200; // 2016-07-01T00:00:00
expectedDates[4] = 1472688000; // 2016-09-01T00:00:00
expectedDates[5] = 1477958400; // 2016-11-01T00:00:00
expectedDates[6] = 1483228800; // 2017-01-01T00:00:00
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_BiMonthly_SD_longstub_startMidMonth() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(2, P.M, S.LONG, true);
uint256 start = 1452816000; // 2016-01-15T00:00:00
uint256 end = 1483228800; // 2017-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
expectedDates[0] = 1452816000; // 2016-01-15T00:00:00
expectedDates[1] = 1458000000; // 2016-03-15T00:00:00
expectedDates[2] = 1463270400; // 2016-05-15T00:00:00
expectedDates[3] = 1468540800; // 2016-07-15T00:00:00
expectedDates[4] = 1473897600; // 2016-09-15T00:00:00
expectedDates[5] = 1483228800; // 2017-01-01T00:00:00
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Monthly_EOM_shortstub_startMidMonth() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.M, S.SHORT, true);
uint256 start = 1452816000; // 2016-01-15T00:00:00
uint256 end = 1483228800; // 2017-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
expectedDates[0] = 1452816000; // 2016-01-15T00:00:00
expectedDates[1] = 1455494400; // 2016-02-15T00:00:00
expectedDates[2] = 1458000000; // 2016-03-15T00:00:00
expectedDates[3] = 1460678400; // 2016-04-15T00:00:00
expectedDates[4] = 1463270400; // 2016-05-15T00:00:00
expectedDates[5] = 1465948800; // 2016-06-15T00:00:00
expectedDates[6] = 1468540800; // 2016-07-15T00:00:00
expectedDates[7] = 1471219200; // 2016-08-15T00:00:00
expectedDates[8] = 1473897600; // 2016-09-15T00:00:00
expectedDates[9] = 1476489600; // 2016-10-15T00:00:00
expectedDates[10] = 1479168000; // 2016-11-15T00:00:00
expectedDates[11] = 1481760000; // 2016-12-15T00:00:00
expectedDates[12] = 1483228800; // 2017-01-01T00:00:00
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
/*
* End of Month Tests (deactivated)
*
function test_Schedule_Monthly_EOM_shortstub_startEndMonthFeb() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.M, S.SHORT, true);
uint256 start = 1456704000; // 2016-02-29T00:00:00
uint256 end = 1483228800; // 2017-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
expectedDates[0] = 1456704000; // 2016-02-29T00:00:00
expectedDates[1] = 1459382400; // 2016-03-31T00:00:00
expectedDates[2] = 1461974400; // 2016-04-30T00:00:00
expectedDates[3] = 1464652800; // 2016-05-31T00:00:00
expectedDates[4] = 1467244800; // 2016-06-30T00:00:00
expectedDates[5] = 1469923200; // 2016-07-31T00:00:00
expectedDates[6] = 1472601600; // 2016-08-31T00:00:00
expectedDates[7] = 1475193600; // 2016-09-30T00:00:00
expectedDates[8] = 1477872000; // 2016-10-31T00:00:00
expectedDates[9] = 1480464000; // 2016-11-30T00:00:00
expectedDates[10] = 1483142400; // 2016-12-31T00:00:00
expectedDates[11] = 1483228800; // 2017-01-01T00:00:00
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Monthly_EOM_longstub_startEndMonthFeb() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.M, S.LONG, true);
uint256 start = 1456704000; // 2016-02-29T00:00:00
uint256 end = 1483228800; // 2017-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
expectedDates[0] = 1456704000; // 2016-02-29T00:00:00
expectedDates[1] = 1459382400; // 2016-03-31T00:00:00
expectedDates[2] = 1461974400; // 2016-04-30T00:00:00
expectedDates[3] = 1464652800; // 2016-05-31T00:00:00
expectedDates[4] = 1467244800; // 2016-06-30T00:00:00
expectedDates[5] = 1469923200; // 2016-07-31T00:00:00
expectedDates[6] = 1472601600; // 2016-08-31T00:00:00
expectedDates[7] = 1475193600; // 2016-09-30T00:00:00
expectedDates[8] = 1477872000; // 2016-10-31T00:00:00
expectedDates[9] = 1480464000; // 2016-11-30T00:00:00
expectedDates[10] = 1483228800; // 2017-01-01T00:00:00
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Monthly_EOM_longstub_startEndMonthMar() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.M, S.LONG, true);
uint256 start = 1459382400; // 2016-03-31T00:00:00
uint256 end = 1483228800; // 2017-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
expectedDates[0] = 1459382400; // 2016-03-31T00:00:00
expectedDates[1] = 1461974400; // 2016-04-30T00:00:00
expectedDates[2] = 1464652800; // 2016-05-31T00:00:00
expectedDates[3] = 1467244800; // 2016-06-30T00:00:00
expectedDates[4] = 1469923200; // 2016-07-31T00:00:00
expectedDates[5] = 1472601600; // 2016-08-31T00:00:00
expectedDates[6] = 1475193600; // 2016-09-30T00:00:00
expectedDates[7] = 1477872000; // 2016-10-31T00:00:00
expectedDates[8] = 1480464000; // 2016-11-30T00:00:00
expectedDates[9] = 1483228800; // 2017-01-01T00:00:00
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Monthly_EOM_longstub_startEndMonthApr() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.M, S.LONG, true);
uint256 start = 1461974400; // 2016-04-30T00:00:00
uint256 end = 1483228800; // 2017-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
expectedDates[0] = 1461974400; // 2016-04-30T00:00:00
expectedDates[1] = 1464652800; // 2016-05-31T00:00:00
expectedDates[2] = 1467244800; // 2016-06-30T00:00:00
expectedDates[3] = 1469923200; // 2016-07-31T00:00:00
expectedDates[4] = 1472601600; // 2016-08-31T00:00:00
expectedDates[5] = 1475193600; // 2016-09-30T00:00:00
expectedDates[6] = 1477872000; // 2016-10-31T00:00:00
expectedDates[7] = 1480464000; // 2016-11-30T00:00:00
expectedDates[8] = 1483228800; // 2017-01-01T00:00:00
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_BiMonthly_EOM_longstub_startEndMonthFeb() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(2, P.M, S.LONG, true);
uint256 start = 1456704000; // 2016-02-29T00:00:00
uint256 end = 1483228800; // 2017-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
expectedDates[0] = 1456704000; // 2016-02-29T00:00:00
expectedDates[1] = 1461974400; // 2016-04-30T00:00:00
expectedDates[2] = 1467244800; // 2016-06-30T00:00:00
expectedDates[3] = 1472601600; // 2016-08-31T00:00:00
expectedDates[4] = 1477872000; // 2016-10-31T00:00:00
expectedDates[5] = 1483228800; // 2017-01-01T00:00:00
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
} */
function test_Schedule_BiMonthly_SD_shortstub_onlyStartAndEndTimes() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(2, P.M, S.SHORT, true);
uint256 start = 1477958400; // 2016-11-01T00:00:00
uint256 end = 1483228800; // 2017-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
expectedDates[0] = 1477958400; // 2016-11-01T00:00:00
expectedDates[1] = 1483228800; // 2017-01-01T00:00:00
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_BiMonthly_EOM_shortstub_onlyStartAndEndTimes() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(2, P.M, S.SHORT, true);
uint256 start = 1480464000; // 2016-11-30T00:00:00
uint256 end = 1483228800; // 2017-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
expectedDates[0] = 1480464000; // 2016-11-30T00:00:00
expectedDates[1] = 1483228800; // 2017-01-01T00:00:00
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_BiMonthly_EOM_longstub_onlyStartAndEndTimes() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(2, P.M, S.LONG, true);
uint256 start = 1480464000; // 2016-11-30T00:00:00
uint256 end = 1483228800; // 2017-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(start, end, c, true, 0, 9999999999);
expectedDates[0] = 1480464000; // 2016-11-30T00:00:00
expectedDates[1] = 1483228800; // 2017-01-01T00:00:00
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Quarterly_SD_shortstub() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.Q, S.SHORT, true);
uint256 start = 1456704000; // 2016-02-29T00:00:00
uint256 end = 1546300800; // 2019-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(
start, end, c, true, 0, 9999999999);
c = IPS(3, P.M, S.SHORT, true);
expectedDates = computeDatesFromCycleSegment(
start, end, c, true, 0, 9999999999);
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Quarterly_SD_longstub() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.Q, S.LONG, true);
uint256 start = 1456704000; // 2016-02-29T00:00:00
uint256 end = 1546300800; // 2019-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(
start, end, c, true, 0, 9999999999);
c = IPS(3, P.M, S.LONG, true);
expectedDates = computeDatesFromCycleSegment(
start, end, c, true, 0, 9999999999);
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Quarterly_EOM_longstub() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.Q, S.LONG, true);
uint256 start = 1456704000; // 2016-02-29T00:00:00
uint256 end = 1546300800; // 2019-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(
start, end, c, true, 0, 9999999999);
c = IPS(3, P.M, S.LONG, true);
expectedDates = computeDatesFromCycleSegment(
start, end, c, true, 0, 9999999999);
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_BiQuarterly_EOM_longstub() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(2, P.Q, S.LONG, true);
uint256 start = 1456704000; // 2016-02-29T00:00:00
uint256 end = 1640995200; // 2022-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(
start, end, c, true, 0, 9999999999);
c = IPS(6, P.M, S.LONG, true);
expectedDates = computeDatesFromCycleSegment(
start, end, c, true, 0, 9999999999);
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Halfyear_EOM_longstub() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.H, S.LONG, true);
uint256 start = 1456704000; // 2016-02-29T00:00:00
uint256 end = 1640995200; // 2022-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(
start, end, c, true, 0, 9999999999);
c = IPS(2, P.Q, S.LONG, true);
expectedDates = computeDatesFromCycleSegment(
start, end, c, true, 0, 9999999999);
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_Yearly_EOM_longstub() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(1, P.Y, S.LONG, true);
uint256 start = 1456704000; // 2016-02-29T00:00:00
uint256 end = 1640995200; // 2022-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(
start, end, c, true, 0, 9999999999);
c = IPS(2, P.H, S.LONG, true);
expectedDates = computeDatesFromCycleSegment(
start, end, c, true, 0, 9999999999);
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
function test_Schedule_BiYearly_EOM_longstub() public {
uint256[MAX_CYCLE_SIZE] memory expectedDates;
uint256[MAX_CYCLE_SIZE] memory generatedDates;
IPS memory c = IPS(2, P.Y, S.LONG, true);
uint256 start = 1456704000; // 2016-02-29T00:00:00
uint256 end = 1767225600; // 2026-01-01T00:00:00
generatedDates = computeDatesFromCycleSegment(
start, end, c, true, 0, 9999999999);
c = IPS(4, P.H, S.LONG, true);
expectedDates = computeDatesFromCycleSegment(
start, end, c, true, 0, 9999999999);
Assert.equal(
keccak256(abi.encode(expectedDates)),
keccak256(abi.encode(generatedDates)),
"Generated schedules should be equal."
);
}
}
| 2016-04-30T00:00:00
| expectedDates[1] = 1461974400; | 5,516,558 | [
1,
28525,
17,
3028,
17,
5082,
56,
713,
30,
713,
30,
713,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2665,
15578,
63,
21,
65,
273,
5045,
26,
3657,
5608,
16010,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/4/0x12D6fDfE8a01E495095638e4Ff823d379788b204/sources/kaliDAOnft.sol | this is safe from underflow because decrement only occurs if `nCheckpoints` is positive cannot realistically overflow on human timescales | function _writeCheckpoint(
address delegatee,
uint256 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
) internal virtual {
unchecked {
if (nCheckpoints != 0 && checkpoints[delegatee][nCheckpoints - 1].fromTimestamp == block.timestamp) {
checkpoints[delegatee][nCheckpoints - 1].votes = _safeCastTo96(newVotes);
checkpoints[delegatee][nCheckpoints] = Checkpoint(_safeCastTo32(block.timestamp), _safeCastTo96(newVotes));
numCheckpoints[delegatee] = nCheckpoints + 1;
}
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
MINT/BURN LOGIC
| 666,867 | [
1,
2211,
353,
4183,
628,
3613,
2426,
2724,
15267,
1338,
9938,
309,
1375,
82,
1564,
4139,
68,
353,
6895,
2780,
2863,
5846,
1230,
9391,
603,
8672,
1658,
742,
5408,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
389,
2626,
14431,
12,
203,
3639,
1758,
7152,
73,
16,
7010,
3639,
2254,
5034,
290,
1564,
4139,
16,
7010,
3639,
2254,
5034,
1592,
29637,
16,
7010,
3639,
2254,
5034,
394,
29637,
203,
565,
262,
2713,
5024,
288,
203,
3639,
22893,
288,
203,
5411,
309,
261,
82,
1564,
4139,
480,
374,
597,
26402,
63,
22216,
73,
6362,
82,
1564,
4139,
300,
404,
8009,
2080,
4921,
422,
1203,
18,
5508,
13,
288,
203,
7734,
26402,
63,
22216,
73,
6362,
82,
1564,
4139,
300,
404,
8009,
27800,
273,
389,
4626,
9735,
774,
10525,
12,
2704,
29637,
1769,
203,
7734,
26402,
63,
22216,
73,
6362,
82,
1564,
4139,
65,
273,
25569,
24899,
4626,
9735,
774,
1578,
12,
2629,
18,
5508,
3631,
389,
4626,
9735,
774,
10525,
12,
2704,
29637,
10019,
203,
1171,
203,
7734,
818,
1564,
4139,
63,
22216,
73,
65,
273,
290,
1564,
4139,
397,
404,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
3639,
3626,
27687,
29637,
5033,
12,
22216,
73,
16,
1592,
29637,
16,
394,
29637,
1769,
203,
565,
289,
203,
203,
18701,
490,
3217,
19,
38,
8521,
2018,
2871,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/80001/0xe94704DcCc26eFF327A4fd729459408a14953b8A/sources/Contracts/NFTCFrance_OG.sol | Retourne les metadata du NFT id */ | function uri(uint256 id) override public view returns (string memory)
{
require(id >= 1 && id <= maxId, "Nonexistent id");
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
)
)
)
);
return string(abi.encodePacked('data:application/json;base64,', json));
}
| 8,814,813 | [
1,
7055,
6561,
73,
18022,
1982,
9978,
423,
4464,
612,
342,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
2003,
12,
11890,
5034,
612,
13,
3849,
1071,
1476,
1135,
261,
1080,
3778,
13,
203,
565,
288,
203,
3639,
2583,
12,
350,
1545,
404,
597,
612,
1648,
943,
548,
16,
315,
3989,
19041,
612,
8863,
203,
540,
203,
3639,
533,
3778,
1163,
273,
3360,
1105,
18,
3015,
12,
203,
5411,
1731,
12,
203,
7734,
533,
12,
203,
10792,
24126,
18,
3015,
4420,
329,
12,
203,
10792,
262,
203,
7734,
262,
203,
5411,
262,
203,
3639,
11272,
203,
203,
3639,
327,
533,
12,
21457,
18,
3015,
4420,
329,
2668,
892,
30,
3685,
19,
1977,
31,
1969,
1105,
16,
2187,
1163,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
*Submitted for verification at Etherscan.io on 2021-09-11
*/
pragma solidity ^0.5.0;
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
//
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Safe Math Library
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) public pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) public pure returns (uint c) {
require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0);
c = a / b;
}
}
contract BabyDonda is ERC20Interface, SafeMath {
string public name;
string public symbol;
uint8 public decimals; // 18 decimals is the strongly suggested default, avoid changing it
uint256 public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor() public {
name = "BabyDonda";
symbol = "BBDNDA";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
function totalSupply() public view returns (uint) {
return _totalSupply - balances[address(0)];
}
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
function allowance(address tokenOwner, address spender) public view returns (uint remaining) {
return allowed[tokenOwner][spender];
}
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
emit Transfer(from, to, tokens);
return true;
}
} | * Constrctor function Initializes contract with initial supply tokens to the creator of the contract/ | constructor() public {
name = "BabyDonda";
symbol = "BBDNDA";
decimals = 18;
_totalSupply = 100000000000000000000000000;
balances[msg.sender] = _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
| 15,189,944 | [
1,
442,
701,
30206,
445,
10188,
3128,
6835,
598,
2172,
14467,
2430,
358,
326,
11784,
434,
326,
6835,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
1435,
1071,
288,
203,
3639,
508,
273,
315,
38,
24383,
40,
1434,
69,
14432,
203,
3639,
3273,
273,
315,
9676,
40,
2908,
37,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
2130,
12648,
12648,
12648,
31,
203,
203,
3639,
324,
26488,
63,
3576,
18,
15330,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
1234,
18,
15330,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.5.1;
// v1.0
import "../../lib/lifecycle/Destructible.sol";
import "../../lib/ownership/Upgradable.sol";
import "../database/DatabaseInterface.sol";
import "./RegistryInterface.sol";
contract Registry is Destructible, RegistryInterface, Upgradable {
event NewProvider(
address indexed provider,
bytes32 indexed title
);
event NewCurve(
address indexed provider,
bytes32 indexed endpoint,
int[] curve,
address indexed broker
);
DatabaseInterface public db;
constructor(address c) Upgradable(c) public {
_updateDependencies();
}
function _updateDependencies() internal {
address databaseAddress = coordinator.getContract("DATABASE");
db = DatabaseInterface(databaseAddress);
}
/// @dev initiates a provider.
/// If no address->Oracle mapping exists, Oracle object is created
/// @param publicKey unique id for provider. used for encyrpted key swap for subscription endpoints
/// @param title name
function initiateProvider(
uint256 publicKey,
bytes32 title
)
public
returns (bool)
{
require(!isProviderInitiated(msg.sender), "Error: Provider is already initiated");
createOracle(msg.sender, publicKey, title);
addOracle(msg.sender);
emit NewProvider(msg.sender, title);
return true;
}
/// @dev initiates an endpoint specific provider curve
/// If oracle[specfifier] is uninitialized, Curve is mapped to endpoint
/// @param endpoint specifier of endpoint. currently "smart_contract" or "socket_subscription"
/// @param curve flattened array of all segments, coefficients across all polynomial terms, [e0,l0,c0,c1,c2,...]
/// @param broker address for endpoint. if non-zero address, only this address will be able to bond/unbond
function initiateProviderCurve(
bytes32 endpoint,
int256[] memory curve,
address broker
)
public
returns (bool)
{
// Provider must be initiated
require(isProviderInitiated(msg.sender), "Error: Provider is not yet initiated");
// Can't reset their curve
require(getCurveUnset(msg.sender, endpoint), "Error: Curve is already set");
// Can't initiate null endpoint
require(endpoint != bytes32(0), "Error: Can't initiate null endpoint");
setCurve(msg.sender, endpoint, curve);
db.pushBytesArray(keccak256(abi.encodePacked('oracles', msg.sender, 'endpoints')), endpoint);
db.setBytes32(keccak256(abi.encodePacked('oracles', msg.sender, endpoint, 'broker')), stringToBytes32(string(abi.encodePacked(broker))));
emit NewCurve(msg.sender, endpoint, curve, broker);
return true;
}
function stringToBytes32(string memory source) public pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
// Sets provider data
function setProviderParameter(bytes32 key, bytes memory value) public {
// Provider must be initiated
require(isProviderInitiated(msg.sender), "Error: Provider is not yet initiated");
if (!isProviderParamInitialized(msg.sender, key)) {
// initialize this provider param
db.setNumber(keccak256(abi.encodePacked('oracles', msg.sender, 'is_param_set', key)), 1);
db.pushBytesArray(keccak256(abi.encodePacked('oracles', msg.sender, 'providerParams')), key);
}
db.setBytes(keccak256(abi.encodePacked('oracles', msg.sender, 'providerParams', key)), value);
}
// Gets provider data
function getProviderParameter(address provider, bytes32 key) public view returns (bytes memory){
// Provider must be initiated
require(isProviderInitiated(provider), "Error: Provider is not yet initiated");
require(isProviderParamInitialized(provider, key), "Error: Provider Parameter is not yet initialized");
return db.getBytes(keccak256(abi.encodePacked('oracles', provider, 'providerParams', key)));
}
// Gets keys of all provider params
function getAllProviderParams(address provider) public view returns (bytes32[] memory){
// Provider must be initiated
require(isProviderInitiated(provider), "Error: Provider is not yet initiated");
return db.getBytesArray(keccak256(abi.encodePacked('oracles', provider, 'providerParams')));
}
// Set endpoint specific parameters for a given endpoint
function setEndpointParams(bytes32 endpoint, bytes32[] memory endpointParams) public {
// Provider must be initiated
require(isProviderInitiated(msg.sender), "Error: Provider is not yet initialized");
// Can't set endpoint params on an unset provider
require(!getCurveUnset(msg.sender, endpoint), "Error: Curve is not yet set");
db.setBytesArray(keccak256(abi.encodePacked('oracles', msg.sender, 'endpointParams', endpoint)), endpointParams);
}
//Set title for registered provider account
function setProviderTitle(bytes32 title) public {
require(isProviderInitiated(msg.sender), "Error: Provider is not initiated");
db.setBytes32(keccak256(abi.encodePacked('oracles', msg.sender, "title")), title);
}
//Clear an endpoint with no bonds
function clearEndpoint(bytes32 endpoint) public {
require(isProviderInitiated(msg.sender), "Error: Provider is not initiated");
uint256 bound = db.getNumber(keccak256(abi.encodePacked('totalBound', msg.sender, endpoint)));
require(bound == 0, "Error: Endpoint must have no bonds");
int256[] memory nullArray = new int256[](0);
bytes32[] memory endpoints = db.getBytesArray(keccak256(abi.encodePacked("oracles", msg.sender, "endpoints")));
for(uint256 i = 0; i < endpoints.length; i++) {
if(endpoints[i] == endpoint) {
db.setBytesArrayIndex(keccak256(abi.encodePacked("oracles", msg.sender, "endpoints")), i, bytes32(0));
break;
}
}
db.pushBytesArray(keccak256(abi.encodePacked('oracles', msg.sender, 'endpoints')), bytes32(0));
db.setBytes32(keccak256(abi.encodePacked('oracles', msg.sender, endpoint, 'broker')), bytes32(0));
db.setIntArray(keccak256(abi.encodePacked('oracles', msg.sender, 'curves', endpoint)), nullArray);
}
/// @return public key
function getProviderPublicKey(address provider) public view returns (uint256) {
return getPublicKey(provider);
}
/// @return oracle name
function getProviderTitle(address provider) public view returns (bytes32) {
return getTitle(provider);
}
/// @dev get curve paramaters from oracle
function getProviderCurve(
address provider,
bytes32 endpoint
)
public
view
returns (int[] memory)
{
require(!getCurveUnset(provider, endpoint), "Error: Curve is not yet set");
return db.getIntArray(keccak256(abi.encodePacked('oracles', provider, 'curves', endpoint)));
}
function getProviderCurveLength(address provider, bytes32 endpoint) public view returns (uint256){
require(!getCurveUnset(provider, endpoint), "Error: Curve is not yet set");
return db.getIntArray(keccak256(abi.encodePacked('oracles', provider, 'curves', endpoint))).length;
}
/// @dev is provider initiated
/// @param oracleAddress the provider address
/// @return Whether or not the provider has initiated in the Registry.
function isProviderInitiated(address oracleAddress) public view returns (bool) {
return getProviderTitle(oracleAddress) != 0;
}
/*** STORAGE FUNCTIONS ***/
/// @dev get public key of provider
function getPublicKey(address provider) public view returns (uint256) {
return db.getNumber(keccak256(abi.encodePacked("oracles", provider, "publicKey")));
}
/// @dev get title of provider
function getTitle(address provider) public view returns (bytes32) {
return db.getBytes32(keccak256(abi.encodePacked("oracles", provider, "title")));
}
/// @dev get the endpoints of a provider
function getProviderEndpoints(address provider) public view returns (bytes32[] memory) {
return db.getBytesArray(keccak256(abi.encodePacked("oracles", provider, "endpoints")));
}
/// @dev get all endpoint params
function getEndpointParams(address provider, bytes32 endpoint) public view returns (bytes32[] memory) {
return db.getBytesArray(keccak256(abi.encodePacked('oracles', provider, 'endpointParams', endpoint)));
}
/// @dev get broker address for endpoint
function getEndpointBroker(address oracleAddress, bytes32 endpoint) public view returns (address) {
return address(uint160(uint256(db.getBytes32(keccak256(abi.encodePacked('oracles', oracleAddress, endpoint, 'broker'))))));
}
function getCurveUnset(address provider, bytes32 endpoint) public view returns (bool) {
return db.getIntArrayLength(keccak256(abi.encodePacked('oracles', provider, 'curves', endpoint))) == 0;
}
/// @dev get provider address by index
function getOracleAddress(uint256 index) public view returns (address) {
return db.getAddressArrayIndex(keccak256(abi.encodePacked('oracleIndex')), index);
}
/// @dev get all oracle addresses
function getAllOracles() external view returns (address[] memory) {
return db.getAddressArray(keccak256(abi.encodePacked('oracleIndex')));
}
/// @dev add new provider to mapping
function createOracle(address provider, uint256 publicKey, bytes32 title) private {
db.setNumber(keccak256(abi.encodePacked('oracles', provider, "publicKey")), uint256(publicKey));
db.setBytes32(keccak256(abi.encodePacked('oracles', provider, "title")), title);
}
/// @dev add new provider address to oracles array
function addOracle(address provider) private {
db.pushAddressArray(keccak256(abi.encodePacked('oracleIndex')), provider);
}
/// @dev initialize new curve for provider
/// @param provider address of provider
/// @param endpoint endpoint specifier
/// @param curve flattened array of all segments, coefficients across all polynomial terms, [l0,c0,c1,c2,..., ck, e0, ...]
function setCurve(
address provider,
bytes32 endpoint,
int[] memory curve
)
private
{
uint prevEnd = 1;
uint index = 0;
// Validate the curve
while (index < curve.length) {
// Validate the length of the piece
int len = curve[index];
require(len > 0, "Error: Invalid Curve");
// Validate the end index of the piece
uint endIndex = index + uint(len) + 1;
require(endIndex < curve.length, "Error: Invalid Curve");
// Validate that the end is continuous
int end = curve[endIndex];
require(uint(end) > prevEnd, "Error: Invalid Curve");
prevEnd = uint(end);
index += uint(len) + 2;
}
db.setIntArray(keccak256(abi.encodePacked('oracles', provider, 'curves', endpoint)), curve);
}
// Determines whether this parameter has been initialized
function isProviderParamInitialized(address provider, bytes32 key) private view returns (bool){
uint256 val = db.getNumber(keccak256(abi.encodePacked('oracles', provider, 'is_param_set', key)));
return (val == 1) ? true : false;
}
/*************************************** STORAGE ****************************************
* 'oracles', provider, 'endpoints' => {bytes32[]} array of endpoints for this oracle
* 'oracles', provider, 'endpointParams', endpoint => {bytes32[]} array of params for this endpoint
* 'oracles', provider, 'curves', endpoint => {uint[]} curve array for this endpoint
* 'oracles', provider, 'broker', endpoint => {bytes32} broker address for this endpoint
* 'oracles', provider, 'is_param_set', key => {uint} Is this provider parameter set (0/1)
* 'oracles', provider, "publicKey" => {uint} public key for this oracle
* 'oracles', provider, "title" => {bytes32} title of this oracle
****************************************************************************************/
}
| @dev is provider initiated @param oracleAddress the provider address @return Whether or not the provider has initiated in the Registry. | function isProviderInitiated(address oracleAddress) public view returns (bool) {
return getProviderTitle(oracleAddress) != 0;
}
| 1,017,016 | [
1,
291,
2893,
27183,
225,
20865,
1887,
326,
2893,
1758,
327,
17403,
578,
486,
326,
2893,
711,
27183,
316,
326,
5438,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
353,
2249,
2570,
10206,
12,
2867,
20865,
1887,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
16137,
4247,
12,
280,
16066,
1887,
13,
480,
374,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
/**
* Copyright 2017-2020, bZeroX, LLC <https://bzx.network/>. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library MathUtil {
/**
* @dev Integer division of two numbers, rounding up and truncating the quotient
*/
function divCeil(uint256 a, uint256 b) internal pure returns (uint256) {
return divCeil(a, b, "SafeMath: division by zero");
}
/**
* @dev Integer division of two numbers, rounding up and truncating the quotient
*/
function divCeil(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b != 0, errorMessage);
if (a == 0) {
return 0;
}
uint256 c = ((a - 1) / b) + 1;
return c;
}
function min256(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a < _b ? _a : _b;
}
}
interface IPriceFeeds {
function queryRate(
address sourceToken,
address destToken)
external
view
returns (uint256 rate, uint256 precision);
function queryPrecision(
address sourceToken,
address destToken)
external
view
returns (uint256 precision);
function queryReturn(
address sourceToken,
address destToken,
uint256 sourceAmount)
external
view
returns (uint256 destAmount);
function checkPriceDisagreement(
address sourceToken,
address destToken,
uint256 sourceAmount,
uint256 destAmount,
uint256 maxSlippage)
external
view
returns (uint256 sourceToDestSwapRate);
function amountInEth(
address Token,
uint256 amount)
external
view
returns (uint256 ethAmount);
function getMaxDrawdown(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount,
uint256 maintenanceMargin)
external
view
returns (uint256);
function getCurrentMarginAndCollateralSize(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount)
external
view
returns (uint256 currentMargin, uint256 collateralInEthAmount);
function getCurrentMargin(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount)
external
view
returns (uint256 currentMargin, uint256 collateralToLoanRate);
function shouldLiquidate(
address loanToken,
address collateralToken,
uint256 loanAmount,
uint256 collateralAmount,
uint256 maintenanceMargin)
external
view
returns (bool);
function getFastGasPrice(
address payToken)
external
view
returns (uint256);
}
contract IVestingToken is IERC20 {
function claim()
external;
function vestedBalanceOf(
address _owner)
external
view
returns (uint256);
function claimedBalanceOf(
address _owner)
external
view
returns (uint256);
}
/**
* @dev Library for managing loan sets
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* Include with `using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;`.
*
*/
library EnumerableBytes32Set {
struct Bytes32Set {
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) index;
bytes32[] values;
}
/**
* @dev Add an address value to a set. O(1).
* Returns false if the value was already in the set.
*/
function addAddress(Bytes32Set storage set, address addrvalue)
internal
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return addBytes32(set, value);
}
/**
* @dev Add a value to a set. O(1).
* Returns false if the value was already in the set.
*/
function addBytes32(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
if (!contains(set, value)){
set.index[value] = set.values.push(value);
return true;
} else {
return false;
}
}
/**
* @dev Removes an address value from a set. O(1).
* Returns false if the value was not present in the set.
*/
function removeAddress(Bytes32Set storage set, address addrvalue)
internal
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return removeBytes32(set, value);
}
/**
* @dev Removes a value from a set. O(1).
* Returns false if the value was not present in the set.
*/
function removeBytes32(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
if (contains(set, value)){
uint256 toDeleteIndex = set.index[value] - 1;
uint256 lastIndex = set.values.length - 1;
// If the element we're deleting is the last one, we can just remove it without doing a swap
if (lastIndex != toDeleteIndex) {
bytes32 lastValue = set.values[lastIndex];
// Move the last value to the index where the deleted value is
set.values[toDeleteIndex] = lastValue;
// Update the index for the moved value
set.index[lastValue] = toDeleteIndex + 1; // All indexes are 1-based
}
// Delete the index entry for the deleted value
delete set.index[value];
// Delete the old entry for the moved value
set.values.pop();
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return set.index[value] != 0;
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function containsAddress(Bytes32Set storage set, address addrvalue)
internal
view
returns (bool)
{
bytes32 value;
assembly {
value := addrvalue
}
return set.index[value] != 0;
}
/**
* @dev Returns an array with all values in the set. O(N).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
* WARNING: This function may run out of gas on large sets: use {length} and
* {get} instead in these cases.
*/
function enumerate(Bytes32Set storage set, uint256 start, uint256 count)
internal
view
returns (bytes32[] memory output)
{
uint256 end = start + count;
require(end >= start, "addition overflow");
end = set.values.length < end ? set.values.length : end;
if (end == 0 || start >= end) {
return output;
}
output = new bytes32[](end-start);
for (uint256 i = start; i < end; i++) {
output[i-start] = set.values[i];
}
return output;
}
/**
* @dev Returns the number of elements on the set. O(1).
*/
function length(Bytes32Set storage set)
internal
view
returns (uint256)
{
return set.values.length;
}
/** @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function get(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return set.values[index];
}
/** @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function getAddress(Bytes32Set storage set, uint256 index)
internal
view
returns (address)
{
bytes32 value = set.values[index];
address addrvalue;
assembly {
addrvalue := value
}
return addrvalue;
}
}
interface IUniswapV2Router {
// 0x38ed1739
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline)
external
returns (uint256[] memory amounts);
// 0x8803dbee
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline)
external
returns (uint256[] memory amounts);
// 0x1f00ca74
function getAmountsIn(
uint256 amountOut,
address[] calldata path)
external
view
returns (uint256[] memory amounts);
// 0xd06ca61f
function getAmountsOut(
uint256 amountIn,
address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
interface ICurve3Pool {
function add_liquidity(
uint256[3] calldata amounts,
uint256 min_mint_amount)
external;
function get_virtual_price()
external
view
returns (uint256);
}
/// @title A proxy interface for The Protocol
/// @author bZeroX
/// @notice This is just an interface, not to be deployed itself.
/// @dev This interface is to be used for the protocol interactions.
interface IBZx {
////// Protocol //////
/// @dev adds or replaces existing proxy module
/// @param target target proxy module address
function replaceContract(address target) external;
/// @dev updates all proxy modules addreses and function signatures.
/// sigsArr and targetsArr should be of equal length
/// @param sigsArr array of function signatures
/// @param targetsArr array of target proxy module addresses
function setTargets(
string[] calldata sigsArr,
address[] calldata targetsArr
) external;
/// @dev returns protocol module address given a function signature
/// @return module address
function getTarget(string calldata sig) external view returns (address);
////// Protocol Settings //////
/// @dev sets price feed contract address. The contract on the addres should implement IPriceFeeds interface
/// @param newContract module address for the IPriceFeeds implementation
function setPriceFeedContract(address newContract) external;
/// @dev sets swaps contract address. The contract on the addres should implement ISwapsImpl interface
/// @param newContract module address for the ISwapsImpl implementation
function setSwapsImplContract(address newContract) external;
/// @dev sets loan pool with assets. Accepts two arrays of equal length
/// @param pools array of address of pools
/// @param assets array of addresses of assets
function setLoanPool(address[] calldata pools, address[] calldata assets)
external;
/// @dev updates list of supported tokens, it can be use also to disable or enable particualr token
/// @param addrs array of address of pools
/// @param toggles array of addresses of assets
/// @param withApprovals resets tokens to unlimited approval with the swaps integration (kyber, etc.)
function setSupportedTokens(
address[] calldata addrs,
bool[] calldata toggles,
bool withApprovals
) external;
/// @dev sets lending fee with WEI_PERCENT_PRECISION
/// @param newValue lending fee percent
function setLendingFeePercent(uint256 newValue) external;
/// @dev sets trading fee with WEI_PERCENT_PRECISION
/// @param newValue trading fee percent
function setTradingFeePercent(uint256 newValue) external;
/// @dev sets borrowing fee with WEI_PERCENT_PRECISION
/// @param newValue borrowing fee percent
function setBorrowingFeePercent(uint256 newValue) external;
/// @dev sets affiliate fee with WEI_PERCENT_PRECISION
/// @param newValue affiliate fee percent
function setAffiliateFeePercent(uint256 newValue) external;
/// @dev sets liquidation inncetive percent per loan per token. This is the profit percent
/// that liquidator gets in the process of liquidating.
/// @param loanTokens array list of loan tokens
/// @param collateralTokens array list of collateral tokens
/// @param amounts array list of liquidation inncetive amount
function setLiquidationIncentivePercent(
address[] calldata loanTokens,
address[] calldata collateralTokens,
uint256[] calldata amounts
) external;
/// @dev sets max swap rate slippage percent.
/// @param newAmount max swap rate slippage percent.
function setMaxDisagreement(uint256 newAmount) external;
/// TODO
function setSourceBufferPercent(uint256 newAmount) external;
/// @dev sets maximum supported swap size in ETH
/// @param newAmount max swap size in ETH.
function setMaxSwapSize(uint256 newAmount) external;
/// @dev sets fee controller address
/// @param newController address of the new fees controller
function setFeesController(address newController) external;
/// @dev withdraws lending fees to receiver. Only can be called by feesController address
/// @param tokens array of token addresses.
/// @param receiver fees receiver address
/// @return amounts array of amounts withdrawn
function withdrawFees(
address[] calldata tokens,
address receiver,
FeeClaimType feeType
) external returns (uint256[] memory amounts);
/// @dev withdraw protocol token (BZRX) from vesting contract vBZRX
/// @param receiver address of BZRX tokens claimed
/// @param amount of BZRX token to be claimed. max is claimed if amount is greater than balance.
/// @return rewardToken reward token address
/// @return withdrawAmount amount
function withdrawProtocolToken(address receiver, uint256 amount)
external
returns (address rewardToken, uint256 withdrawAmount);
/// @dev depozit protocol token (BZRX)
/// @param amount address of BZRX tokens to deposit
function depositProtocolToken(uint256 amount) external;
function grantRewards(address[] calldata users, uint256[] calldata amounts)
external
returns (uint256 totalAmount);
// NOTE: this doesn't sanitize inputs -> inaccurate values may be returned if there are duplicates tokens input
function queryFees(address[] calldata tokens, FeeClaimType feeType)
external
view
returns (uint256[] memory amountsHeld, uint256[] memory amountsPaid);
function priceFeeds() external view returns (address);
function swapsImpl() external view returns (address);
function logicTargets(bytes4) external view returns (address);
function loans(bytes32) external view returns (Loan memory);
function loanParams(bytes32) external view returns (LoanParams memory);
// we don't use this yet
// function lenderOrders(address, bytes32) external returns (Order memory);
// function borrowerOrders(address, bytes32) external returns (Order memory);
function delegatedManagers(bytes32, address) external view returns (bool);
function lenderInterest(address, address)
external
view
returns (LenderInterest memory);
function loanInterest(bytes32) external view returns (LoanInterest memory);
function feesController() external view returns (address);
function lendingFeePercent() external view returns (uint256);
function lendingFeeTokensHeld(address) external view returns (uint256);
function lendingFeeTokensPaid(address) external view returns (uint256);
function borrowingFeePercent() external view returns (uint256);
function borrowingFeeTokensHeld(address) external view returns (uint256);
function borrowingFeeTokensPaid(address) external view returns (uint256);
function protocolTokenHeld() external view returns (uint256);
function protocolTokenPaid() external view returns (uint256);
function affiliateFeePercent() external view returns (uint256);
function liquidationIncentivePercent(address, address)
external
view
returns (uint256);
function loanPoolToUnderlying(address) external view returns (address);
function underlyingToLoanPool(address) external view returns (address);
function supportedTokens(address) external view returns (bool);
function maxDisagreement() external view returns (uint256);
function sourceBufferPercent() external view returns (uint256);
function maxSwapSize() external view returns (uint256);
/// @dev get list of loan pools in the system. Ordering is not guaranteed
/// @param start start index
/// @param count number of pools to return
/// @return loanPoolsList array of loan pools
function getLoanPoolsList(uint256 start, uint256 count)
external
view
returns (address[] memory loanPoolsList);
/// @dev checks whether addreess is a loan pool address
/// @return boolean
function isLoanPool(address loanPool) external view returns (bool);
////// Loan Settings //////
/// @dev creates new loan param settings
/// @param loanParamsList array of LoanParams
/// @return loanParamsIdList array of loan ids created
function setupLoanParams(LoanParams[] calldata loanParamsList)
external
returns (bytes32[] memory loanParamsIdList);
/// @dev Deactivates LoanParams for future loans. Active loans using it are unaffected.
/// @param loanParamsIdList array of loan ids
function disableLoanParams(bytes32[] calldata loanParamsIdList) external;
/// @dev gets array of LoanParams by given ids
/// @param loanParamsIdList array of loan ids
/// @return loanParamsList array of LoanParams
function getLoanParams(bytes32[] calldata loanParamsIdList)
external
view
returns (LoanParams[] memory loanParamsList);
/// @dev Enumerates LoanParams in the system by owner
/// @param owner of the loan params
/// @param start number of loans to return
/// @param count total number of the items
/// @return loanParamsList array of LoanParams
function getLoanParamsList(
address owner,
uint256 start,
uint256 count
) external view returns (bytes32[] memory loanParamsList);
/// @dev returns total loan principal for token address
/// @param lender address
/// @param loanToken address
/// @return total principal of the loan
function getTotalPrincipal(address lender, address loanToken)
external
view
returns (uint256);
////// Loan Openings //////
/// @dev This is THE function that borrows or trades on the protocol
/// @param loanParamsId id of the LoanParam created beforehand by setupLoanParams function
/// @param loanId id of existing loan, if 0, start a new loan
/// @param isTorqueLoan boolean whether it is toreque or non torque loan
/// @param initialMargin in WEI_PERCENT_PRECISION
/// @param sentAddresses array of size 4:
/// lender: must match loan if loanId provided
/// borrower: must match loan if loanId provided
/// receiver: receiver of funds (address(0) assumes borrower address)
/// manager: delegated manager of loan unless address(0)
/// @param sentValues array of size 5:
/// newRate: new loan interest rate
/// newPrincipal: new loan size (borrowAmount + any borrowed interest)
/// torqueInterest: new amount of interest to escrow for Torque loan (determines initial loan length)
/// loanTokenReceived: total loanToken deposit (amount not sent to borrower in the case of Torque loans)
/// collateralTokenReceived: total collateralToken deposit
/// @param loanDataBytes required when sending ether
/// @return principal of the loan and collateral amount
function borrowOrTradeFromPool(
bytes32 loanParamsId,
bytes32 loanId,
bool isTorqueLoan,
uint256 initialMargin,
address[4] calldata sentAddresses,
uint256[5] calldata sentValues,
bytes calldata loanDataBytes
) external payable returns (LoanOpenData memory);
/// @dev sets/disables/enables the delegated manager for the loan
/// @param loanId id of the loan
/// @param delegated delegated manager address
/// @param toggle boolean set enabled or disabled
function setDelegatedManager(
bytes32 loanId,
address delegated,
bool toggle
) external;
/// @dev estimates margin exposure for simulated position
/// @param loanToken address of the loan token
/// @param collateralToken address of collateral token
/// @param loanTokenSent amout of loan token sent
/// @param collateralTokenSent amount of collateral token sent
/// @param interestRate yearly interest rate
/// @param newPrincipal principal amount of the loan
/// @return estimated margin exposure amount
function getEstimatedMarginExposure(
address loanToken,
address collateralToken,
uint256 loanTokenSent,
uint256 collateralTokenSent,
uint256 interestRate,
uint256 newPrincipal
) external view returns (uint256);
/// @dev calculates required collateral for simulated position
/// @param loanToken address of loan token
/// @param collateralToken address of collateral token
/// @param newPrincipal principal amount of the loan
/// @param marginAmount margin amount of the loan
/// @param isTorqueLoan boolean torque or non torque loan
/// @return collateralAmountRequired amount required
function getRequiredCollateral(
address loanToken,
address collateralToken,
uint256 newPrincipal,
uint256 marginAmount,
bool isTorqueLoan
) external view returns (uint256 collateralAmountRequired);
function getRequiredCollateralByParams(
bytes32 loanParamsId,
uint256 newPrincipal
) external view returns (uint256 collateralAmountRequired);
/// @dev calculates borrow amount for simulated position
/// @param loanToken address of loan token
/// @param collateralToken address of collateral token
/// @param collateralTokenAmount amount of collateral token sent
/// @param marginAmount margin amount
/// @param isTorqueLoan boolean torque or non torque loan
/// @return borrowAmount possible borrow amount
function getBorrowAmount(
address loanToken,
address collateralToken,
uint256 collateralTokenAmount,
uint256 marginAmount,
bool isTorqueLoan
) external view returns (uint256 borrowAmount);
function getBorrowAmountByParams(
bytes32 loanParamsId,
uint256 collateralTokenAmount
) external view returns (uint256 borrowAmount);
////// Loan Closings //////
/// @dev liquidates unhealty loans
/// @param loanId id of the loan
/// @param receiver address receiving liquidated loan collateral
/// @param closeAmount amount to close denominated in loanToken
/// @return loanCloseAmount amount of the collateral token of the loan
/// @return seizedAmount sezied amount in the collateral token
/// @return seizedToken loan token address
function liquidate(
bytes32 loanId,
address receiver,
uint256 closeAmount
)
external
payable
returns (
uint256 loanCloseAmount,
uint256 seizedAmount,
address seizedToken
);
/// @dev rollover loan
/// @param loanId id of the loan
/// @param loanDataBytes reserved for future use.
function rollover(bytes32 loanId, bytes calldata loanDataBytes)
external
returns (address rebateToken, uint256 gasRebate);
/// @dev close position with loan token deposit
/// @param loanId id of the loan
/// @param receiver collateral token reciever address
/// @param depositAmount amount of loan token to deposit
/// @return loanCloseAmount loan close amount
/// @return withdrawAmount loan token withdraw amount
/// @return withdrawToken loan token address
function closeWithDeposit(
bytes32 loanId,
address receiver,
uint256 depositAmount // denominated in loanToken
)
external
payable
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
);
/// @dev close position with swap
/// @param loanId id of the loan
/// @param receiver collateral token reciever address
/// @param swapAmount amount of loan token to swap
/// @param returnTokenIsCollateral boolean whether to return tokens is collateral
/// @param loanDataBytes reserved for future use
/// @return loanCloseAmount loan close amount
/// @return withdrawAmount loan token withdraw amount
/// @return withdrawToken loan token address
function closeWithSwap(
bytes32 loanId,
address receiver,
uint256 swapAmount, // denominated in collateralToken
bool returnTokenIsCollateral, // true: withdraws collateralToken, false: withdraws loanToken
bytes calldata loanDataBytes
)
external
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
);
////// Loan Closings With Gas Token //////
/// @dev liquidates unhealty loans by using Gas token
/// @param loanId id of the loan
/// @param receiver address receiving liquidated loan collateral
/// @param gasTokenUser user address of the GAS token
/// @param closeAmount amount to close denominated in loanToken
/// @return loanCloseAmount loan close amount
/// @return seizedAmount loan token withdraw amount
/// @return seizedToken loan token address
function liquidateWithGasToken(
bytes32 loanId,
address receiver,
address gasTokenUser,
uint256 closeAmount // denominated in loanToken
)
external
payable
returns (
uint256 loanCloseAmount,
uint256 seizedAmount,
address seizedToken
);
/// @dev rollover loan
/// @param loanId id of the loan
/// @param gasTokenUser user address of the GAS token
function rolloverWithGasToken(
bytes32 loanId,
address gasTokenUser,
bytes calldata /*loanDataBytes*/
) external returns (address rebateToken, uint256 gasRebate);
/// @dev close position with loan token deposit
/// @param loanId id of the loan
/// @param receiver collateral token reciever address
/// @param gasTokenUser user address of the GAS token
/// @param depositAmount amount of loan token to deposit denominated in loanToken
/// @return loanCloseAmount loan close amount
/// @return withdrawAmount loan token withdraw amount
/// @return withdrawToken loan token address
function closeWithDepositWithGasToken(
bytes32 loanId,
address receiver,
address gasTokenUser,
uint256 depositAmount
)
external
payable
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
);
/// @dev close position with swap
/// @param loanId id of the loan
/// @param receiver collateral token reciever address
/// @param gasTokenUser user address of the GAS token
/// @param swapAmount amount of loan token to swap denominated in collateralToken
/// @param returnTokenIsCollateral true: withdraws collateralToken, false: withdraws loanToken
/// @return loanCloseAmount loan close amount
/// @return withdrawAmount loan token withdraw amount
/// @return withdrawToken loan token address
function closeWithSwapWithGasToken(
bytes32 loanId,
address receiver,
address gasTokenUser,
uint256 swapAmount,
bool returnTokenIsCollateral,
bytes calldata loanDataBytes
)
external
returns (
uint256 loanCloseAmount,
uint256 withdrawAmount,
address withdrawToken
);
////// Loan Maintenance //////
/// @dev deposit collateral to existing loan
/// @param loanId existing loan id
/// @param depositAmount amount to deposit which must match msg.value if ether is sent
function depositCollateral(bytes32 loanId, uint256 depositAmount)
external
payable;
/// @dev withdraw collateral from existing loan
/// @param loanId existing lona id
/// @param receiver address of withdrawn tokens
/// @param withdrawAmount amount to withdraw
/// @return actualWithdrawAmount actual amount withdrawn
function withdrawCollateral(
bytes32 loanId,
address receiver,
uint256 withdrawAmount
) external returns (uint256 actualWithdrawAmount);
/// @dev withdraw accrued interest rate for a loan given token address
/// @param loanToken loan token address
function withdrawAccruedInterest(address loanToken) external;
/// @dev extends loan duration by depositing more collateral
/// @param loanId id of the existing loan
/// @param depositAmount amount to deposit
/// @param useCollateral boolean whether to extend using collateral or deposit amount
/// @return secondsExtended by that number of seconds loan duration was extended
function extendLoanDuration(
bytes32 loanId,
uint256 depositAmount,
bool useCollateral,
bytes calldata // for future use /*loanDataBytes*/
) external payable returns (uint256 secondsExtended);
/// @dev reduces loan duration by withdrawing collateral
/// @param loanId id of the existing loan
/// @param receiver address to receive tokens
/// @param withdrawAmount amount to withdraw
/// @return secondsReduced by that number of seconds loan duration was extended
function reduceLoanDuration(
bytes32 loanId,
address receiver,
uint256 withdrawAmount
) external returns (uint256 secondsReduced);
function setDepositAmount(
bytes32 loanId,
uint256 depositValueAsLoanToken,
uint256 depositValueAsCollateralToken
) external;
function claimRewards(address receiver)
external
returns (uint256 claimAmount);
function transferLoan(bytes32 loanId, address newOwner) external;
function rewardsBalanceOf(address user)
external
view
returns (uint256 rewardsBalance);
/// @dev Gets current lender interest data totals for all loans with a specific oracle and interest token
/// @param lender The lender address
/// @param loanToken The loan token address
/// @return interestPaid The total amount of interest that has been paid to a lender so far
/// @return interestPaidDate The date of the last interest pay out, or 0 if no interest has been withdrawn yet
/// @return interestOwedPerDay The amount of interest the lender is earning per day
/// @return interestUnPaid The total amount of interest the lender is owned and not yet withdrawn
/// @return interestFeePercent The fee retained by the protocol before interest is paid to the lender
/// @return principalTotal The total amount of outstading principal the lender has loaned
function getLenderInterestData(address lender, address loanToken)
external
view
returns (
uint256 interestPaid,
uint256 interestPaidDate,
uint256 interestOwedPerDay,
uint256 interestUnPaid,
uint256 interestFeePercent,
uint256 principalTotal
);
/// @dev Gets current interest data for a loan
/// @param loanId A unique id representing the loan
/// @return loanToken The loan token that interest is paid in
/// @return interestOwedPerDay The amount of interest the borrower is paying per day
/// @return interestDepositTotal The total amount of interest the borrower has deposited
/// @return interestDepositRemaining The amount of deposited interest that is not yet owed to a lender
function getLoanInterestData(bytes32 loanId)
external
view
returns (
address loanToken,
uint256 interestOwedPerDay,
uint256 interestDepositTotal,
uint256 interestDepositRemaining
);
/// @dev gets list of loans of particular user address
/// @param user address of the loans
/// @param start of the index
/// @param count number of loans to return
/// @param loanType type of the loan: All(0), Margin(1), NonMargin(2)
/// @param isLender whether to list lender loans or borrower loans
/// @param unsafeOnly booleat if true return only unsafe loans that are open for liquidation
/// @return loansData LoanReturnData array of loans
function getUserLoans(
address user,
uint256 start,
uint256 count,
LoanType loanType,
bool isLender,
bool unsafeOnly
) external view returns (LoanReturnData[] memory loansData);
function getUserLoansCount(address user, bool isLender)
external
view
returns (uint256);
/// @dev gets existing loan
/// @param loanId id of existing loan
/// @return loanData array of loans
function getLoan(bytes32 loanId)
external
view
returns (LoanReturnData memory loanData);
/// @dev get current active loans in the system
/// @param start of the index
/// @param count number of loans to return
/// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation)
function getActiveLoans(
uint256 start,
uint256 count,
bool unsafeOnly
) external view returns (LoanReturnData[] memory loansData);
/// @dev get current active loans in the system
/// @param start of the index
/// @param count number of loans to return
/// @param unsafeOnly boolean if true return unsafe loan only (open for liquidation)
/// @param isLiquidatable boolean if true return liquidatable loans only
function getActiveLoansAdvanced(
uint256 start,
uint256 count,
bool unsafeOnly,
bool isLiquidatable
) external view returns (LoanReturnData[] memory loansData);
function getActiveLoansCount() external view returns (uint256);
////// Swap External //////
/// @dev swap thru external integration
/// @param sourceToken source token address
/// @param destToken destintaion token address
/// @param receiver address to receive tokens
/// @param returnToSender TODO
/// @param sourceTokenAmount source token amount
/// @param requiredDestTokenAmount destination token amount
/// @param swapData TODO
/// @return destTokenAmountReceived destination token received
/// @return sourceTokenAmountUsed source token amount used
function swapExternal(
address sourceToken,
address destToken,
address receiver,
address returnToSender,
uint256 sourceTokenAmount,
uint256 requiredDestTokenAmount,
bytes calldata swapData
)
external
payable
returns (
uint256 destTokenAmountReceived,
uint256 sourceTokenAmountUsed
);
/// @dev swap thru external integration using GAS
/// @param sourceToken source token address
/// @param destToken destintaion token address
/// @param receiver address to receive tokens
/// @param returnToSender TODO
/// @param gasTokenUser user address of the GAS token
/// @param sourceTokenAmount source token amount
/// @param requiredDestTokenAmount destination token amount
/// @param swapData TODO
/// @return destTokenAmountReceived destination token received
/// @return sourceTokenAmountUsed source token amount used
function swapExternalWithGasToken(
address sourceToken,
address destToken,
address receiver,
address returnToSender,
address gasTokenUser,
uint256 sourceTokenAmount,
uint256 requiredDestTokenAmount,
bytes calldata swapData
)
external
payable
returns (
uint256 destTokenAmountReceived,
uint256 sourceTokenAmountUsed
);
/// @dev calculate simulated return of swap
/// @param sourceToken source token address
/// @param destToken destination token address
/// @param sourceTokenAmount source token amount
/// @return amoun denominated in destination token
function getSwapExpectedReturn(
address sourceToken,
address destToken,
uint256 sourceTokenAmount
) external view returns (uint256);
function owner() external view returns (address);
function transferOwnership(address newOwner) external;
struct LoanParams {
bytes32 id;
bool active;
address owner;
address loanToken;
address collateralToken;
uint256 minInitialMargin;
uint256 maintenanceMargin;
uint256 maxLoanTerm;
}
struct LoanOpenData {
bytes32 loanId;
uint256 principal;
uint256 collateral;
}
enum LoanType {
All,
Margin,
NonMargin
}
struct LoanReturnData {
bytes32 loanId;
uint96 endTimestamp;
address loanToken;
address collateralToken;
uint256 principal;
uint256 collateral;
uint256 interestOwedPerDay;
uint256 interestDepositRemaining;
uint256 startRate;
uint256 startMargin;
uint256 maintenanceMargin;
uint256 currentMargin;
uint256 maxLoanTerm;
uint256 maxLiquidatable;
uint256 maxSeizable;
uint256 depositValueAsLoanToken;
uint256 depositValueAsCollateralToken;
}
enum FeeClaimType {
All,
Lending,
Trading,
Borrowing
}
struct Loan {
bytes32 id; // id of the loan
bytes32 loanParamsId; // the linked loan params id
bytes32 pendingTradesId; // the linked pending trades id
uint256 principal; // total borrowed amount outstanding
uint256 collateral; // total collateral escrowed for the loan
uint256 startTimestamp; // loan start time
uint256 endTimestamp; // for active loans, this is the expected loan end time, for in-active loans, is the actual (past) end time
uint256 startMargin; // initial margin when the loan opened
uint256 startRate; // reference rate when the loan opened for converting collateralToken to loanToken
address borrower; // borrower of this loan
address lender; // lender of this loan
bool active; // if false, the loan has been fully closed
}
struct LenderInterest {
uint256 principalTotal; // total borrowed amount outstanding of asset
uint256 owedPerDay; // interest owed per day for all loans of asset
uint256 owedTotal; // total interest owed for all loans of asset (assuming they go to full term)
uint256 paidTotal; // total interest paid so far for asset
uint256 updatedTimestamp; // last update
}
struct LoanInterest {
uint256 owedPerDay; // interest owed per day for loan
uint256 depositTotal; // total escrowed interest for loan
uint256 updatedTimestamp; // last update
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
contract StakingConstants {
address public constant BZRX = 0x56d811088235F11C8920698a204A5010a788f4b3;
address public constant vBZRX = 0xB72B31907C1C95F3650b64b2469e08EdACeE5e8F;
address public constant iBZRX = 0x18240BD9C07fA6156Ce3F3f61921cC82b2619157;
address public constant LPToken = 0xa30911e072A0C88D55B5D0A0984B66b0D04569d0; // sushiswap
address public constant LPTokenOld = 0xe26A220a341EAca116bDa64cF9D5638A935ae629; // balancer
IERC20 public constant curve3Crv = IERC20(0x6c3F90f043a72FA612cbac8115EE7e52BDe6E490);
address public constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
IUniswapV2Router public constant uniswapRouter = IUniswapV2Router(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); // sushiswap
ICurve3Pool public constant curve3pool = ICurve3Pool(0xbEbc44782C7dB0a1A60Cb6fe97d0b483032FF1C7);
IBZx public constant bZx = IBZx(0xD8Ee69652E4e4838f2531732a46d1f7F584F0b7f);
uint256 public constant cliffDuration = 15768000; // 86400 * 365 * 0.5
uint256 public constant vestingDuration = 126144000; // 86400 * 365 * 4
uint256 internal constant vestingDurationAfterCliff = 110376000; // 86400 * 365 * 3.5
uint256 internal constant vestingStartTimestamp = 1594648800; // start_time
uint256 internal constant vestingCliffTimestamp = vestingStartTimestamp + cliffDuration;
uint256 internal constant vestingEndTimestamp = vestingStartTimestamp + vestingDuration;
uint256 internal constant _startingVBZRXBalance = 889389933e18; // 889,389,933 BZRX
uint256 public constant BZRXWeightStored = 1e18;
struct DelegatedTokens {
address user;
uint256 BZRX;
uint256 vBZRX;
uint256 iBZRX;
uint256 LPToken;
uint256 totalVotes;
}
event Stake(
address indexed user,
address indexed token,
address indexed delegate,
uint256 amount
);
event Unstake(
address indexed user,
address indexed token,
address indexed delegate,
uint256 amount
);
event AddRewards(
address indexed sender,
uint256 bzrxAmount,
uint256 stableCoinAmount
);
event Claim(
address indexed user,
uint256 bzrxAmount,
uint256 stableCoinAmount
);
event ChangeDelegate(
address indexed user,
address indexed oldDelegate,
address indexed newDelegate
);
event WithdrawFees(
address indexed sender
);
event ConvertFees(
address indexed sender,
uint256 bzrxOutput,
uint256 stableCoinOutput
);
event DistributeFees(
address indexed sender,
uint256 bzrxRewards,
uint256 stableCoinRewards
);
}
contract StakingUpgradeable is Ownable {
address public implementation;
}
contract StakingState is StakingUpgradeable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using EnumerableBytes32Set for EnumerableBytes32Set.Bytes32Set;
uint256 public constant initialCirculatingSupply = 1030000000e18 - 889389933e18;
address internal constant ZERO_ADDRESS = address(0);
bool public isPaused;
address public fundsWallet;
mapping(address => uint256) internal _totalSupplyPerToken; // token => value
mapping(address => mapping(address => uint256)) internal _balancesPerToken; // token => account => value
mapping(address => address) public delegate; // user => delegate
mapping(address => mapping(address => uint256)) public delegatedPerToken; // token => user => value
uint256 public bzrxPerTokenStored;
mapping(address => uint256) public bzrxRewardsPerTokenPaid; // user => value
mapping(address => uint256) public bzrxRewards; // user => value
mapping(address => uint256) public bzrxVesting; // user => value
uint256 public stableCoinPerTokenStored;
mapping(address => uint256) public stableCoinRewardsPerTokenPaid; // user => value
mapping(address => uint256) public stableCoinRewards; // user => value
mapping(address => uint256) public stableCoinVesting; // user => value
uint256 public vBZRXWeightStored;
uint256 public iBZRXWeightStored;
uint256 public LPTokenWeightStored;
EnumerableBytes32Set.Bytes32Set internal _delegatedSet;
uint256 public lastRewardsAddTime;
mapping(address => uint256) public vestingLastSync;
mapping(address => address[]) public swapPaths;
mapping(address => uint256) public stakingRewards;
uint256 public rewardPercent = 50e18;
uint256 public maxUniswapDisagreement = 3e18;
uint256 public maxCurveDisagreement = 3e18;
uint256 public callerRewardDivisor = 100;
address[] public currentFeeTokens;
struct ProposalState {
uint256 proposalTime;
uint256 iBZRXWeight;
uint256 lpBZRXBalance;
uint256 lpTotalSupply;
}
address public governor;
mapping(uint256 => ProposalState) internal _proposalState;
}
contract StakingV1_1 is StakingState, StakingConstants {
using MathUtil for uint256;
modifier onlyEOA() {
require(msg.sender == tx.origin, "unauthorized");
_;
}
modifier checkPause() {
require(!isPaused, "paused");
_;
}
function stake(
address[] calldata tokens,
uint256[] calldata values)
external
checkPause
updateRewards(msg.sender)
{
require(tokens.length == values.length, "count mismatch");
address token;
uint256 stakeAmount;
for (uint256 i = 0; i < tokens.length; i++) {
token = tokens[i];
require(token == BZRX || token == vBZRX || token == iBZRX || token == LPToken, "invalid token");
stakeAmount = values[i];
if (stakeAmount == 0) {
continue;
}
_balancesPerToken[token][msg.sender] = _balancesPerToken[token][msg.sender].add(stakeAmount);
_totalSupplyPerToken[token] = _totalSupplyPerToken[token].add(stakeAmount);
IERC20(token).safeTransferFrom(msg.sender, address(this), stakeAmount);
emit Stake(
msg.sender,
token,
msg.sender, //currentDelegate,
stakeAmount
);
}
}
function unstake(
address[] memory tokens,
uint256[] memory values)
public
checkPause
updateRewards(msg.sender)
{
require(tokens.length == values.length, "count mismatch");
address token;
uint256 unstakeAmount;
uint256 stakedAmount;
for (uint256 i = 0; i < tokens.length; i++) {
token = tokens[i];
require(token == BZRX || token == vBZRX || token == iBZRX || token == LPToken || token == LPTokenOld, "invalid token");
unstakeAmount = values[i];
stakedAmount = _balancesPerToken[token][msg.sender];
if (unstakeAmount == 0 || stakedAmount == 0) {
continue;
}
if (unstakeAmount > stakedAmount) {
unstakeAmount = stakedAmount;
}
_balancesPerToken[token][msg.sender] = stakedAmount - unstakeAmount; // will not overflow
_totalSupplyPerToken[token] = _totalSupplyPerToken[token] - unstakeAmount; // will not overflow
if (token == BZRX && IERC20(BZRX).balanceOf(address(this)) < unstakeAmount) {
// settle vested BZRX only if needed
IVestingToken(vBZRX).claim();
}
IERC20(token).safeTransfer(msg.sender, unstakeAmount);
emit Unstake(
msg.sender,
token,
msg.sender, //currentDelegate,
unstakeAmount
);
}
}
function claim(
bool restake)
external
checkPause
updateRewards(msg.sender)
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned)
{
return _claim(restake);
}
function claimBzrx()
external
checkPause
updateRewards(msg.sender)
returns (uint256 bzrxRewardsEarned)
{
bzrxRewardsEarned = _claimBzrx(false);
emit Claim(
msg.sender,
bzrxRewardsEarned,
0
);
}
function claim3Crv()
external
checkPause
updateRewards(msg.sender)
returns (uint256 stableCoinRewardsEarned)
{
stableCoinRewardsEarned = _claim3Crv();
emit Claim(
msg.sender,
0,
stableCoinRewardsEarned
);
}
function _claim(
bool restake)
internal
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned)
{
bzrxRewardsEarned = _claimBzrx(restake);
stableCoinRewardsEarned = _claim3Crv();
emit Claim(
msg.sender,
bzrxRewardsEarned,
stableCoinRewardsEarned
);
}
function _claimBzrx(
bool restake)
internal
returns (uint256 bzrxRewardsEarned)
{
bzrxRewardsEarned = bzrxRewards[msg.sender];
if (bzrxRewardsEarned != 0) {
bzrxRewards[msg.sender] = 0;
if (restake) {
_restakeBZRX(
msg.sender,
bzrxRewardsEarned
);
} else {
if (IERC20(BZRX).balanceOf(address(this)) < bzrxRewardsEarned) {
// settle vested BZRX only if needed
IVestingToken(vBZRX).claim();
}
IERC20(BZRX).transfer(msg.sender, bzrxRewardsEarned);
}
}
}
function _claim3Crv()
internal
returns (uint256 stableCoinRewardsEarned)
{
stableCoinRewardsEarned = stableCoinRewards[msg.sender];
if (stableCoinRewardsEarned != 0) {
stableCoinRewards[msg.sender] = 0;
curve3Crv.transfer(msg.sender, stableCoinRewardsEarned);
}
}
function _restakeBZRX(
address account,
uint256 amount)
internal
{
//address currentDelegate = delegate[account];
_balancesPerToken[BZRX][account] = _balancesPerToken[BZRX][account]
.add(amount);
_totalSupplyPerToken[BZRX] = _totalSupplyPerToken[BZRX]
.add(amount);
emit Stake(
account,
BZRX,
account, //currentDelegate,
amount
);
}
function exit()
public
// unstake() does a checkPause
{
address[] memory tokens = new address[](4);
uint256[] memory values = new uint256[](4);
tokens[0] = iBZRX;
tokens[1] = LPToken;
tokens[2] = vBZRX;
tokens[3] = BZRX;
values[0] = uint256(-1);
values[1] = uint256(-1);
values[2] = uint256(-1);
values[3] = uint256(-1);
unstake(tokens, values); // calls updateRewards
_claim(false);
}
modifier updateRewards(address account) {
uint256 _bzrxPerTokenStored = bzrxPerTokenStored;
uint256 _stableCoinPerTokenStored = stableCoinPerTokenStored;
(uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting) = _earned(
account,
_bzrxPerTokenStored,
_stableCoinPerTokenStored
);
bzrxRewardsPerTokenPaid[account] = _bzrxPerTokenStored;
stableCoinRewardsPerTokenPaid[account] = _stableCoinPerTokenStored;
// vesting amounts get updated before sync
bzrxVesting[account] = bzrxRewardsVesting;
stableCoinVesting[account] = stableCoinRewardsVesting;
(bzrxRewards[account], stableCoinRewards[account]) = _syncVesting(
account,
bzrxRewardsEarned,
stableCoinRewardsEarned,
bzrxRewardsVesting,
stableCoinRewardsVesting
);
vestingLastSync[account] = block.timestamp;
_;
}
function earned(
address account)
external
view
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting)
{
(bzrxRewardsEarned, stableCoinRewardsEarned, bzrxRewardsVesting, stableCoinRewardsVesting) = _earned(
account,
bzrxPerTokenStored,
stableCoinPerTokenStored
);
(bzrxRewardsEarned, stableCoinRewardsEarned) = _syncVesting(
account,
bzrxRewardsEarned,
stableCoinRewardsEarned,
bzrxRewardsVesting,
stableCoinRewardsVesting
);
// discount vesting amounts for vesting time
uint256 multiplier = vestedBalanceForAmount(
1e36,
0,
block.timestamp
);
bzrxRewardsVesting = bzrxRewardsVesting
.sub(bzrxRewardsVesting
.mul(multiplier)
.div(1e36)
);
stableCoinRewardsVesting = stableCoinRewardsVesting
.sub(stableCoinRewardsVesting
.mul(multiplier)
.div(1e36)
);
}
function _earned(
address account,
uint256 _bzrxPerToken,
uint256 _stableCoinPerToken)
internal
view
returns (uint256 bzrxRewardsEarned, uint256 stableCoinRewardsEarned, uint256 bzrxRewardsVesting, uint256 stableCoinRewardsVesting)
{
uint256 bzrxPerTokenUnpaid = _bzrxPerToken.sub(bzrxRewardsPerTokenPaid[account]);
uint256 stableCoinPerTokenUnpaid = _stableCoinPerToken.sub(stableCoinRewardsPerTokenPaid[account]);
bzrxRewardsEarned = bzrxRewards[account];
stableCoinRewardsEarned = stableCoinRewards[account];
bzrxRewardsVesting = bzrxVesting[account];
stableCoinRewardsVesting = stableCoinVesting[account];
if (bzrxPerTokenUnpaid != 0 || stableCoinPerTokenUnpaid != 0) {
uint256 value;
uint256 multiplier;
uint256 lastSync;
(uint256 vestedBalance, uint256 vestingBalance) = balanceOfStored(account);
value = vestedBalance
.mul(bzrxPerTokenUnpaid);
value /= 1e36;
bzrxRewardsEarned = value
.add(bzrxRewardsEarned);
value = vestedBalance
.mul(stableCoinPerTokenUnpaid);
value /= 1e36;
stableCoinRewardsEarned = value
.add(stableCoinRewardsEarned);
if (vestingBalance != 0 && bzrxPerTokenUnpaid != 0) {
// add new vesting amount for BZRX
value = vestingBalance
.mul(bzrxPerTokenUnpaid);
value /= 1e36;
bzrxRewardsVesting = bzrxRewardsVesting
.add(value);
// true up earned amount to vBZRX vesting schedule
lastSync = vestingLastSync[account];
multiplier = vestedBalanceForAmount(
1e36,
0,
lastSync
);
value = value
.mul(multiplier);
value /= 1e36;
bzrxRewardsEarned = bzrxRewardsEarned
.add(value);
}
if (vestingBalance != 0 && stableCoinPerTokenUnpaid != 0) {
// add new vesting amount for 3crv
value = vestingBalance
.mul(stableCoinPerTokenUnpaid);
value /= 1e36;
stableCoinRewardsVesting = stableCoinRewardsVesting
.add(value);
// true up earned amount to vBZRX vesting schedule
if (lastSync == 0) {
lastSync = vestingLastSync[account];
multiplier = vestedBalanceForAmount(
1e36,
0,
lastSync
);
}
value = value
.mul(multiplier);
value /= 1e36;
stableCoinRewardsEarned = stableCoinRewardsEarned
.add(value);
}
}
}
function _syncVesting(
address account,
uint256 bzrxRewardsEarned,
uint256 stableCoinRewardsEarned,
uint256 bzrxRewardsVesting,
uint256 stableCoinRewardsVesting)
internal
view
returns (uint256, uint256)
{
uint256 lastVestingSync = vestingLastSync[account];
if (lastVestingSync != block.timestamp) {
uint256 rewardsVested;
uint256 multiplier = vestedBalanceForAmount(
1e36,
lastVestingSync,
block.timestamp
);
if (bzrxRewardsVesting != 0) {
rewardsVested = bzrxRewardsVesting
.mul(multiplier)
.div(1e36);
bzrxRewardsEarned += rewardsVested;
}
if (stableCoinRewardsVesting != 0) {
rewardsVested = stableCoinRewardsVesting
.mul(multiplier)
.div(1e36);
stableCoinRewardsEarned += rewardsVested;
}
uint256 vBZRXBalance = _balancesPerToken[vBZRX][account];
if (vBZRXBalance != 0) {
// add vested BZRX to rewards balance
rewardsVested = vBZRXBalance
.mul(multiplier)
.div(1e36);
bzrxRewardsEarned += rewardsVested;
}
}
return (bzrxRewardsEarned, stableCoinRewardsEarned);
}
// note: anyone can contribute rewards to the contract
function addDirectRewards(
address[] calldata accounts,
uint256[] calldata bzrxAmounts,
uint256[] calldata stableCoinAmounts)
external
checkPause
returns (uint256 bzrxTotal, uint256 stableCoinTotal)
{
require(accounts.length == bzrxAmounts.length && accounts.length == stableCoinAmounts.length, "count mismatch");
for (uint256 i = 0; i < accounts.length; i++) {
bzrxRewards[accounts[i]] = bzrxRewards[accounts[i]].add(bzrxAmounts[i]);
bzrxTotal = bzrxTotal.add(bzrxAmounts[i]);
stableCoinRewards[accounts[i]] = stableCoinRewards[accounts[i]].add(stableCoinAmounts[i]);
stableCoinTotal = stableCoinTotal.add(stableCoinAmounts[i]);
}
if (bzrxTotal != 0) {
IERC20(BZRX).transferFrom(msg.sender, address(this), bzrxTotal);
}
if (stableCoinTotal != 0) {
curve3Crv.transferFrom(msg.sender, address(this), stableCoinTotal);
}
}
// note: anyone can contribute rewards to the contract
function addRewards(
uint256 newBZRX,
uint256 newStableCoin)
external
checkPause
{
if (newBZRX != 0 || newStableCoin != 0) {
_addRewards(newBZRX, newStableCoin);
if (newBZRX != 0) {
IERC20(BZRX).transferFrom(msg.sender, address(this), newBZRX);
}
if (newStableCoin != 0) {
curve3Crv.transferFrom(msg.sender, address(this), newStableCoin);
}
}
}
function _addRewards(
uint256 newBZRX,
uint256 newStableCoin)
internal
{
(vBZRXWeightStored, iBZRXWeightStored, LPTokenWeightStored) = getVariableWeights();
uint256 totalTokens = totalSupplyStored();
require(totalTokens != 0, "nothing staked");
bzrxPerTokenStored = newBZRX
.mul(1e36)
.div(totalTokens)
.add(bzrxPerTokenStored);
stableCoinPerTokenStored = newStableCoin
.mul(1e36)
.div(totalTokens)
.add(stableCoinPerTokenStored);
lastRewardsAddTime = block.timestamp;
emit AddRewards(
msg.sender,
newBZRX,
newStableCoin
);
}
function getVariableWeights()
public
view
returns (uint256 vBZRXWeight, uint256 iBZRXWeight, uint256 LPTokenWeight)
{
uint256 totalVested = vestedBalanceForAmount(
_startingVBZRXBalance,
0,
block.timestamp
);
vBZRXWeight = SafeMath.mul(_startingVBZRXBalance - totalVested, 1e18) // overflow not possible
.div(_startingVBZRXBalance);
iBZRXWeight = _calcIBZRXWeight();
uint256 lpTokenSupply = _totalSupplyPerToken[LPToken];
if (lpTokenSupply != 0) {
// staked LP tokens are assumed to represent the total unstaked supply (circulated supply - staked BZRX)
uint256 normalizedLPTokenSupply = initialCirculatingSupply +
totalVested -
_totalSupplyPerToken[BZRX];
LPTokenWeight = normalizedLPTokenSupply
.mul(1e18)
.div(lpTokenSupply);
}
}
function _calcIBZRXWeight()
internal
view
returns (uint256)
{
return IERC20(BZRX).balanceOf(iBZRX)
.mul(1e50)
.div(IERC20(iBZRX).totalSupply());
}
function balanceOfByAsset(
address token,
address account)
public
view
returns (uint256 balance)
{
balance = _balancesPerToken[token][account];
}
function balanceOfByAssets(
address account)
external
view
returns (
uint256 bzrxBalance,
uint256 iBZRXBalance,
uint256 vBZRXBalance,
uint256 LPTokenBalance,
uint256 LPTokenBalanceOld
)
{
return (
balanceOfByAsset(BZRX, account),
balanceOfByAsset(iBZRX, account),
balanceOfByAsset(vBZRX, account),
balanceOfByAsset(LPToken, account),
balanceOfByAsset(LPTokenOld, account)
);
}
function balanceOfStored(
address account)
public
view
returns (uint256 vestedBalance, uint256 vestingBalance)
{
uint256 balance = _balancesPerToken[vBZRX][account];
if (balance != 0) {
vestingBalance = _balancesPerToken[vBZRX][account]
.mul(vBZRXWeightStored)
.div(1e18);
}
vestedBalance = _balancesPerToken[BZRX][account];
balance = _balancesPerToken[iBZRX][account];
if (balance != 0) {
vestedBalance = balance
.mul(iBZRXWeightStored)
.div(1e50)
.add(vestedBalance);
}
balance = _balancesPerToken[LPToken][account];
if (balance != 0) {
vestedBalance = balance
.mul(LPTokenWeightStored)
.div(1e18)
.add(vestedBalance);
}
}
function totalSupplyByAsset(
address token)
external
view
returns (uint256)
{
return _totalSupplyPerToken[token];
}
function totalSupplyStored()
public
view
returns (uint256 supply)
{
supply = _totalSupplyPerToken[vBZRX]
.mul(vBZRXWeightStored)
.div(1e18);
supply = _totalSupplyPerToken[BZRX]
.add(supply);
supply = _totalSupplyPerToken[iBZRX]
.mul(iBZRXWeightStored)
.div(1e50)
.add(supply);
supply = _totalSupplyPerToken[LPToken]
.mul(LPTokenWeightStored)
.div(1e18)
.add(supply);
}
function vestedBalanceForAmount(
uint256 tokenBalance,
uint256 lastUpdate,
uint256 vestingEndTime)
public
view
returns (uint256 vested)
{
vestingEndTime = vestingEndTime.min256(block.timestamp);
if (vestingEndTime > lastUpdate) {
if (vestingEndTime <= vestingCliffTimestamp ||
lastUpdate >= vestingEndTimestamp) {
// time cannot be before vesting starts
// OR all vested token has already been claimed
return 0;
}
if (lastUpdate < vestingCliffTimestamp) {
// vesting starts at the cliff timestamp
lastUpdate = vestingCliffTimestamp;
}
if (vestingEndTime > vestingEndTimestamp) {
// vesting ends at the end timestamp
vestingEndTime = vestingEndTimestamp;
}
uint256 timeSinceClaim = vestingEndTime.sub(lastUpdate);
vested = tokenBalance.mul(timeSinceClaim) / vestingDurationAfterCliff; // will never divide by 0
}
}
// Governance Logic //
function votingBalanceOf(
address account,
uint256 proposalId)
public
view
returns (uint256 totalVotes)
{
return _votingBalanceOf(account, _proposalState[proposalId]);
}
function votingBalanceOfNow(
address account)
public
view
returns (uint256 totalVotes)
{
return _votingBalanceOf(account, _getProposalState());
}
function _setProposalVals(
address account,
uint256 proposalId)
public
returns (uint256)
{
require(msg.sender == governor, "unauthorized");
require(_proposalState[proposalId].proposalTime == 0, "proposal exists");
ProposalState memory newProposal = _getProposalState();
_proposalState[proposalId] = newProposal;
return _votingBalanceOf(account, newProposal);
}
function _getProposalState()
internal
view
returns (ProposalState memory)
{
return ProposalState({
proposalTime: block.timestamp - 1,
iBZRXWeight: _calcIBZRXWeight(),
lpBZRXBalance: IERC20(BZRX).balanceOf(LPToken),
lpTotalSupply: IERC20(LPToken).totalSupply()
});
}
function _votingBalanceOf(
address account,
ProposalState memory proposal)
internal
view
returns (uint256 totalVotes)
{
uint256 _vestingLastSync = vestingLastSync[account];
if (proposal.proposalTime == 0 || _vestingLastSync > proposal.proposalTime - 1) {
return 0;
}
uint256 _vBZRXBalance = _balancesPerToken[vBZRX][account];
if (_vBZRXBalance != 0) {
// staked vBZRX is prorated based on total vested
totalVotes = _vBZRXBalance
.mul(_startingVBZRXBalance -
vestedBalanceForAmount( // overflow not possible
_startingVBZRXBalance,
0,
proposal.proposalTime
)
).div(_startingVBZRXBalance);
// user is attributed a staked balance of vested BZRX, from their last update to the present
totalVotes = vestedBalanceForAmount(
_vBZRXBalance,
_vestingLastSync,
proposal.proposalTime
).add(totalVotes);
}
totalVotes = _balancesPerToken[BZRX][account]
.add(bzrxRewards[account]) // unclaimed BZRX rewards count as votes
.add(totalVotes);
totalVotes = _balancesPerToken[iBZRX][account]
.mul(proposal.iBZRXWeight)
.div(1e50)
.add(totalVotes);
// LPToken votes are measured based on amount of underlying BZRX staked
totalVotes = proposal.lpBZRXBalance
.mul(_balancesPerToken[LPToken][account])
.div(proposal.lpTotalSupply)
.add(totalVotes);
}
// Fee Conversion Logic //
function sweepFees()
public
// sweepFeesByAsset() does checkPause
returns (uint256 bzrxRewards, uint256 crv3Rewards)
{
return sweepFeesByAsset(currentFeeTokens);
}
function sweepFeesByAsset(
address[] memory assets)
public
checkPause
onlyEOA
returns (uint256 bzrxRewards, uint256 crv3Rewards)
{
uint256[] memory amounts = _withdrawFees(assets);
_convertFees(assets, amounts);
(bzrxRewards, crv3Rewards) = _distributeFees();
}
function _withdrawFees(
address[] memory assets)
internal
returns (uint256[] memory)
{
uint256[] memory amounts = bZx.withdrawFees(assets, address(this), IBZx.FeeClaimType.All);
for (uint256 i = 0; i < assets.length; i++) {
stakingRewards[assets[i]] = stakingRewards[assets[i]]
.add(amounts[i]);
}
emit WithdrawFees(
msg.sender
);
return amounts;
}
function _convertFees(
address[] memory assets,
uint256[] memory amounts)
internal
returns (uint256 bzrxOutput, uint256 crv3Output)
{
require(assets.length == amounts.length, "count mismatch");
IPriceFeeds priceFeeds = IPriceFeeds(bZx.priceFeeds());
(uint256 bzrxRate,) = priceFeeds.queryRate(
BZRX,
WETH
);
uint256 maxDisagreement = maxUniswapDisagreement;
address asset;
uint256 daiAmount;
uint256 usdcAmount;
uint256 usdtAmount;
for (uint256 i = 0; i < assets.length; i++) {
asset = assets[i];
if (asset == BZRX) {
continue;
} else if (asset == DAI) {
daiAmount = daiAmount.add(amounts[i]);
continue;
} else if (asset == USDC) {
usdcAmount = usdcAmount.add(amounts[i]);
continue;
} else if (asset == USDT) {
usdtAmount = usdtAmount.add(amounts[i]);
continue;
}
if (amounts[i] != 0) {
bzrxOutput += _convertFeeWithUniswap(asset, amounts[i], priceFeeds, bzrxRate, maxDisagreement);
}
}
if (bzrxOutput != 0) {
stakingRewards[BZRX] += bzrxOutput;
}
if (daiAmount != 0 || usdcAmount != 0 || usdtAmount != 0) {
crv3Output = _convertFeesWithCurve(
daiAmount,
usdcAmount,
usdtAmount
);
stakingRewards[address(curve3Crv)] += crv3Output;
}
emit ConvertFees(
msg.sender,
bzrxOutput,
crv3Output
);
}
function _distributeFees()
internal
returns (uint256 bzrxRewards, uint256 crv3Rewards)
{
bzrxRewards = stakingRewards[BZRX];
crv3Rewards = stakingRewards[address(curve3Crv)];
if (bzrxRewards != 0 || crv3Rewards != 0) {
address _fundsWallet = fundsWallet;
uint256 rewardAmount;
uint256 callerReward;
if (bzrxRewards != 0) {
stakingRewards[BZRX] = 0;
rewardAmount = bzrxRewards
.mul(rewardPercent)
.div(1e20);
IERC20(BZRX).transfer(
_fundsWallet,
bzrxRewards - rewardAmount
);
bzrxRewards = rewardAmount;
callerReward = bzrxRewards / callerRewardDivisor;
IERC20(BZRX).transfer(
msg.sender,
callerReward
);
bzrxRewards = bzrxRewards
.sub(callerReward);
}
if (crv3Rewards != 0) {
stakingRewards[address(curve3Crv)] = 0;
rewardAmount = crv3Rewards
.mul(rewardPercent)
.div(1e20);
curve3Crv.transfer(
_fundsWallet,
crv3Rewards - rewardAmount
);
crv3Rewards = rewardAmount;
callerReward = crv3Rewards / callerRewardDivisor;
curve3Crv.transfer(
msg.sender,
callerReward
);
crv3Rewards = crv3Rewards
.sub(callerReward);
}
_addRewards(bzrxRewards, crv3Rewards);
}
emit DistributeFees(
msg.sender,
bzrxRewards,
crv3Rewards
);
}
function _convertFeeWithUniswap(
address asset,
uint256 amount,
IPriceFeeds priceFeeds,
uint256 bzrxRate,
uint256 maxDisagreement)
internal
returns (uint256 returnAmount)
{
uint256 stakingReward = stakingRewards[asset];
if (stakingReward != 0) {
if (amount > stakingReward) {
amount = stakingReward;
}
stakingRewards[asset] = stakingReward
.sub(amount);
uint256[] memory amounts = uniswapRouter.swapExactTokensForTokens(
amount,
1, // amountOutMin
swapPaths[asset],
address(this),
block.timestamp
);
returnAmount = amounts[amounts.length - 1];
// will revert if disagreement found
_checkUniDisagreement(
asset,
amount,
returnAmount,
priceFeeds,
bzrxRate,
maxDisagreement
);
}
}
function _convertFeesWithCurve(
uint256 daiAmount,
uint256 usdcAmount,
uint256 usdtAmount)
internal
returns (uint256 returnAmount)
{
uint256[3] memory curveAmounts;
uint256 curveTotal;
uint256 stakingReward;
if (daiAmount != 0) {
stakingReward = stakingRewards[DAI];
if (stakingReward != 0) {
if (daiAmount > stakingReward) {
daiAmount = stakingReward;
}
stakingRewards[DAI] = stakingReward
.sub(daiAmount);
curveAmounts[0] = daiAmount;
curveTotal = daiAmount;
}
}
if (usdcAmount != 0) {
stakingReward = stakingRewards[USDC];
if (stakingReward != 0) {
if (usdcAmount > stakingReward) {
usdcAmount = stakingReward;
}
stakingRewards[USDC] = stakingReward
.sub(usdcAmount);
curveAmounts[1] = usdcAmount;
curveTotal = curveTotal.add(usdcAmount.mul(1e12)); // normalize to 18 decimals
}
}
if (usdtAmount != 0) {
stakingReward = stakingRewards[USDT];
if (stakingReward != 0) {
if (usdtAmount > stakingReward) {
usdtAmount = stakingReward;
}
stakingRewards[USDT] = stakingReward
.sub(usdtAmount);
curveAmounts[2] = usdtAmount;
curveTotal = curveTotal.add(usdtAmount.mul(1e12)); // normalize to 18 decimals
}
}
uint256 beforeBalance = curve3Crv.balanceOf(address(this));
curve3pool.add_liquidity(curveAmounts, 0);
returnAmount = curve3Crv.balanceOf(address(this)) - beforeBalance;
// will revert if disagreement found
_checkCurveDisagreement(
curveTotal,
returnAmount,
maxCurveDisagreement
);
}
function _checkUniDisagreement(
address asset,
uint256 assetAmount,
uint256 bzrxAmount,
IPriceFeeds priceFeeds,
uint256 bzrxRate,
uint256 maxDisagreement)
internal
view
{
(uint256 rate, uint256 precision) = priceFeeds.queryRate(
asset,
WETH
);
rate = rate
.mul(1e36)
.div(precision)
.div(bzrxRate);
uint256 sourceToDestSwapRate = bzrxAmount
.mul(1e18)
.div(assetAmount);
uint256 spreadValue = sourceToDestSwapRate > rate ?
sourceToDestSwapRate - rate :
rate - sourceToDestSwapRate;
if (spreadValue != 0) {
spreadValue = spreadValue
.mul(1e20)
.div(sourceToDestSwapRate);
require(
spreadValue <= maxDisagreement,
"uniswap price disagreement"
);
}
}
function _checkCurveDisagreement(
uint256 sendAmount, // deposit tokens
uint256 actualReturn, // returned lp token
uint256 maxDisagreement)
internal
view
{
uint256 expectedReturn = sendAmount
.mul(1e18)
.div(curve3pool.get_virtual_price());
uint256 spreadValue = actualReturn > expectedReturn ?
actualReturn - expectedReturn :
expectedReturn - actualReturn;
if (spreadValue != 0) {
spreadValue = spreadValue
.mul(1e20)
.div(actualReturn);
require(
spreadValue <= maxDisagreement,
"curve price disagreement"
);
}
}
// OnlyOwner functions
function togglePause(
bool _isPaused)
external
onlyOwner
{
isPaused = _isPaused;
}
function setFundsWallet(
address _fundsWallet)
external
onlyOwner
{
fundsWallet = _fundsWallet;
}
function setGovernor(
address _governor)
external
onlyOwner
{
governor = _governor;
}
function setFeeTokens(
address[] calldata tokens)
external
onlyOwner
{
currentFeeTokens = tokens;
}
// path should start with the asset to swap and end with BZRX
// only one path allowed per asset
// ex: asset -> WETH -> BZRX
function setPaths(
address[][] calldata paths)
external
onlyOwner
{
address[] memory path;
for (uint256 i = 0; i < paths.length; i++) {
path = paths[i];
require(path.length >= 2 &&
path[0] != path[path.length - 1] &&
path[path.length - 1] == BZRX,
"invalid path"
);
// check that the path exists
uint256[] memory amountsOut = uniswapRouter.getAmountsOut(1e10, path);
require(amountsOut[amountsOut.length - 1] != 0, "path does not exist");
swapPaths[path[0]] = path;
IERC20(path[0]).safeApprove(address(uniswapRouter), 0);
IERC20(path[0]).safeApprove(address(uniswapRouter), uint256(-1));
}
}
function setRewardPercent(
uint256 _rewardPercent)
external
onlyOwner
{
require(_rewardPercent <= 1e20, "value too high");
rewardPercent = _rewardPercent;
}
function setMaxUniswapDisagreement(
uint256 _maxUniswapDisagreement)
external
onlyOwner
{
require(_maxUniswapDisagreement != 0, "invalid param");
maxUniswapDisagreement = _maxUniswapDisagreement;
}
function setMaxCurveDisagreement(
uint256 _maxCurveDisagreement)
external
onlyOwner
{
require(_maxCurveDisagreement != 0, "invalid param");
maxCurveDisagreement = _maxCurveDisagreement;
}
function setCallerRewardDivisor(
uint256 _callerRewardDivisor)
external
onlyOwner
{
require(_callerRewardDivisor != 0, "invalid param");
callerRewardDivisor = _callerRewardDivisor;
}
} | time cannot be before vesting starts OR all vested token has already been claimed vesting starts at the cliff timestamp vesting ends at the end timestamp | function vestedBalanceForAmount(
uint256 tokenBalance,
uint256 lastUpdate,
uint256 vestingEndTime)
public
view
returns (uint256 vested)
{
vestingEndTime = vestingEndTime.min256(block.timestamp);
if (vestingEndTime > lastUpdate) {
if (vestingEndTime <= vestingCliffTimestamp ||
lastUpdate >= vestingEndTimestamp) {
return 0;
}
if (lastUpdate < vestingCliffTimestamp) {
lastUpdate = vestingCliffTimestamp;
}
if (vestingEndTime > vestingEndTimestamp) {
vestingEndTime = vestingEndTimestamp;
}
uint256 timeSinceClaim = vestingEndTime.sub(lastUpdate);
}
}
| 605,453 | [
1,
957,
2780,
506,
1865,
331,
10100,
2542,
4869,
777,
331,
3149,
1147,
711,
1818,
2118,
7516,
329,
331,
10100,
2542,
622,
326,
927,
3048,
2858,
331,
10100,
3930,
622,
326,
679,
2858,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
331,
3149,
13937,
1290,
6275,
12,
203,
3639,
2254,
5034,
1147,
13937,
16,
203,
3639,
2254,
5034,
1142,
1891,
16,
203,
3639,
2254,
5034,
331,
10100,
25255,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
331,
3149,
13,
203,
565,
288,
203,
3639,
331,
10100,
25255,
273,
331,
10100,
25255,
18,
1154,
5034,
12,
2629,
18,
5508,
1769,
203,
3639,
309,
261,
90,
10100,
25255,
405,
1142,
1891,
13,
288,
203,
5411,
309,
261,
90,
10100,
25255,
1648,
331,
10100,
2009,
3048,
4921,
747,
203,
7734,
1142,
1891,
1545,
331,
10100,
1638,
4921,
13,
288,
203,
7734,
327,
374,
31,
203,
5411,
289,
203,
5411,
309,
261,
2722,
1891,
411,
331,
10100,
2009,
3048,
4921,
13,
288,
203,
7734,
1142,
1891,
273,
331,
10100,
2009,
3048,
4921,
31,
203,
5411,
289,
203,
5411,
309,
261,
90,
10100,
25255,
405,
331,
10100,
1638,
4921,
13,
288,
203,
7734,
331,
10100,
25255,
273,
331,
10100,
1638,
4921,
31,
203,
5411,
289,
203,
203,
5411,
2254,
5034,
813,
9673,
9762,
273,
331,
10100,
25255,
18,
1717,
12,
2722,
1891,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.24;
/*
* CrystalAirdropGame
* Author: InspiGames
* Website: https://cryptominingwar.github.io/
*/
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;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract CryptoMiningWarInterface {
uint256 public roundNumber;
uint256 public deadline;
function addCrystal( address _addr, uint256 _value ) public {}
}
contract CrystalAirdropGame {
using SafeMath for uint256;
address public administrator;
// mini game
uint256 public MINI_GAME_TIME_DEFAULT = 60 * 5;
uint256 public MINI_GAME_PRIZE_CRYSTAL = 100;
uint256 public MINI_GAME_BETWEEN_TIME = 8 hours;
uint256 public MINI_GAME_ADD_TIME_DEFAULT = 15;
address public miningWarContractAddress;
uint256 public miniGameId = 0;
uint256 public noRoundMiniGame;
CryptoMiningWarInterface public MiningWarContract;
/**
* Admin can set the bonus of game's reward
*/
uint256 public MINI_GAME_BONUS = 100;
/**
* @dev mini game information
*/
mapping(uint256 => MiniGame) public minigames;
/**
* @dev player information
*/
mapping(address => PlayerData) public players;
struct MiniGame {
uint256 miningWarRoundNumber;
bool ended;
uint256 prizeCrystal;
uint256 startTime;
uint256 endTime;
address playerWin;
uint256 totalPlayer;
}
struct PlayerData {
uint256 currentMiniGameId;
uint256 lastMiniGameId;
uint256 win;
uint256 share;
uint256 totalJoin;
uint256 miningWarRoundNumber;
}
event eventEndMiniGame(
address playerWin,
uint256 crystalBonus
);
event eventJoinMiniGame(
uint256 totalJoin
);
modifier disableContract()
{
require(tx.origin == msg.sender);
_;
}
constructor() public {
administrator = msg.sender;
// set interface main contract
miningWarContractAddress = address(0xf84c61bb982041c030b8580d1634f00fffb89059);
MiningWarContract = CryptoMiningWarInterface(miningWarContractAddress);
}
/**
* @dev MainContract used this function to verify game's contract
*/
function isContractMiniGame() public pure returns( bool _isContractMiniGame )
{
_isContractMiniGame = true;
}
/**
* @dev set discount bonus for game
* require is administrator
*/
function setDiscountBonus( uint256 _discountBonus ) public
{
require( administrator == msg.sender );
MINI_GAME_BONUS = _discountBonus;
}
/**
* @dev Main Contract call this function to setup mini game.
* @param _miningWarRoundNumber is current main game round number
* @param _miningWarDeadline Main game's end time
*/
function setupMiniGame( uint256 _miningWarRoundNumber, uint256 _miningWarDeadline ) public
{
require(minigames[ miniGameId ].miningWarRoundNumber < _miningWarRoundNumber && msg.sender == miningWarContractAddress);
// rerest current mini game to default
minigames[ miniGameId ] = MiniGame(0, true, 0, 0, 0, 0x0, 0);
noRoundMiniGame = 0;
startMiniGame();
}
/**
* @dev start the mini game
*/
function startMiniGame() private
{
uint256 miningWarRoundNumber = getMiningWarRoundNumber();
require(minigames[ miniGameId ].ended == true);
// caculate information for next mini game
uint256 currentPrizeCrystal;
if ( noRoundMiniGame == 0 ) {
currentPrizeCrystal = SafeMath.div(SafeMath.mul(MINI_GAME_PRIZE_CRYSTAL, MINI_GAME_BONUS),100);
} else {
uint256 rate = 168 * MINI_GAME_BONUS;
currentPrizeCrystal = SafeMath.div(SafeMath.mul(minigames[miniGameId].prizeCrystal, rate), 10000); // price * 168 / 100 * MINI_GAME_BONUS / 100
}
uint256 startTime = now + MINI_GAME_BETWEEN_TIME;
uint256 endTime = startTime + MINI_GAME_TIME_DEFAULT;
noRoundMiniGame = noRoundMiniGame + 1;
// start new round mini game
miniGameId = miniGameId + 1;
minigames[ miniGameId ] = MiniGame(miningWarRoundNumber, false, currentPrizeCrystal, startTime, endTime, 0x0, 0);
}
/**
* @dev end Mini Game's round
*/
function endMiniGame() private
{
require(minigames[ miniGameId ].ended == false && (minigames[ miniGameId ].endTime <= now ));
uint256 crystalBonus = SafeMath.div( SafeMath.mul(minigames[ miniGameId ].prizeCrystal, 50), 100 );
// update crystal bonus for player win
if (minigames[ miniGameId ].playerWin != 0x0) {
PlayerData storage p = players[minigames[ miniGameId ].playerWin];
p.win = p.win + crystalBonus;
}
// end current mini game
minigames[ miniGameId ].ended = true;
emit eventEndMiniGame(minigames[ miniGameId ].playerWin, crystalBonus);
// start new mini game
startMiniGame();
}
/**
* @dev player join this round
*/
function joinMiniGame() public disableContract
{
require(now >= minigames[ miniGameId ].startTime && minigames[ miniGameId ].ended == false);
PlayerData storage p = players[msg.sender];
if (now <= minigames[ miniGameId ].endTime) {
// update player data in current mini game
if (p.currentMiniGameId == miniGameId) {
p.totalJoin = p.totalJoin + 1;
} else {
// if player join an new mini game then update share of last mini game for this player
updateShareCrystal();
p.currentMiniGameId = miniGameId;
p.totalJoin = 1;
p.miningWarRoundNumber = minigames[ miniGameId ].miningWarRoundNumber;
}
// update information for current mini game
if ( p.totalJoin <= 1 ) { // this player into the current mini game for the first time
minigames[ miniGameId ].totalPlayer = minigames[ miniGameId ].totalPlayer + 1;
}
minigames[ miniGameId ].playerWin = msg.sender;
minigames[ miniGameId ].endTime = minigames[ miniGameId ].endTime + MINI_GAME_ADD_TIME_DEFAULT;
emit eventJoinMiniGame(p.totalJoin);
} else {
// need run end round
if (minigames[ miniGameId ].playerWin == 0x0) {
updateShareCrystal();
p.currentMiniGameId = miniGameId;
p.lastMiniGameId = miniGameId;
p.totalJoin = 1;
p.miningWarRoundNumber = minigames[ miniGameId ].miningWarRoundNumber;
minigames[ miniGameId ].playerWin = msg.sender;
}
endMiniGame();
}
}
/**
* @dev update share bonus for player who join the game
*/
function updateShareCrystal() private
{
uint256 miningWarRoundNumber = getMiningWarRoundNumber();
PlayerData storage p = players[msg.sender];
// check current mini game of player join. if mining war start new round then reset player data
if ( p.miningWarRoundNumber != miningWarRoundNumber) {
p.share = 0;
p.win = 0;
} else if (minigames[ p.currentMiniGameId ].ended == true && p.lastMiniGameId < p.currentMiniGameId && minigames[ p.currentMiniGameId ].miningWarRoundNumber == miningWarRoundNumber) {
// check current mini game of player join, last update mini game and current mining war round id
// require this mini game is children of mining war game( is current mining war round id )
p.share = SafeMath.add(p.share, calculateShareCrystal(p.currentMiniGameId));
p.lastMiniGameId = p.currentMiniGameId;
}
}
/**
* @dev claim crystals
*/
function claimCrystal() public
{
// should run end round
if ( minigames[miniGameId].endTime < now ) {
endMiniGame();
}
updateShareCrystal();
// update crystal for this player to main game
uint256 crystalBonus = players[msg.sender].win + players[msg.sender].share;
MiningWarContract.addCrystal(msg.sender,crystalBonus);
// update player data. reset value win and share of player
PlayerData storage p = players[msg.sender];
p.win = 0;
p.share = 0;
}
/**
* @dev calculate share crystal of player
*/
function calculateShareCrystal(uint256 _miniGameId) public view returns(uint256 _share)
{
PlayerData memory p = players[msg.sender];
if ( p.lastMiniGameId >= p.currentMiniGameId && p.currentMiniGameId != 0) {
_share = 0;
} else {
_share = SafeMath.div( SafeMath.div( SafeMath.mul(minigames[ _miniGameId ].prizeCrystal, 50), 100 ), minigames[ _miniGameId ].totalPlayer );
}
}
function getMiningWarDealine () private view returns( uint256 _dealine )
{
_dealine = MiningWarContract.deadline();
}
function getMiningWarRoundNumber () private view returns( uint256 _roundNumber )
{
_roundNumber = MiningWarContract.roundNumber();
}
} | * Admin can set the bonus of game's reward/* @dev mini game information/* @dev player information/ | struct MiniGame {
uint256 miningWarRoundNumber;
bool ended;
uint256 prizeCrystal;
uint256 startTime;
uint256 endTime;
address playerWin;
uint256 totalPlayer;
}
| 2,124,681 | [
1,
4446,
848,
444,
326,
324,
22889,
434,
7920,
10,
5520,
31,
87,
19890,
19,
225,
21959,
7920,
1779,
19,
225,
7291,
1779,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
1958,
27987,
12496,
288,
203,
3639,
2254,
5034,
1131,
310,
30634,
11066,
1854,
31,
203,
3639,
1426,
16926,
31,
7010,
3639,
2254,
5034,
846,
554,
12893,
31365,
31,
203,
3639,
2254,
5034,
8657,
31,
203,
3639,
2254,
5034,
13859,
31,
203,
3639,
1758,
7291,
18049,
31,
203,
3639,
2254,
5034,
2078,
12148,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/56/0x20522019a3c2F35537561E75C519F19bd5Ae0d4A/sources/factory test.sol | single check is sufficient
| require(getPair[token0][token1] == address(0), 'BallswapV1: PAIR_EXISTS'); | 3,252,028 | [
1,
7526,
866,
353,
18662,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
3639,
2583,
12,
588,
4154,
63,
2316,
20,
6362,
2316,
21,
65,
422,
1758,
12,
20,
3631,
296,
38,
454,
22270,
58,
21,
30,
15662,
7937,
67,
21205,
8284,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0x7E739Af6cb9BD1c618f51278A32F40b5c2e69bE6/sources/contracts/nftbond/NFTBond.sol | * @title NFTBond @dev Contains functions related to buying and liquidating bonds, and borrowing and returning funds @author Ethichub/ | abstract contract NFTBond is NFT, CollateralizedBondGranter, LiquidityRequester, PausableUpgradeable {
using Strings for uint256;
using DecimalStrings for uint256;
function __NFTBond_init(
string calldata _name,
string calldata _symbol
)
pragma solidity 0.8.13;
internal initializer {
__NFT_init(_name, _symbol);
}
function returnLiquidity(uint256 amount) public payable virtual override returns (uint256) {
_beforeReturnLiquidity();
super.returnLiquidity(amount);
_afterReturnLiquidity(amount);
return totalBorrowed;
}
function requestLiquidity(address destination, uint256 amount) public override whenNotPaused returns (uint256) {
_beforeRequestLiquidity(destination, amount);
super.requestLiquidity(destination, amount);
return totalBorrowed;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), "ERC721: nonexistent token");
Bond memory bond = bonds[tokenId];
if (bytes(bond.imageCID).length != 0) {
return _bondTokenURI(tokenId);
return super.tokenURI(tokenId);
}
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), "ERC721: nonexistent token");
Bond memory bond = bonds[tokenId];
if (bytes(bond.imageCID).length != 0) {
return _bondTokenURI(tokenId);
return super.tokenURI(tokenId);
}
}
} else {
function _buyBond(
address beneficiary,
uint256 maturity,
uint256 principal,
string memory imageCID
)
internal returns (uint256) {
require(msg.sender == beneficiary, "NFTBond::Beneficiary != sender");
_beforeBondPurchased(beneficiary, maturity, principal);
uint256 tokenId = _safeMint(beneficiary, "");
super._issueBond(tokenId, maturity, principal, imageCID);
_afterBondPurchased(beneficiary, maturity, principal, tokenId);
return tokenId;
}
function _redeemBond(uint256 tokenId) internal virtual override returns (uint256) {
uint256 amount = super._redeemBond(tokenId);
address beneficiary = ownerOf(tokenId);
_afterBondRedeemed(tokenId, amount, beneficiary);
return amount;
}
) internal virtual {}
) internal virtual {}
function _beforeBondRedeemed(uint256 tokenId, uint256 value) internal virtual {}
function _afterBondRedeemed(uint256 tokenId, uint256 value, address beneficiary) internal virtual {}
function _beforeRequestLiquidity(address destination, uint256 amount) internal virtual {}
function _afterRequestLiquidity(address destination) internal virtual {}
function _beforeReturnLiquidity() internal virtual {}
function _afterReturnLiquidity(uint256 amount) internal virtual {}
function _beforeBondPurchased(
address beneficiary,
uint256 maturity,
uint256 principal
function _afterBondPurchased(
address beneficiary,
uint256 maturity,
uint256 principal,
uint256 tokenId
function _bondTokenURI(uint256 tokenId) private view returns (string memory) {
Bond memory bond = bonds[tokenId];
string memory dataJSON = string.concat(
'{'
'"name": "', string.concat('Minimice Yield Bond #', tokenId.toString()), '", ',
'"description": "MiniMice Risk Yield Bond from EthicHub.", ',
'"attributes": [',
_setAttribute('Principal', string.concat(bond.principal._decimalString(18, false), ' USD')),',',
_setAttribute('Collateral', string.concat(calculateCollateralBondAmount(bond.principal)._decimalString(18, false), ' Ethix')),',',
_setAttribute('APY', (bond.interest*365 days/1e16)._decimalString(2, true)),',',
_setAttribute('Maturity', string.concat((bond.maturity*1e2/30 days)._decimalString(2, false), ' Months')),',',
_setAttribute('Maturity Unix Timestamp', (bond.mintingDate + bond.maturity).toString()),
']'
'}'
);
return string.concat("data:application/json;base64,", Base64.encode(bytes(dataJSON)));
}
function _beforeBondPurchased(
address beneficiary,
uint256 maturity,
uint256 principal
function _afterBondPurchased(
address beneficiary,
uint256 maturity,
uint256 principal,
uint256 tokenId
function _bondTokenURI(uint256 tokenId) private view returns (string memory) {
Bond memory bond = bonds[tokenId];
string memory dataJSON = string.concat(
'{'
'"name": "', string.concat('Minimice Yield Bond #', tokenId.toString()), '", ',
'"description": "MiniMice Risk Yield Bond from EthicHub.", ',
'"attributes": [',
_setAttribute('Principal', string.concat(bond.principal._decimalString(18, false), ' USD')),',',
_setAttribute('Collateral', string.concat(calculateCollateralBondAmount(bond.principal)._decimalString(18, false), ' Ethix')),',',
_setAttribute('APY', (bond.interest*365 days/1e16)._decimalString(2, true)),',',
_setAttribute('Maturity', string.concat((bond.maturity*1e2/30 days)._decimalString(2, false), ' Months')),',',
_setAttribute('Maturity Unix Timestamp', (bond.mintingDate + bond.maturity).toString()),
']'
'}'
);
return string.concat("data:application/json;base64,", Base64.encode(bytes(dataJSON)));
}
function _setAttribute(string memory _name, string memory _value) private pure returns (string memory) {
}
uint256[49] private __gap;
return string.concat('{"trait_type":"', _name,'","value":"', _value,'"}');
} | 7,072,167 | [
1,
50,
4464,
9807,
225,
8398,
4186,
3746,
358,
30143,
310,
471,
4501,
26595,
1776,
15692,
16,
471,
29759,
310,
471,
5785,
284,
19156,
225,
512,
451,
1354,
373,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
17801,
6835,
423,
4464,
9807,
353,
423,
4464,
16,
17596,
2045,
287,
1235,
9807,
43,
2450,
387,
16,
511,
18988,
24237,
30260,
16,
21800,
16665,
10784,
429,
288,
203,
565,
1450,
8139,
364,
2254,
5034,
31,
203,
565,
1450,
11322,
7957,
364,
2254,
5034,
31,
203,
203,
565,
445,
1001,
50,
4464,
9807,
67,
2738,
12,
203,
3639,
533,
745,
892,
389,
529,
16,
203,
3639,
533,
745,
892,
389,
7175,
203,
565,
262,
203,
683,
9454,
18035,
560,
374,
18,
28,
18,
3437,
31,
203,
565,
2713,
12562,
288,
203,
3639,
1001,
50,
4464,
67,
2738,
24899,
529,
16,
389,
7175,
1769,
203,
565,
289,
203,
203,
565,
445,
327,
48,
18988,
24237,
12,
11890,
5034,
3844,
13,
1071,
8843,
429,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
389,
5771,
990,
48,
18988,
24237,
5621,
203,
3639,
2240,
18,
2463,
48,
18988,
24237,
12,
8949,
1769,
203,
3639,
389,
5205,
990,
48,
18988,
24237,
12,
8949,
1769,
203,
3639,
327,
2078,
38,
15318,
329,
31,
203,
565,
289,
203,
203,
565,
445,
590,
48,
18988,
24237,
12,
2867,
2929,
16,
2254,
5034,
3844,
13,
1071,
3849,
1347,
1248,
28590,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
389,
5771,
691,
48,
18988,
24237,
12,
10590,
16,
3844,
1769,
203,
3639,
2240,
18,
2293,
48,
18988,
24237,
12,
10590,
16,
3844,
1769,
203,
3639,
327,
2078,
38,
15318,
329,
31,
203,
565,
289,
203,
203,
565,
445,
1147,
3098,
12,
11890,
5034,
1147,
548,
13,
203,
3639,
1071,
203,
3639,
1476,
2
]
|
./full_match/421613/0x712A3480705560bB3158c8933403B04564305158/sources/project_/contracts/tokens/Corn.sol | GETTERS* @dev Return the amount available to harvest at a specific block by farm/ Owning a farmer increase the length of the growth cycle | {
require(targetBlock <= block.number, "You can only calculate up to current block");
require(farm.lastHarvestedBlockNumber <= targetBlock, "You can only specify blocks at or ahead of last harvested block");
} else {
}
| 11,566,874 | [
1,
7113,
1470,
11367,
225,
2000,
326,
3844,
2319,
358,
17895,
26923,
622,
279,
2923,
1203,
635,
284,
4610,
19,
14223,
2093,
279,
284,
4610,
264,
10929,
326,
769,
434,
326,
13334,
451,
8589,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
288,
203,
3639,
2583,
12,
3299,
1768,
1648,
1203,
18,
2696,
16,
28524,
29159,
315,
6225,
848,
1338,
4604,
731,
358,
783,
1203,
8863,
203,
3639,
2583,
12,
74,
4610,
18,
2722,
44,
297,
90,
3149,
1768,
1854,
1648,
1018,
1768,
16,
28524,
13491,
315,
6225,
848,
1338,
4800,
4398,
622,
578,
17510,
434,
1142,
17895,
90,
3149,
1203,
8863,
203,
203,
3639,
289,
469,
288,
203,
3639,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/80001/0x0e09008f63e4A0ec8e2dE9785Ea857c77B0c7CE3/sources/project:/contracts/MarketplaceAssets.sol | * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension/ | interface IERC721Enumerable is IERC721 {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(
address owner,
uint256 index
) external view returns (uint256);
function tokenByIndex(uint256 index) external view returns (uint256);
}
}
| 870,922 | [
1,
654,
39,
17,
27,
5340,
3858,
17,
42,
20651,
1523,
3155,
8263,
16,
3129,
16836,
2710,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
467,
654,
39,
27,
5340,
3572,
25121,
353,
467,
654,
39,
27,
5340,
288,
203,
565,
445,
2078,
3088,
1283,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
1147,
951,
5541,
21268,
12,
203,
3639,
1758,
3410,
16,
203,
3639,
2254,
5034,
770,
203,
565,
262,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
1147,
21268,
12,
11890,
5034,
770,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
97,
203,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0x5358a276C28028dB9DCcD5Fe1fC92540652530aa/sources/contracts/messageService/lib/Rlp.sol | * @param _item The RLP item. @return Indicator whether encoded payload is a list./ | function _isList(RLPItem memory _item) internal pure returns (bool) {
if (_item.len == 0) return false;
uint8 byte0;
uint256 memPtr = _item.memPtr;
assembly {
byte0 := byte(0, mload(memPtr))
}
if (byte0 < LIST_SHORT_START) return false;
return true;
}
| 7,069,875 | [
1,
67,
1726,
1021,
534,
14461,
761,
18,
327,
26871,
2856,
3749,
2385,
353,
279,
666,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
389,
291,
682,
12,
54,
48,
1102,
874,
3778,
389,
1726,
13,
2713,
16618,
1135,
261,
6430,
13,
288,
203,
565,
309,
261,
67,
1726,
18,
1897,
422,
374,
13,
327,
629,
31,
203,
203,
565,
2254,
28,
1160,
20,
31,
203,
565,
2254,
5034,
1663,
5263,
273,
389,
1726,
18,
3917,
5263,
31,
203,
565,
19931,
288,
203,
1377,
1160,
20,
519,
1160,
12,
20,
16,
312,
945,
12,
3917,
5263,
3719,
203,
565,
289,
203,
203,
565,
309,
261,
7229,
20,
411,
15130,
67,
15993,
67,
7570,
13,
327,
629,
31,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.4;
import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
contract MarzResources is ERC1155Upgradeable {
using StringsUpgradeable for uint256;
uint256 private constant SECONDS_PER_MINING_PERIOD = 86400;
uint256 private constant CLAIMS_PER_PLOT = 30;
// COMMON
uint256 public constant DIRT = 0;
uint256 public constant TIN = 1;
uint256 public constant COPPER = 2;
uint256 public constant IRON = 3;
uint256 public constant NICKEL = 4;
uint256 public constant ZINC = 5;
uint256[6] private COMMON;
// UNCOMMON
uint256 public constant ICE = 6;
uint256 public constant LEAD = 7;
uint256 public constant BISMUTH = 8;
uint256 public constant ANTIMONY = 9;
uint256 public constant LITHIUM = 10;
uint256 public constant COBALT = 11;
uint256[6] private UNCOMMON;
// RARE
uint256 public constant SILVER = 12;
uint256 public constant GOLD = 13;
uint256 public constant CHROMIUM = 14;
uint256 public constant MERCURY = 15;
uint256 public constant TUNGSTEN = 16;
uint256[5] private RARE;
// INSANE :o
uint256 public constant BACTERIA = 17;
uint256 public constant DIAMOND = 18;
uint256[2] private INSANE;
mapping(uint256 => uint256) public startTimes;
mapping(uint256 => uint256) public claimed;
address public marz;
string public constant baseURI = "https://api.marzmining.xyz/token/";
string public constant name = "Marz Resources";
string public constant symbol = "rMARZ";
//--------------------------------------------------------------------------
// Public functions
function initialize(address _marz) external initializer {
__ERC1155_init("https://api.marzmining.xyz/token/{id}");
marz = _marz;
// upgradeable contracts need variables to be set in the initializer
COMMON = [DIRT, TIN, COPPER, IRON, NICKEL, ZINC];
UNCOMMON = [ICE, LEAD, BISMUTH, ANTIMONY, LITHIUM, COBALT];
RARE = [SILVER, GOLD, CHROMIUM, MERCURY, TUNGSTEN];
INSANE = [BACTERIA, DIAMOND];
}
/**
* Return array of resources found at a given plot number
* There will be between 1 and 4 resources of varying rarities at each plot
*/
function getResources(uint256 plotId) public view returns (uint256[] memory resources) {
uint256 countRand = random(string(abi.encodePacked("COUNT", plotId.toString())));
uint256 countScore = countRand % 21;
uint256 resourceCount = countScore < 12 ? 1 : countScore < 18 ? 2 : countScore < 20 ? 3 : 4;
resources = new uint256[](resourceCount);
for (uint256 i = 0; i < resourceCount; i++) {
uint256 rarityRand = random(string(abi.encodePacked("RARITY", i, plotId.toString())));
uint256 rarity = rarityRand % 101;
// ~1% chance you have this
if (rarity == 100) {
resources[i] = INSANE[rarityRand % INSANE.length];
}
// ~5% chance you have this
else if (rarity > 95) {
resources[i] = RARE[rarityRand % RARE.length];
}
// ~15% chance you have this
else if (rarity > 80) {
resources[i] = UNCOMMON[rarityRand % UNCOMMON.length];
}
// ~80% chance you have this
else {
resources[i] = COMMON[rarityRand % COMMON.length];
}
}
}
/**
* Starts mining a given plot
* Outputs one of each resource found on that plot per period
* with maximum of CLAIMS_PER_PLOT
*/
function mine(uint256 plotId) external {
// throws if not yet minted
address owner = IERC721Upgradeable(marz).ownerOf(plotId);
if (startTimes[plotId] == 0) {
startTimes[plotId] = block.timestamp;
claimed[plotId] = 1;
// output one at the start for fun
uint256[] memory resources = getResources(plotId);
uint256[] memory amounts = new uint256[](resources.length);
for (uint256 i = 0; i < resources.length; i++) {
amounts[i] = 1;
}
_mintBatch(owner, resources, amounts, "");
} else {
uint256 numClaimed = claimed[plotId];
require(numClaimed < CLAIMS_PER_PLOT, "Already claimed all resources");
// add one because of the free initial mint
uint256 totalMined = ((block.timestamp - startTimes[plotId]) /
SECONDS_PER_MINING_PERIOD) + 1;
if (totalMined > CLAIMS_PER_PLOT) {
totalMined = CLAIMS_PER_PLOT;
}
uint256 numToClaim = totalMined - numClaimed;
require(numToClaim > 0, "No resources to claim");
claimed[plotId] = totalMined;
uint256[] memory resources = getResources(plotId);
uint256[] memory amounts = new uint256[](resources.length);
for (uint256 i = 0; i < resources.length; i++) {
amounts[i] = numToClaim;
}
_mintBatch(owner, resources, amounts, "");
}
}
function uri(uint256 tokenId) public view override returns (string memory) {
return string(abi.encodePacked(baseURI, tokenId.toString()));
}
function random(string memory input) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(input)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC1155Upgradeable.sol";
import "./IERC1155ReceiverUpgradeable.sol";
import "./extensions/IERC1155MetadataURIUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable {
using AddressUpgradeable for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
function __ERC1155_init(string memory uri_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC1155_init_unchained(uri_);
}
function __ERC1155_init_unchained(string memory uri_) internal initializer {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC1155Upgradeable).interfaceId ||
interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155ReceiverUpgradeable.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
uint256[47] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC1155Upgradeable.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
| * Return array of resources found at a given plot number There will be between 1 and 4 resources of varying rarities at each plot/ ~1% chance you have this ~5% chance you have this ~15% chance you have this ~80% chance you have this | function getResources(uint256 plotId) public view returns (uint256[] memory resources) {
uint256 countRand = random(string(abi.encodePacked("COUNT", plotId.toString())));
uint256 countScore = countRand % 21;
uint256 resourceCount = countScore < 12 ? 1 : countScore < 18 ? 2 : countScore < 20 ? 3 : 4;
resources = new uint256[](resourceCount);
for (uint256 i = 0; i < resourceCount; i++) {
uint256 rarityRand = random(string(abi.encodePacked("RARITY", i, plotId.toString())));
uint256 rarity = rarityRand % 101;
if (rarity == 100) {
resources[i] = INSANE[rarityRand % INSANE.length];
}
else if (rarity > 95) {
resources[i] = RARE[rarityRand % RARE.length];
}
else if (rarity > 80) {
resources[i] = UNCOMMON[rarityRand % UNCOMMON.length];
}
else {
resources[i] = COMMON[rarityRand % COMMON.length];
}
}
}
| 1,430,542 | [
1,
990,
526,
434,
2703,
1392,
622,
279,
864,
3207,
1300,
6149,
903,
506,
3086,
404,
471,
1059,
2703,
434,
569,
14946,
436,
297,
1961,
622,
1517,
3207,
19,
4871,
21,
9,
17920,
1846,
1240,
333,
225,
4871,
25,
9,
17920,
1846,
1240,
333,
4871,
3600,
9,
17920,
1846,
1240,
333,
4871,
3672,
9,
17920,
225,
1846,
1240,
333,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
14590,
12,
11890,
5034,
3207,
548,
13,
1071,
1476,
1135,
261,
11890,
5034,
8526,
3778,
2703,
13,
288,
203,
3639,
2254,
5034,
1056,
54,
464,
273,
2744,
12,
1080,
12,
21457,
18,
3015,
4420,
329,
2932,
7240,
3113,
3207,
548,
18,
10492,
1435,
3719,
1769,
203,
3639,
2254,
5034,
1056,
7295,
273,
1056,
54,
464,
738,
9035,
31,
203,
3639,
2254,
5034,
1058,
1380,
273,
1056,
7295,
411,
2593,
692,
404,
294,
1056,
7295,
411,
6549,
692,
576,
294,
1056,
7295,
411,
4200,
692,
890,
294,
1059,
31,
203,
203,
3639,
2703,
273,
394,
2254,
5034,
8526,
12,
3146,
1380,
1769,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
1058,
1380,
31,
277,
27245,
288,
203,
5411,
2254,
5034,
436,
20498,
54,
464,
273,
2744,
12,
1080,
12,
21457,
18,
3015,
4420,
329,
2932,
54,
985,
4107,
3113,
277,
16,
3207,
548,
18,
10492,
1435,
3719,
1769,
203,
5411,
2254,
5034,
436,
20498,
273,
436,
20498,
54,
464,
738,
13822,
31,
203,
203,
5411,
309,
261,
86,
20498,
422,
2130,
13,
288,
203,
7734,
2703,
63,
77,
65,
273,
2120,
22721,
41,
63,
86,
20498,
54,
464,
738,
2120,
22721,
41,
18,
2469,
15533,
203,
5411,
289,
203,
5411,
469,
309,
261,
86,
20498,
405,
16848,
13,
288,
203,
7734,
2703,
63,
77,
65,
273,
534,
9332,
63,
86,
20498,
54,
464,
738,
534,
9332,
18,
2469,
15533,
203,
5411,
289,
203,
5411,
469,
309,
261,
86,
20498,
405,
8958,
13,
288,
203,
7734,
2703,
63,
77,
65,
2
]
|
./full_match/1/0x8CC23A8CFE803f8E9Ee978bD7F9D343eeA0Cf82F/sources/src/LockRewards.sol | * @notice Set a new epoch. The amount needed of tokens should be transfered before calling setNextEpoch. Can only have 2 epochs set, the on going one and the next. @dev Can set a start epoch different from now when there's no epoch on going. If there's an epoch on going, can only set the start after the finish of current epoch. @param values: the amount of rewards to be distributed tokens @param epochDurationInDays: how long the epoch will last in days @param epochStart: the epoch start date in unix epoch (seconds)/ | function setNextEpoch(uint256[] calldata values, uint256 epochDurationInDays, uint256 epochStart)
external
onlyRole(EPOCH_SETTER_ROLE)
updateEpoch
{
if (values.length != rewardTokens.length) {
revert IncorrectRewards(values.length, rewardTokens.length);
}
_setEpoch(values, epochDurationInDays, epochStart);
}
| 9,625,215 | [
1,
694,
279,
394,
7632,
18,
1021,
3844,
3577,
434,
2430,
1410,
506,
7412,
329,
1865,
4440,
27674,
14638,
18,
4480,
1338,
1240,
576,
25480,
444,
16,
326,
603,
8554,
1245,
471,
326,
1024,
18,
282,
4480,
444,
279,
787,
7632,
3775,
628,
2037,
1347,
1915,
1807,
1158,
7632,
603,
8554,
18,
971,
1915,
1807,
392,
7632,
603,
8554,
16,
848,
1338,
444,
326,
787,
1839,
326,
4076,
434,
783,
7632,
18,
282,
924,
30,
326,
3844,
434,
283,
6397,
358,
506,
16859,
2430,
282,
7632,
5326,
382,
9384,
30,
3661,
1525,
326,
7632,
903,
1142,
316,
4681,
282,
7632,
1685,
30,
326,
7632,
787,
1509,
316,
9753,
7632,
261,
7572,
13176,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
27674,
14638,
12,
11890,
5034,
8526,
745,
892,
924,
16,
2254,
5034,
7632,
5326,
382,
9384,
16,
2254,
5034,
7632,
1685,
13,
203,
3639,
3903,
203,
3639,
1338,
2996,
12,
41,
30375,
67,
1090,
11976,
67,
16256,
13,
203,
3639,
1089,
14638,
203,
565,
288,
203,
3639,
309,
261,
2372,
18,
2469,
480,
19890,
5157,
18,
2469,
13,
288,
203,
5411,
15226,
657,
6746,
17631,
14727,
12,
2372,
18,
2469,
16,
19890,
5157,
18,
2469,
1769,
203,
3639,
289,
203,
3639,
389,
542,
14638,
12,
2372,
16,
7632,
5326,
382,
9384,
16,
7632,
1685,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/3/0x49939B1610162C9128e2281366b2a6672C5fAad9/sources/HospitalManagement.sol | * @dev doctor Review the patient details and start the required treatment process. doctor updating the treatment process. Throws if called by any account other than the doctor./ | function treatmentStatus(uint256 _npiNo,uint256 _claimId)
public isDoctor(_npiNo) {
require(treatmentDetails[_claimId].appoinmentID != 0 ,"HospitalManagement : Not exist");
treatmentDetails[claimId].treatmentStatus=true;
}
| 5,195,723 | [
1,
2896,
30206,
21354,
326,
18608,
3189,
471,
787,
326,
1931,
24266,
1207,
18,
741,
30206,
9702,
326,
24266,
1207,
18,
22435,
309,
2566,
635,
1281,
2236,
1308,
2353,
326,
741,
30206,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
24266,
1482,
12,
11890,
5034,
389,
6782,
77,
2279,
16,
11890,
5034,
389,
14784,
548,
13,
7010,
540,
1071,
353,
3244,
30206,
24899,
6782,
77,
2279,
13,
288,
203,
2398,
203,
5411,
2583,
12,
25707,
3790,
63,
67,
14784,
548,
8009,
2910,
885,
475,
734,
480,
374,
225,
269,
6,
44,
538,
84,
7053,
10998,
294,
2288,
1005,
8863,
203,
2398,
203,
5411,
24266,
3790,
63,
14784,
548,
8009,
25707,
1482,
33,
3767,
31,
203,
2868,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/5/0x3e004b1a415B45C8E2213CAc32a597FDee92BfC3/sources/contracts/StakingContract5.sol | First deposit address that can be WITHDRAWN
| mapping(address => uint256) public currentId; | 1,854,341 | [
1,
3759,
443,
1724,
1758,
716,
848,
506,
13601,
28446,
5665,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
1071,
783,
548,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.20;
contract Accessible {
/** Access Right Management **
* Copyright 2019
* Florian Weigand
* Synalytix UG, Munich
* florian(at)synalytix.de
*/
address public owner;
mapping(address => bool) public accessAllowed;
function Accessible() public {
owner = msg.sender;
}
modifier ownership() {
require(owner == msg.sender);
_;
}
modifier accessible() {
require(accessAllowed[msg.sender]);
_;
}
function allowAccess(address _address) ownership public {
if (_address != address(0)) {
accessAllowed[_address] = true;
}
}
function denyAccess(address _address) ownership public {
if (_address != address(0)) {
accessAllowed[_address] = false;
}
}
function transferOwnership(address _address) ownership public {
if (_address != address(0)) {
owner = _address;
}
}
}
contract TrueProfileStorage is Accessible {
/** Data Storage Contract **
* Copyright 2019
* Florian Weigand
* Synalytix UG, Munich
* florian(at)synalytix.de
*/
/**** signature struct ****/
struct Signature {
uint8 v;
bytes32 r;
bytes32 s;
uint8 revocationReasonId;
bool isValue;
}
/**** signature storage ****/
mapping(bytes32 => Signature) public signatureStorage;
/**** general storage of non-struct data which might
be needed for further development of main contract ****/
mapping(bytes32 => uint256) public uIntStorage;
mapping(bytes32 => string) public stringStorage;
mapping(bytes32 => address) public addressStorage;
mapping(bytes32 => bytes) public bytesStorage;
mapping(bytes32 => bool) public boolStorage;
mapping(bytes32 => int256) public intStorage;
/**** CRUD for Signature storage ****/
function getSignature(bytes32 _key) external view returns (uint8 v, bytes32 r, bytes32 s, uint8 revocationReasonId) {
Signature memory tempSignature = signatureStorage[_key];
if (tempSignature.isValue) {
return(tempSignature.v, tempSignature.r, tempSignature.s, tempSignature.revocationReasonId);
} else {
return(0, bytes32(0), bytes32(0), 0);
}
}
function setSignature(bytes32 _key, uint8 _v, bytes32 _r, bytes32 _s, uint8 _revocationReasonId) accessible external {
require(ecrecover(_key, _v, _r, _s) != 0x0);
Signature memory tempSignature = Signature({
v: _v,
r: _r,
s: _s,
revocationReasonId: _revocationReasonId,
isValue: true
});
signatureStorage[_key] = tempSignature;
}
function deleteSignature(bytes32 _key) accessible external {
require(signatureStorage[_key].isValue);
Signature memory tempSignature = Signature({
v: 0,
r: bytes32(0),
s: bytes32(0),
revocationReasonId: 0,
isValue: false
});
signatureStorage[_key] = tempSignature;
}
/**** Get Methods for additional storage ****/
function getAddress(bytes32 _key) external view returns (address) {
return addressStorage[_key];
}
function getUint(bytes32 _key) external view returns (uint) {
return uIntStorage[_key];
}
function getString(bytes32 _key) external view returns (string) {
return stringStorage[_key];
}
function getBytes(bytes32 _key) external view returns (bytes) {
return bytesStorage[_key];
}
function getBool(bytes32 _key) external view returns (bool) {
return boolStorage[_key];
}
function getInt(bytes32 _key) external view returns (int) {
return intStorage[_key];
}
/**** Set Methods for additional storage ****/
function setAddress(bytes32 _key, address _value) accessible external {
addressStorage[_key] = _value;
}
function setUint(bytes32 _key, uint _value) accessible external {
uIntStorage[_key] = _value;
}
function setString(bytes32 _key, string _value) accessible external {
stringStorage[_key] = _value;
}
function setBytes(bytes32 _key, bytes _value) accessible external {
bytesStorage[_key] = _value;
}
function setBool(bytes32 _key, bool _value) accessible external {
boolStorage[_key] = _value;
}
function setInt(bytes32 _key, int _value) accessible external {
intStorage[_key] = _value;
}
/**** Delete Methods for additional storage ****/
function deleteAddress(bytes32 _key) accessible external {
delete addressStorage[_key];
}
function deleteUint(bytes32 _key) accessible external {
delete uIntStorage[_key];
}
function deleteString(bytes32 _key) accessible external {
delete stringStorage[_key];
}
function deleteBytes(bytes32 _key) accessible external {
delete bytesStorage[_key];
}
function deleteBool(bytes32 _key) accessible external {
delete boolStorage[_key];
}
function deleteInt(bytes32 _key) accessible external {
delete intStorage[_key];
}
}
contract TrueProfileLogic is Accessible {
/** Logic Contract (updatable) **
* Copyright 2019
* Florian Weigand
* Synalytix UG, Munich
* florian(at)synalytix.de
*/
TrueProfileStorage trueProfileStorage;
function TrueProfileLogic(address _trueProfileStorage) public {
trueProfileStorage = TrueProfileStorage(_trueProfileStorage);
}
/**** Signature logic methods ****/
// add or update TrueProof
// if not present add to array
// if present the old TrueProof can be replaced with a new TrueProof
function addTrueProof(bytes32 _key, uint8 _v, bytes32 _r, bytes32 _s) accessible external {
require(accessAllowed[ecrecover(_key, _v, _r, _s)]);
// the certifcate is valid, so set the revokationReasonId to 0
uint8 revokationReasonId = 0;
trueProfileStorage.setSignature(_key, _v, _r, _s, revokationReasonId);
}
// if the TrueProof was issued by error it can be revoked
// for revocation a reason id needs to be given
function revokeTrueProof(bytes32 _key, uint8 _revocationReasonId) accessible external {
require(_revocationReasonId != 0);
uint8 v;
bytes32 r;
bytes32 s;
uint8 oldRevocationReasonId;
(v, r, s, oldRevocationReasonId) = trueProfileStorage.getSignature(_key);
require(v != 0);
// set the revokation reason id to the new value
trueProfileStorage.setSignature(_key, v, r, s, _revocationReasonId);
}
function isValidTrueProof(bytes32 _key) external view returns (bool) {
// needs to be not revoked AND needs to have a valid signature
if (this.isValidSignatureTrueProof(_key) && this.isNotRevokedTrueProof(_key)) {
return true;
} else {
return false;
}
}
function isValidSignatureTrueProof(bytes32 _key) external view returns (bool) {
uint8 v;
bytes32 r;
bytes32 s;
uint8 revocationReasonId;
(v, r, s, revocationReasonId) = trueProfileStorage.getSignature(_key);
// needs to have a valid signature
if (accessAllowed[ecrecover(_key, v, r, s)]) {
return true;
} else {
return false;
}
}
function isNotRevokedTrueProof(bytes32 _key) external view returns (bool) {
uint8 v;
bytes32 r;
bytes32 s;
uint8 revocationReasonId;
(v, r, s, revocationReasonId) = trueProfileStorage.getSignature(_key);
// needs to be not revoked
if (revocationReasonId == 0) {
return true;
} else {
return false;
}
}
function getSignature(bytes32 _key) external view returns (uint8 v, bytes32 r, bytes32 s, uint8 revocationReasonId) {
return trueProfileStorage.getSignature(_key);
}
function getRevocationReasonId(bytes32 _key) external view returns (uint8) {
uint8 v;
bytes32 r;
bytes32 s;
uint8 revocationReasonId;
(v, r, s, revocationReasonId) = trueProfileStorage.getSignature(_key);
return revocationReasonId;
}
} | * Access Right Management ** Copyright 2019 Florian Weigand Synalytix UG, Munich florian(at)synalytix.de/ | function Accessible() public {
owner = msg.sender;
}
| 1,785,615 | [
1,
1862,
13009,
13303,
225,
25417,
30562,
3857,
280,
2779,
1660,
360,
464,
16091,
7834,
697,
587,
43,
16,
490,
318,
1354,
1183,
280,
2779,
12,
270,
13,
11982,
7834,
697,
18,
323,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
5016,
1523,
1435,
1071,
288,
203,
3639,
3410,
273,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/43114/0x562BdcEff7aA89936e52E16EB52ABd1770e42cBE/sources/StratX2_Treasury.sol | * @dev Changes the minimum timelock duration for future operations. Emits a {MinDelayChange} event. Requirements: - the caller must be the timelock itself. This can only be achieved by scheduling and later executing an operation where the timelock is the target and the data is the ABI-encoded call to this function./ | function updateMinDelay(uint256 newDelay) external virtual {
require(
msg.sender == address(this),
"TimelockController: caller must be timelock"
);
emit MinDelayChange(minDelay, newDelay);
minDelay = newDelay;
}
| 4,631,776 | [
1,
7173,
326,
5224,
1658,
292,
975,
3734,
364,
3563,
5295,
18,
7377,
1282,
279,
288,
2930,
6763,
3043,
97,
871,
18,
29076,
30,
300,
326,
4894,
1297,
506,
326,
1658,
292,
975,
6174,
18,
1220,
848,
1338,
506,
20186,
2155,
635,
21895,
471,
5137,
11274,
392,
1674,
1625,
326,
1658,
292,
975,
353,
326,
1018,
471,
326,
501,
353,
326,
10336,
45,
17,
10787,
745,
358,
333,
445,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1089,
2930,
6763,
12,
11890,
5034,
394,
6763,
13,
3903,
5024,
288,
203,
3639,
2583,
12,
203,
5411,
1234,
18,
15330,
422,
1758,
12,
2211,
3631,
203,
5411,
315,
10178,
292,
975,
2933,
30,
4894,
1297,
506,
1658,
292,
975,
6,
203,
3639,
11272,
203,
3639,
3626,
5444,
6763,
3043,
12,
1154,
6763,
16,
394,
6763,
1769,
203,
3639,
1131,
6763,
273,
394,
6763,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "./Tag.sol";
contract RealFace is ERC721, ERC721Enumerable, Ownable {
enum SaleState {
Off,
Presale1,
Presale2,
Public
}
struct PresaleData {
uint256 maxMintPerAddress;
uint256 price;
bytes32 merkleroot;
mapping(address => uint256) tokensMintedByAddress;
}
using SafeMath for uint256;
using MerkleProof for bytes32[];
SaleState public saleState;
uint256 public maxSupply;
uint256 public maxMintPerTransaction;
uint256 public price;
PresaleData[] public presaleData;
address public beneficiary;
string public baseURI;
modifier whenPublicSaleStarted() {
require(saleState==SaleState.Public,"Public Sale not active");
_;
}
modifier whenSaleStarted() {
require(
saleState==SaleState.Presale1 ||
saleState==SaleState.Presale2 ||
saleState==SaleState.Public,
"whenSaleStarted: Sale not active"
);
_;
}
modifier whenSaleOff() {
require(
saleState==SaleState.Off,
"whenSaleOff: Sale is active"
);
_;
}
modifier isWhitelistSale(SaleState _saleState) {
require(
_saleState==SaleState.Presale1 ||
_saleState==SaleState.Presale2,
"isWhitelistSale: Parameter must be a valid presale"
);
_;
}
modifier whenMerklerootSet(SaleState _presaleNumber) {
require(presaleData[uint(_presaleNumber)].merkleroot!=0,"whenMerklerootSet: Merkleroot not set for presale");
_;
}
modifier whenAddressOnWhitelist(bytes32[] memory _merkleproof) {
require(MerkleProof.verify(
_merkleproof,
getPresale().merkleroot,
keccak256(abi.encodePacked(msg.sender))
),
"whenAddressOnWhitelist: Not on white list"
);
_;
}
constructor(
address _beneficiary,
string memory _uri
)
ERC721("Real Face", "FACES")
{
price = 0.06 ether;
beneficiary = _beneficiary;
saleState = SaleState.Off;
maxSupply = 7753;
maxMintPerTransaction = 7;
baseURI = _uri;
presaleData.push();
//Presale 1
createPresale(5, 0.04 ether);
//Presale 2
createPresale(3, 0.05 ether);
}
function createPresale(
uint256 _maxMintPerAddress,
uint256 _price
)
private
{
PresaleData storage presale = presaleData.push();
presale.maxMintPerAddress = _maxMintPerAddress;
presale.price = _price;
}
function startPublicSale() external onlyOwner() whenSaleOff(){
saleState = SaleState.Public;
}
function startWhitelistSale(SaleState _presaleNumber) external
whenSaleOff()
isWhitelistSale(_presaleNumber)
whenMerklerootSet(_presaleNumber)
onlyOwner()
{
saleState = _presaleNumber;
}
function stopSale() external whenSaleStarted() onlyOwner() {
saleState = SaleState.Off;
}
function mintPublic(uint256 _numTokens) external payable whenPublicSaleStarted() {
uint256 supply = totalSupply();
require(_numTokens <= maxMintPerTransaction, "mintPublic: Minting too many tokens at once!");
require(supply.add(_numTokens) <= maxSupply, "mintPublic: Not enough Tokens remaining.");
require(_numTokens.mul(price) <= msg.value, "mintPublic: Incorrect amount sent!");
for (uint256 i; i < _numTokens; i++) {
_safeMint(msg.sender, supply.add(1).add(i));
}
}
function mintWhitelist(uint256 _numTokens, bytes32[] calldata _merkleproof) external payable
isWhitelistSale(saleState)
whenMerklerootSet(saleState)
whenAddressOnWhitelist(_merkleproof)
{
uint256 currentSupply = totalSupply();
uint256 numWhitelistTokensByAddress = getPresale().tokensMintedByAddress[msg.sender];
require(numWhitelistTokensByAddress.add(_numTokens) <= getPresale().maxMintPerAddress,"mintWhitelist: Exceeds the number of whitelist mints");
require(currentSupply.add(_numTokens) <= maxSupply, "mintWhitelist: Not enough Tokens remaining in sale.");
require(_numTokens.mul(getPresale().price) <= msg.value, "mintWhitelist: Incorrect amount sent!");
for (uint256 i; i < _numTokens; i++) {
_safeMint(msg.sender, currentSupply.add(1).add(i));
}
getPresale().tokensMintedByAddress[msg.sender] = numWhitelistTokensByAddress.add(_numTokens);
}
function mintReserveTokens(address _to, uint256 _numTokens) public onlyOwner {
require(saleState==SaleState.Off,"mintReserveTokens: Sale must be off to reserve tokens");
require(_to!=address(0),"mintReserveTokens: Cannot mint reserve tokens to the burn address");
uint256 supply = totalSupply();
require(supply.add(_numTokens) <= maxSupply, "mintReserveTokens: Cannot mint more than max supply");
require(_numTokens <= 50,"mintReserveTokens: Gas limit protection");
for (uint256 i; i < _numTokens; i++) {
_safeMint(_to, supply.add(1).add(i));
}
}
function getPresale() private view returns (PresaleData storage) {
return presaleData[uint(saleState)];
}
function setBaseURI(string memory _URI) external onlyOwner {
baseURI = _URI;
}
function setMerkleroot(SaleState _presaleNumber, bytes32 _merkleRoot) public
whenSaleOff()
isWhitelistSale(_presaleNumber)
onlyOwner
{
presaleData[uint(_presaleNumber)].merkleroot = _merkleRoot;
}
function _baseURI() internal view override(ERC721) returns (string memory) {
return baseURI;
}
function withdraw() public {
uint256 balance = address(this).balance;
require(payable(beneficiary).send(balance));
}
function tokensInWallet(address _owner) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokensId = new uint256[](tokenCount);
for(uint256 i; i < tokenCount; i++){
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;
// ---------------[ ]---------------
// -------[ ]-------------[ ]-------
// ---------------------------------
// ----[ ]--------[ ]--------[ ]----
// ---------------------------------
// -------[ ]-------------[ ]-------
// ---------------[ ]---------------
// SPDX-License-Identifier: MIT
// 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;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
} | * @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 {
pragma solidity ^0.8.12;
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);
}
}
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);
}
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
| 1,526,256 | [
1,
24114,
1879,
348,
7953,
560,
1807,
30828,
5295,
18,
5219,
30,
1375,
9890,
10477,
68,
353,
19190,
486,
3577,
5023,
598,
348,
7953,
560,
374,
18,
28,
16,
3241,
326,
5274,
2037,
711,
6650,
316,
9391,
6728,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
12083,
14060,
10477,
288,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
2138,
31,
203,
203,
203,
203,
565,
445,
775,
986,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
6430,
16,
2254,
5034,
13,
288,
203,
3639,
22893,
288,
203,
5411,
2254,
5034,
276,
273,
279,
397,
324,
31,
203,
5411,
309,
261,
71,
411,
279,
13,
327,
261,
5743,
16,
374,
1769,
203,
5411,
327,
261,
3767,
16,
276,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
775,
986,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
6430,
16,
2254,
5034,
13,
288,
203,
3639,
22893,
288,
203,
5411,
2254,
5034,
276,
273,
279,
397,
324,
31,
203,
5411,
309,
261,
71,
411,
279,
13,
327,
261,
5743,
16,
374,
1769,
203,
5411,
327,
261,
3767,
16,
276,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
775,
1676,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
6430,
16,
2254,
5034,
13,
288,
203,
3639,
22893,
288,
203,
5411,
309,
261,
70,
405,
279,
13,
327,
261,
5743,
16,
374,
1769,
203,
5411,
327,
261,
3767,
16,
279,
300,
324,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
775,
1676,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
6430,
16,
2254,
5034,
13,
288,
203,
3639,
22893,
288,
203,
5411,
309,
261,
70,
405,
279,
13,
327,
261,
5743,
16,
374,
1769,
2
]
|
pragma solidity ^0.4.20;
contract HouseHolding {
address owner = msg.sender; // админ
uint top = 0; // счетчик ид для добавления домов
struct HouseInfo {
address owner; // владелец
bool inPledge; // в залоге или нет
uint area; // площадь
bool isResidetial; // жилой или нет
uint date; // начало последнего использования
}
mapping(uint => HouseInfo) all_houses; // global id => основная информация о доме
mapping(address => uint[]) my_houses; // владелец => список global id его домов
// создание объекта недвижимости(админ)
function addHouse(address _owner, uint _area, bool _isResidential, uint _data) public {
require(
msg.sender == owner,
"only admin can add"
);
HouseInfo memory t = HouseInfo(_owner, false, _area, _isResidential, _data);
all_houses[top] = t;
my_houses[_owner].push(top);
++top;
}
//Просмотр данных об объекте недвижимости по его global id(все)
function get_house_info(uint id) public constant returns
(address, bool, uint, bool, uint) {
HouseInfo memory t = all_houses[id];
return (t.owner, t.inPledge, t.area, t.isResidetial, t.date);
}
//доп. информация о продающимся доме
struct SaleInfo {
uint id; // global id
uint price; // цена
uint time; // срок действия предложения
}
mapping(address => uint[]) my_houses_in_sale; // address => список global id моих продающихся домов
SaleInfo[] all_houses_in_sale; // список всех продающихся домов
// информация о предложении между 2мя пользователями
struct OfferInfo {
address b; // вторая сторона
uint id; // global id
}
mapping(address => OfferInfo[]) offer_for_sale_for_me; // address => список предложений, чтобы купить у address
mapping(address => OfferInfo[]) offer_for_sale_from_me; // address => список предложений address, чтобы купить у другого
// создать предложение о продаже(собственник)
function create_offer_for_sale
(uint my_house_id, uint price, uint time) public {
require(
msg.sender == all_houses[my_houses[msg.sender][my_house_id] ].owner,
"You don't own that house"
);
for(uint i = 0; i < my_houses_in_sale[msg.sender].length; ++i) { // проверка что такой дом уже не продается
if(my_houses[msg.sender][my_house_id] == my_houses_in_sale[msg.sender][i]) {
return;
}
}
SaleInfo memory t = SaleInfo(my_houses[msg.sender][my_house_id], price, time);
all_houses_in_sale.push(t);
my_houses_in_sale[msg.sender].push(my_houses[msg.sender][my_house_id]); // push global id
/* to do list
* не должен быть в предложении на подарок(убрать предложение)
* (мб)такой ид моего дома должен существовать */
}
// // удалить предложение о продаже
// function delete_offer_for_sale(uint my_house_in_sale_id) public {
// require(
// all_houses[my_houses_in_sale[msg.sender][my_house_in_sale_id] ].owner == msg.sender,
// "You don't own that house"
// );
// uint gID = my_houses_in_sale[msg.sender][my_house_in_sale_id]; // получение глобального ид дома
// for(uint q = 0; q < offer_for_sale_for_me[msg.sender].length; ++q) { /* удалить предложения о покупке */
// if(gID == offer_for_sale_for_me[msg.sender][q].id) {
// address r = offer_for_sale_for_me[msg.sender][q].b;
// for(uint w = 0; w < offer_for_sale_from_me[r].length; ++w) {
// if(gID == offer_for_sale_from_me[r][w].id) {
// delete offer_for_sale_from_me[r];
// uint[] memory arr = new uint[](offer_for_sale_from_me[r].length - 1);
// offer_for_sale_from_me[r] = arr;
// }
// }
// delete offer_for_sale_for_me[msg.sender][q];
// if(offer_for_sale_for_me[msg.sender].length != 0 && q != offer_for_sale_for_me[r].length - 1) {
// offer_for_sale_for_me[msg.sender][q] = offer_for_sale_for_me[msg.sender][offer_for_sale_for_me[msg.sender].length - 1];
// delete offer_for_sale_for_me[msg.sender][offer_for_sale_for_me[msg.sender].length - 1];
// --q;
// }
// }
// }
// /* to do list
// * возврат денег с контракта, желающим купить
// * (мб)такой ид моего продающегося дома должен существовать */
// delete my_houses_in_sale[msg.sender][my_house_in_sale_id];
// if(my_houses_in_sale[msg.sender].length != 0 && my_house_in_sale_id != my_houses_in_sale[msg.sender].length - 1) {
// my_houses_in_sale[msg.sender][my_house_in_sale_id] = my_houses_in_sale[msg.sender][my_houses_in_sale[msg.sender].length - 1];
// delete my_houses_in_sale[msg.sender][my_houses_in_sale[msg.sender].length - 1];
// }
// for(uint i = 0; i < all_houses_in_sale.length; ++i) {
// if(gID == all_houses_in_sale[i].id) {
// delete all_houses_in_sale[i];
// if(all_houses_in_sale.length != 0 && i != all_houses_in_sale.length - 1) {
// all_houses_in_sale[i] = all_houses_in_sale[all_houses_in_sale.length - 1];
// delete all_houses_in_sale[all_houses_in_sale.length - 1];
// }
// break;
// }
// }
// }
// сделать запрос на покупку
function make_offer_to_buy(uint id) public payable{ // ид из всех продающихся домов
require(
msg.value == all_houses_in_sale[id].price,
"Not enought money"
);
uint gID = all_houses_in_sale[id].id;
offer_for_sale_from_me[msg.sender].push(OfferInfo(all_houses[gID].owner, gID)); // add в список предложений от меня (стоимость можно будет взять из списка домов, которые продает овнер и найти тот самый)
offer_for_sale_for_me[all_houses[gID].owner].push(OfferInfo(msg.sender, gID)); // add в список предложений для владельца
/* to do list
* (мб)срок действия обьявления не истек */
}
// --->> Список моих "покупок", ожидающих подтверждения
// количество "покупок", ожидающих подтверждения
function get_count_of_offer_to_buy_from_me() public constant returns (uint) {
return offer_for_sale_from_me[msg.sender].length;
}
// информация об "покупке" ожидающей подтверждения по ее ид в списке моих покупок, ожидающих подтверждения
function get_offer_to_buy_from_me_info(uint id) public constant returns (address, bool, uint, bool, uint) {
HouseInfo memory t = all_houses[offer_for_sale_from_me[msg.sender][id].id];
return (t.owner, t.inPledge, t.area, t.isResidetial, t.date);
}
// <<--- Список моих "покупок", ожидающих подтверждения
// принять запрос на покупку
// function accept_offer_to_sell(uint id) public { // ид из offer_for_sale_for_me
// /* только овнер может принимать предложения о продаже своих домов */
// /* овнеру переводятся требуемые деньги со смарт контракта */
// address buyer = offer_for_sale_for_me[msg.sender][id].b;
// uint gID = offer_for_sale_for_me[msg.sender][id].id;
// delete offer_for_sale_for_me[msg.sender][id];
// for(uint s = 0; s < offer_for_sale_for_me[msg.sender][id]) {
// }
// for(uint i = 0; i < my_houses_in_sale[msg.sender].length; ++i) {
// if(gID == my_houses_in_sale[msg.sender][i]) {
// delete_offer_for_sale(i);
// break;
// }
// }
// for(uint j = 0; j < my_houses[msg.sender].length; ++j) {
// if(gID == my_houses[msg.sender][j]) {
// delete my_houses[msg.sender][j];
// if(my_houses[msg.sender].length != 0) {
// my_houses[msg.sender][j] = my_houses[msg.sender][my_houses[msg.sender].length - 1];
// delete my_houses[msg.sender][my_houses[msg.sender].length - 1];
// }
// break;
// }
// }
// all_houses[gID].owner = offer_for_sale_for_me[msg.sender][id].b;
// all_houses[gID].date = now;
// my_houses[offer_for_sale_for_me[msg.sender][id].b].push(gID);
// }
// --->> Просмотр всех предложений о продаже
// количество всех предложени о продаже
function get_count_of_saling_houses() public constant returns(uint) {
return all_houses_in_sale.length;
}
// информация о продающемся доме по его ид в списке всех продающихся домов
function get_saling_house_info(uint id) public constant returns(address, uint, bool, bool, uint, uint, uint) { // ид в списке всех продающихся домов
HouseInfo memory t = all_houses[all_houses_in_sale[id].id];
return (t.owner, t.area, t.inPledge, t.isResidetial, t.date, all_houses_in_sale[id].price, all_houses_in_sale[id].time);
}
// <<--- Просмотр всех предложений о продаже
// --->> Все мои объекты недвижимости
// количество моих домов
function get_count_of_my_houses() public constant returns (uint) {
return my_houses[msg.sender].length;
}
// информация о моем доме по его ид в списке моих домов
function get_my_house_info(uint id) public constant returns (address, bool, uint, bool, uint) {
HouseInfo memory t = all_houses[my_houses[msg.sender][id]];
return (t.owner, t.inPledge, t.area, t.isResidetial, t.date);
}
// <<--- Все мои объекты недвижимости
// --->> Всех мои предложения о продаже
// количество моих продающихся домов
function get_count_of_my_saling_houses() public constant returns(uint) {
return my_houses_in_sale[msg.sender].length;
}
// информация о моем продающемся доме по его ид из списка моих продающихся домов
function get_my_saling_house_info(uint id) public constant returns (address, bool, uint, bool, uint) {
HouseInfo memory t = all_houses[my_houses_in_sale[msg.sender][id]];
return (t.owner, t.inPledge, t.area, t.isResidetial, t.date);
}
// << --- Всех мои предложения о продаже
mapping(address => uint[]) my_houses_in_offer_to_pledge; // address => предложения о залоге от address
SaleInfo[] all_houses_in_offer_to_pledge; // Все предложения о залоге
// Создание предложения о залоге(собственник)
function create_offer_for_pledge(uint id, uint price, uint time) public {
uint gID = my_houses[msg.sender][id];
SaleInfo memory o = SaleInfo(gID, price, time);
all_houses_in_offer_to_pledge.push(o);
my_houses_in_offer_to_pledge[msg.sender].push(gID);
}
// --->> Всех мои предложения о залоге
// Количество моих предложений о залоге
function get_count_of_my_house_to_pledge() public constant returns (uint) {
return my_houses_in_offer_to_pledge[msg.sender].length;
}
// Информация о доме, который я предлагаю взять в залог по его ид из списка моих предложений о залоге
function get_my_house_to_pledge_info(uint id) public constant returns (address, uint, bool, uint) {
HouseInfo memory h = all_houses[my_houses_in_offer_to_pledge[msg.sender][id]];
return (h.owner, h.area, h.isResidetial, h.date);
}
// <<--- Всех мои предложения о залоге
// --->> Просмотр предложений о залоге(все)
// количество всех предложений о залоге
function get_count_of_houses_to_pledge() public constant returns (uint) {
return all_houses_in_offer_to_pledge.length;
}
// информация о предложении о залоге по его ид в списке всех предложений о залоге
function get_house_to_pledge_info(uint id) public constant returns (address, uint, bool, uint) {
HouseInfo memory h = all_houses[all_houses_in_offer_to_pledge[id].id];
return (h.owner, h.area, h.isResidetial, h.date);
}
// <<--- Просмотр предложений о залоге(все)
}
| --->> Список моих "покупок", ожидающих подтверждения количество "покупок", ожидающих подтверждения | function get_count_of_offer_to_buy_from_me() public constant returns (uint) {
return offer_for_sale_from_me[msg.sender].length;
}
require(
}
}
| 15,791,019 | [
1,
413,
2122,
34,
225,
145,
99,
145,
128,
145,
121,
146,
228,
145,
127,
145,
123,
225,
145,
125,
145,
127,
145,
121,
146,
232,
315,
145,
128,
145,
127,
145,
123,
146,
230,
145,
128,
145,
127,
145,
123,
3113,
225,
145,
127,
145,
119,
145,
121,
145,
117,
145,
113,
146,
241,
146,
236,
145,
121,
146,
232,
225,
145,
128,
145,
127,
145,
117,
146,
229,
145,
115,
145,
118,
146,
227,
145,
119,
145,
117,
145,
118,
145,
126,
145,
121,
146,
242,
225,
145,
123,
145,
127,
145,
124,
145,
121,
146,
234,
145,
118,
146,
228,
146,
229,
145,
115,
145,
127,
315,
145,
128,
145,
127,
145,
123,
146,
230,
145,
128,
145,
127,
145,
123,
3113,
225,
145,
127,
145,
119,
145,
121,
145,
117,
145,
113,
146,
241,
146,
236,
145,
121,
146,
232,
225,
145,
128,
145,
127,
2
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
]
| [
1,
565,
445,
336,
67,
1883,
67,
792,
67,
23322,
67,
869,
67,
70,
9835,
67,
2080,
67,
3501,
1435,
1071,
5381,
1135,
261,
11890,
13,
288,
203,
3639,
327,
10067,
67,
1884,
67,
87,
5349,
67,
2080,
67,
3501,
63,
3576,
18,
15330,
8009,
2469,
31,
203,
565,
289,
203,
540,
203,
377,
203,
3639,
2583,
12,
203,
565,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.24;
interface itoken {
function freezeAccount(address _target, bool _freeze) external;
function freezeAccountPartialy(address _target, uint256 _value) external;
function balanceOf(address _owner) external view returns (uint256 balance);
// function totalSupply() external view returns (uint256);
// function transferOwnership(address newOwner) external;
function allowance(address _owner, address _spender) external view returns (uint256);
function initialCongress(address _congress) external;
function mint(address _to, uint256 _amount) external returns (bool);
function finishMinting() external returns (bool);
function pause() external;
function unpause() external;
}
library StringUtils {
/// @dev Does a byte-by-byte lexicographical comparison of two strings.
/// @return a negative number if `_a` is smaller, zero if they are equal
/// and a positive numbe if `_b` is smaller.
function compare(string _a, string _b) public pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
//@todo unroll the loop into increments of 32 and do full 32 byte comparisons
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
/// @dev Compares two strings and returns true iff they are equal.
function equal(string _a, string _b) public pure returns (bool) {
return compare(_a, _b) == 0;
}
/// @dev Finds the index of the first occurrence of _needle in _haystack
function indexOf(string _haystack, string _needle) public pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1)) // since we have to be able to return -1 (if the char isn't found or input error), this function must return an "int" type with a max length of (2^128 - 1)
return -1;
else {
uint subindex = 0;
for (uint i = 0; i < h.length; i ++) {
if (h[i] == n[0]) { // found the first char of b
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) {// search until the chars don't match or until we reach the end of a or b
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
}
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;
}
}
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;
}
}
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
contract DelayedClaimable is Claimable {
uint256 public end;
uint256 public start;
/**
* @dev Used to specify the time period during which a pending
* owner can claim ownership.
* @param _start The earliest time ownership can be claimed.
* @param _end The latest time ownership can be claimed.
*/
function setLimits(uint256 _start, uint256 _end) onlyOwner public {
require(_start <= _end);
end = _end;
start = _start;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer, as long as it is called within
* the specified start and end time.
*/
function claimOwnership() onlyPendingOwner public {
require((block.number <= end) && (block.number >= start));
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
end = 0;
}
}
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);
/**
* @dev reverts if addr does not have role
* @param addr address
* @param roleName the name of the role
* // reverts
*/
function checkRole(address addr, string 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 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 addRole(address addr, string 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 roleName)
internal
{
roles[roleName].remove(addr);
emit RoleRemoved(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 roleName)
{
checkRole(msg.sender, roleName);
_;
}
/**
* @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);
// _;
// }
}
contract MultiOwners is DelayedClaimable, RBAC {
using SafeMath for uint256;
using StringUtils for string;
mapping (string => uint256) private authorizations;
mapping (address => string) private ownerOfSides;
// mapping (string => mapping (string => bool)) private voteResults;
mapping (string => uint256) private sideExist;
mapping (string => mapping (string => address[])) private sideVoters;
address[] public owners;
string[] private authTypes;
// string[] private ownerSides;
uint256 public multiOwnerSides;
uint256 ownerSidesLimit = 5;
// uint256 authRate = 75;
bool initAdd = true;
event OwnerAdded(address addr, string side);
event OwnerRemoved(address addr);
event InitialFinished();
string public constant ROLE_MULTIOWNER = "multiOwner";
string public constant AUTH_ADDOWNER = "addOwner";
string public constant AUTH_REMOVEOWNER = "removeOwner";
// string public constant AUTH_SETAUTHRATE = "setAuthRate";
/**
* @dev Throws if called by any account that's not multiOwners.
*/
modifier onlyMultiOwners() {
checkRole(msg.sender, ROLE_MULTIOWNER);
_;
}
/**
* @dev Throws if not in initializing stage.
*/
modifier canInitial() {
require(initAdd);
_;
}
/**
* @dev the msg.sender will authorize a type of event.
* @param _authType the event type need to be authorized
*/
function authorize(string _authType) onlyMultiOwners public {
string memory side = ownerOfSides[msg.sender];
address[] storage voters = sideVoters[side][_authType];
if (voters.length == 0) {
// if the first time to authorize this type of event
authorizations[_authType] = authorizations[_authType].add(1);
// voteResults[side][_authType] = true;
}
// add voters of one side
uint j = 0;
for (; j < voters.length; j = j.add(1)) {
if (voters[j] == msg.sender) {
break;
}
}
if (j >= voters.length) {
voters.push(msg.sender);
}
// add the authType for clearing auth
uint i = 0;
for (; i < authTypes.length; i = i.add(1)) {
if (authTypes[i].equal(_authType)) {
break;
}
}
if (i >= authTypes.length) {
authTypes.push(_authType);
}
}
/**
* @dev the msg.sender will clear the authorization he has given for the event.
* @param _authType the event type need to be authorized
*/
function deAuthorize(string _authType) onlyMultiOwners public {
string memory side = ownerOfSides[msg.sender];
address[] storage voters = sideVoters[side][_authType];
for (uint j = 0; j < voters.length; j = j.add(1)) {
if (voters[j] == msg.sender) {
delete voters[j];
break;
}
}
// if the sender has authorized this type of event, will remove its vote
if (j < voters.length) {
for (uint jj = j; jj < voters.length.sub(1); jj = jj.add(1)) {
voters[jj] = voters[jj.add(1)];
}
delete voters[voters.length.sub(1)];
voters.length = voters.length.sub(1);
// if there is no votes of one side, the authorization need to be decreased
if (voters.length == 0) {
authorizations[_authType] = authorizations[_authType].sub(1);
// voteResults[side][_authType] = true;
}
// if there is no authorization on this type of event,
// this event need to be removed from the list
if (authorizations[_authType] == 0) {
for (uint i = 0; i < authTypes.length; i = i.add(1)) {
if (authTypes[i].equal(_authType)) {
delete authTypes[i];
break;
}
}
for (uint ii = i; ii < authTypes.length.sub(1); ii = ii.add(1)) {
authTypes[ii] = authTypes[ii.add(1)];
}
delete authTypes[authTypes.length.sub(1)];
authTypes.length = authTypes.length.sub(1);
}
}
}
/**
* @dev judge if the event has already been authorized.
* @param _authType the event type need to be authorized
*/
function hasAuth(string _authType) public view returns (bool) {
require(multiOwnerSides > 1); // at least 2 sides have authorized
// uint256 rate = authorizations[_authType].mul(100).div(multiOwnerNumber)
return (authorizations[_authType] == multiOwnerSides);
}
/**
* @dev clear all the authorizations that have been given for a type of event.
* @param _authType the event type need to be authorized
*/
function clearAuth(string _authType) internal {
authorizations[_authType] = 0; // clear authorizations
for (uint i = 0; i < owners.length; i = i.add(1)) {
string memory side = ownerOfSides[owners[i]];
address[] storage voters = sideVoters[side][_authType];
for (uint j = 0; j < voters.length; j = j.add(1)) {
delete voters[j]; // clear votes of one side
}
voters.length = 0;
}
// clear this type of event
for (uint k = 0; k < authTypes.length; k = k.add(1)) {
if (authTypes[k].equal(_authType)) {
delete authTypes[k];
break;
}
}
for (uint kk = k; kk < authTypes.length.sub(1); kk = kk.add(1)) {
authTypes[kk] = authTypes[kk.add(1)];
}
delete authTypes[authTypes.length.sub(1)];
authTypes.length = authTypes.length.sub(1);
}
/**
* @dev add an address as one of the multiOwners.
* @param _addr the account address used as a multiOwner
*/
function addAddress(address _addr, string _side) internal {
require(multiOwnerSides < ownerSidesLimit);
require(_addr != address(0));
require(ownerOfSides[_addr].equal("")); // not allow duplicated adding
// uint i = 0;
// for (; i < owners.length; i = i.add(1)) {
// if (owners[i] == _addr) {
// break;
// }
// }
// if (i >= owners.length) {
owners.push(_addr); // for not allowing duplicated adding, so each addr should be new
addRole(_addr, ROLE_MULTIOWNER);
ownerOfSides[_addr] = _side;
// }
if (sideExist[_side] == 0) {
multiOwnerSides = multiOwnerSides.add(1);
}
sideExist[_side] = sideExist[_side].add(1);
}
/**
* @dev add an address to the whitelist
* @param _addr address will be one of the multiOwner
* @param _side the side name of the multiOwner
* @return true if the address was added to the multiOwners list,
* false if the address was already in the multiOwners list
*/
function initAddressAsMultiOwner(address _addr, string _side)
onlyOwner
canInitial
public
{
// require(initAdd);
addAddress(_addr, _side);
// initAdd = false;
emit OwnerAdded(_addr, _side);
}
/**
* @dev Function to stop initial stage.
*/
function finishInitOwners() onlyOwner canInitial public {
initAdd = false;
emit InitialFinished();
}
/**
* @dev add an address to the whitelist
* @param _addr address
* @param _side the side name of the multiOwner
* @return true if the address was added to the multiOwners list,
* false if the address was already in the multiOwners list
*/
function addAddressAsMultiOwner(address _addr, string _side)
onlyMultiOwners
public
{
require(hasAuth(AUTH_ADDOWNER));
addAddress(_addr, _side);
clearAuth(AUTH_ADDOWNER);
emit OwnerAdded(_addr, _side);
}
/**
* @dev getter to determine if address is in multiOwner list
*/
function isMultiOwner(address _addr)
public
view
returns (bool)
{
return hasRole(_addr, ROLE_MULTIOWNER);
}
/**
* @dev remove an address from the whitelist
* @param _addr address
* @return true if the address was removed from the multiOwner list,
* false if the address wasn't in the multiOwner list
*/
function removeAddressFromOwners(address _addr)
onlyMultiOwners
public
{
require(hasAuth(AUTH_REMOVEOWNER));
removeRole(_addr, ROLE_MULTIOWNER);
// first remove the owner
uint j = 0;
for (; j < owners.length; j = j.add(1)) {
if (owners[j] == _addr) {
delete owners[j];
break;
}
}
if (j < owners.length) {
for (uint jj = j; jj < owners.length.sub(1); jj = jj.add(1)) {
owners[jj] = owners[jj.add(1)];
}
delete owners[owners.length.sub(1)];
owners.length = owners.length.sub(1);
}
string memory side = ownerOfSides[_addr];
// if (sideExist[side] > 0) {
sideExist[side] = sideExist[side].sub(1);
if (sideExist[side] == 0) {
require(multiOwnerSides > 2); // not allow only left 1 side
multiOwnerSides = multiOwnerSides.sub(1); // this side has been removed
}
// for every event type, if this owner has voted the event, then need to remove
for (uint i = 0; i < authTypes.length; ) {
address[] storage voters = sideVoters[side][authTypes[i]];
for (uint m = 0; m < voters.length; m = m.add(1)) {
if (voters[m] == _addr) {
delete voters[m];
break;
}
}
if (m < voters.length) {
for (uint n = m; n < voters.length.sub(1); n = n.add(1)) {
voters[n] = voters[n.add(1)];
}
delete voters[voters.length.sub(1)];
voters.length = voters.length.sub(1);
// if this side only have this 1 voter, the authorization of this event need to be decreased
if (voters.length == 0) {
authorizations[authTypes[i]] = authorizations[authTypes[i]].sub(1);
}
// if there is no authorization of this event, the event need to be removed
if (authorizations[authTypes[i]] == 0) {
delete authTypes[i];
for (uint kk = i; kk < authTypes.length.sub(1); kk = kk.add(1)) {
authTypes[kk] = authTypes[kk.add(1)];
}
delete authTypes[authTypes.length.sub(1)];
authTypes.length = authTypes.length.sub(1);
} else {
i = i.add(1);
}
} else {
i = i.add(1);
}
}
// }
delete ownerOfSides[_addr];
clearAuth(AUTH_REMOVEOWNER);
emit OwnerRemoved(_addr);
}
}
contract MultiOwnerContract is MultiOwners {
Claimable public ownedContract;
address public pendingOwnedOwner;
// address internal origOwner;
string public constant AUTH_CHANGEOWNEDOWNER = "transferOwnerOfOwnedContract";
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
// modifier onlyPendingOwnedOwner() {
// require(msg.sender == pendingOwnedOwner);
// _;
// }
/**
* @dev bind a contract as its owner
*
* @param _contract the contract address that will be binded by this Owner Contract
*/
function bindContract(address _contract) onlyOwner public returns (bool) {
require(_contract != address(0));
ownedContract = Claimable(_contract);
// origOwner = ownedContract.owner();
// take ownership of the owned contract
ownedContract.claimOwnership();
return true;
}
/**
* @dev change the owner of the contract from this contract address to the original one.
*
*/
// function transferOwnershipBack() onlyOwner public {
// ownedContract.transferOwnership(origOwner);
// ownedContract = Claimable(address(0));
// origOwner = address(0);
// }
/**
* @dev change the owner of the contract from this contract address to another one.
*
* @param _nextOwner the contract address that will be next Owner of the original Contract
*/
function changeOwnedOwnershipto(address _nextOwner) onlyMultiOwners public {
require(ownedContract != address(0));
require(hasAuth(AUTH_CHANGEOWNEDOWNER));
if (ownedContract.owner() != pendingOwnedOwner) {
ownedContract.transferOwnership(_nextOwner);
pendingOwnedOwner = _nextOwner;
// ownedContract = Claimable(address(0));
// origOwner = address(0);
} else {
// the pending owner has already taken the ownership
ownedContract = Claimable(address(0));
pendingOwnedOwner = address(0);
}
clearAuth(AUTH_CHANGEOWNEDOWNER);
}
function ownedOwnershipTransferred() onlyOwner public returns (bool) {
require(ownedContract != address(0));
if (ownedContract.owner() == pendingOwnedOwner) {
// the pending owner has already taken the ownership
ownedContract = Claimable(address(0));
pendingOwnedOwner = address(0);
return true;
} else {
return false;
}
}
}
contract DRCTOwner is MultiOwnerContract {
string public constant AUTH_INITCONGRESS = "initCongress";
string public constant AUTH_CANMINT = "canMint";
string public constant AUTH_SETMINTAMOUNT = "setMintAmount";
string public constant AUTH_FREEZEACCOUNT = "freezeAccount";
bool congressInit = false;
// bool paramsInit = false;
// iParams public params;
uint256 onceMintAmount;
// function initParams(address _params) onlyOwner public {
// require(!paramsInit);
// require(_params != address(0));
// params = _params;
// paramsInit = false;
// }
/**
* @dev Function to set mint token amount
* @param _value The mint value.
*/
function setOnceMintAmount(uint256 _value) onlyMultiOwners public {
require(hasAuth(AUTH_SETMINTAMOUNT));
require(_value > 0);
onceMintAmount = _value;
clearAuth(AUTH_SETMINTAMOUNT);
}
/**
* @dev change the owner of the contract from this contract address to another one.
*
* @param _congress the contract address that will be next Owner of the original Contract
*/
function initCongress(address _congress) onlyMultiOwners public {
require(hasAuth(AUTH_INITCONGRESS));
require(!congressInit);
itoken tk = itoken(address(ownedContract));
tk.initialCongress(_congress);
clearAuth(AUTH_INITCONGRESS);
congressInit = true;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to) onlyMultiOwners public returns (bool) {
require(hasAuth(AUTH_CANMINT));
itoken tk = itoken(address(ownedContract));
bool res = tk.mint(_to, onceMintAmount);
clearAuth(AUTH_CANMINT);
return res;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyMultiOwners public returns (bool) {
require(hasAuth(AUTH_CANMINT));
itoken tk = itoken(address(ownedContract));
bool res = tk.finishMinting();
clearAuth(AUTH_CANMINT);
return res;
}
/**
* @dev freeze the account's balance under urgent situation
*
* by default all the accounts will not be frozen until set freeze value as true.
*
* @param _target address the account should be frozen
* @param _freeze bool if true, the account will be frozen
*/
function freezeAccountDirect(address _target, bool _freeze) onlyMultiOwners public {
require(hasAuth(AUTH_FREEZEACCOUNT));
require(_target != address(0));
itoken tk = itoken(address(ownedContract));
tk.freezeAccount(_target, _freeze);
clearAuth(AUTH_FREEZEACCOUNT);
}
/**
* @dev freeze the account's balance
*
* by default all the accounts will not be frozen until set freeze value as true.
*
* @param _target address the account should be frozen
* @param _freeze bool if true, the account will be frozen
*/
function freezeAccount(address _target, bool _freeze) onlyOwner public {
require(_target != address(0));
itoken tk = itoken(address(ownedContract));
if (_freeze) {
require(tk.allowance(_target, this) == tk.balanceOf(_target));
}
tk.freezeAccount(_target, _freeze);
}
/**
* @dev freeze the account's balance
*
* @param _target address the account should be frozen
* @param _value uint256 the amount of tokens that will be frozen
*/
function freezeAccountPartialy(address _target, uint256 _value) onlyOwner public {
require(_target != address(0));
itoken tk = itoken(address(ownedContract));
require(tk.allowance(_target, this) == _value);
tk.freezeAccountPartialy(_target, _value);
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner public {
itoken tk = itoken(address(ownedContract));
tk.pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner public {
itoken tk = itoken(address(ownedContract));
tk.unpause();
}
}
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];
}
} | * @dev freeze the account's balance by default all the accounts will not be frozen until set freeze value as true. @param _target address the account should be frozen @param _freeze bool if true, the account will be frozen/ | function freezeAccount(address _target, bool _freeze) onlyOwner public {
require(_target != address(0));
itoken tk = itoken(address(ownedContract));
if (_freeze) {
require(tk.allowance(_target, this) == tk.balanceOf(_target));
}
tk.freezeAccount(_target, _freeze);
}
| 1,496,910 | [
1,
29631,
326,
2236,
1807,
11013,
635,
805,
777,
326,
9484,
903,
486,
506,
12810,
3180,
444,
16684,
460,
487,
638,
18,
225,
389,
3299,
1758,
326,
2236,
1410,
506,
12810,
225,
389,
29631,
1426,
309,
638,
16,
326,
2236,
903,
506,
12810,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
16684,
3032,
12,
2867,
389,
3299,
16,
1426,
389,
29631,
13,
1338,
5541,
1071,
288,
203,
3639,
2583,
24899,
3299,
480,
1758,
12,
20,
10019,
203,
3639,
518,
969,
13030,
273,
518,
969,
12,
2867,
12,
995,
329,
8924,
10019,
203,
3639,
309,
261,
67,
29631,
13,
288,
203,
5411,
2583,
12,
16099,
18,
5965,
1359,
24899,
3299,
16,
333,
13,
422,
13030,
18,
12296,
951,
24899,
3299,
10019,
203,
3639,
289,
203,
203,
3639,
13030,
18,
29631,
3032,
24899,
3299,
16,
389,
29631,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
//Address: 0x5301f1ec2f48f86bbd5291dfd7998a3d733a3245
//Contract name: RentAuction
//Balance: 0 Ether
//Verification Date: 1/28/2018
//Transacion Count: 4
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Claimable
* @dev Extension for the Ownable contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract Claimable is Ownable {
address public pendingOwner;
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner public {
pendingOwner = newOwner;
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() onlyPendingOwner public {
OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
/**
* @title Contracts that should be able to recover tokens
* @author SylTi
* @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner.
* This will prevent any accidental loss of tokens.
*/
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param token ERC20Basic The address of the token contract
*/
function reclaimToken(ERC20Basic token) external onlyOwner {
uint256 balance = token.balanceOf(this);
token.safeTransfer(owner, balance);
}
}
/// @title Interface for contracts conforming to ERC-721: Deed Standard
/// @author William Entriken (https://phor.net), et al.
/// @dev Specification at https://github.com/ethereum/EIPs/pull/841 (DRAFT)
interface ERC721 {
// COMPLIANCE WITH ERC-165 (DRAFT) /////////////////////////////////////////
/// @dev ERC-165 (draft) interface signature for itself
// bytes4 internal constant INTERFACE_SIGNATURE_ERC165 = // 0x01ffc9a7
// bytes4(keccak256('supportsInterface(bytes4)'));
/// @dev ERC-165 (draft) interface signature for ERC721
// bytes4 internal constant INTERFACE_SIGNATURE_ERC721 = // 0xda671b9b
// bytes4(keccak256('ownerOf(uint256)')) ^
// bytes4(keccak256('countOfDeeds()')) ^
// bytes4(keccak256('countOfDeedsByOwner(address)')) ^
// bytes4(keccak256('deedOfOwnerByIndex(address,uint256)')) ^
// bytes4(keccak256('approve(address,uint256)')) ^
// bytes4(keccak256('takeOwnership(uint256)'));
/// @notice Query a contract to see if it supports a certain interface
/// @dev Returns `true` the interface is supported and `false` otherwise,
/// returns `true` for INTERFACE_SIGNATURE_ERC165 and
/// INTERFACE_SIGNATURE_ERC721, see ERC-165 for other interface signatures.
function supportsInterface(bytes4 _interfaceID) external pure returns (bool);
// PUBLIC QUERY FUNCTIONS //////////////////////////////////////////////////
/// @notice Find the owner of a deed
/// @param _deedId The identifier for a deed we are inspecting
/// @dev Deeds assigned to zero address are considered destroyed, and
/// queries about them do throw.
/// @return The non-zero address of the owner of deed `_deedId`, or `throw`
/// if deed `_deedId` is not tracked by this contract
function ownerOf(uint256 _deedId) external view returns (address _owner);
/// @notice Count deeds tracked by this contract
/// @return A count of the deeds tracked by this contract, where each one of
/// them has an assigned and queryable owner
function countOfDeeds() public view returns (uint256 _count);
/// @notice Count all deeds assigned to an owner
/// @dev Throws if `_owner` is the zero address, representing destroyed deeds.
/// @param _owner An address where we are interested in deeds owned by them
/// @return The number of deeds owned by `_owner`, possibly zero
function countOfDeedsByOwner(address _owner) public view returns (uint256 _count);
/// @notice Enumerate deeds assigned to an owner
/// @dev Throws if `_index` >= `countOfDeedsByOwner(_owner)` or if
/// `_owner` is the zero address, representing destroyed deeds.
/// @param _owner An address where we are interested in deeds owned by them
/// @param _index A counter between zero and `countOfDeedsByOwner(_owner)`,
/// inclusive
/// @return The identifier for the `_index`th deed assigned to `_owner`,
/// (sort order not specified)
function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _deedId);
// TRANSFER MECHANISM //////////////////////////////////////////////////////
/// @dev This event emits when ownership of any deed changes by any
/// mechanism. This event emits when deeds are created (`from` == 0) and
/// destroyed (`to` == 0). Exception: during contract creation, any
/// transfers may occur without emitting `Transfer`.
event Transfer(address indexed from, address indexed to, uint256 indexed deedId);
/// @dev This event emits on any successful call to
/// `approve(address _spender, uint256 _deedId)`. Exception: does not emit
/// if an owner revokes approval (`_to` == 0x0) on a deed with no existing
/// approval.
event Approval(address indexed owner, address indexed approved, uint256 indexed deedId);
/// @notice Approve a new owner to take your deed, or revoke approval by
/// setting the zero address. You may `approve` any number of times while
/// the deed is assigned to you, only the most recent approval matters.
/// @dev Throws if `msg.sender` does not own deed `_deedId` or if `_to` ==
/// `msg.sender`.
/// @param _deedId The deed you are granting ownership of
function approve(address _to, uint256 _deedId) external;
/// @notice Become owner of a deed for which you are currently approved
/// @dev Throws if `msg.sender` is not approved to become the owner of
/// `deedId` or if `msg.sender` currently owns `_deedId`.
/// @param _deedId The deed that is being transferred
function takeOwnership(uint256 _deedId) external;
// SPEC EXTENSIONS /////////////////////////////////////////////////////////
/// @notice Transfer a deed to a new owner.
/// @dev Throws if `msg.sender` does not own deed `_deedId` or if
/// `_to` == 0x0.
/// @param _to The address of the new owner.
/// @param _deedId The deed you are transferring.
function transfer(address _to, uint256 _deedId) external;
}
/// @title Metadata extension to ERC-721 interface
/// @author William Entriken (https://phor.net)
/// @dev Specification at https://github.com/ethereum/EIPs/pull/841 (DRAFT)
interface ERC721Metadata {
/// @dev ERC-165 (draft) interface signature for ERC721
// bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata = // 0x2a786f11
// bytes4(keccak256('name()')) ^
// bytes4(keccak256('symbol()')) ^
// bytes4(keccak256('deedUri(uint256)'));
/// @notice A descriptive name for a collection of deeds managed by this
/// contract
/// @dev Wallets and exchanges MAY display this to the end user.
function name() public pure returns (string _deedName);
/// @notice An abbreviated name for deeds managed by this contract
/// @dev Wallets and exchanges MAY display this to the end user.
function symbol() public pure returns (string _deedSymbol);
/// @notice A distinct URI (RFC 3986) for a given token.
/// @dev If:
/// * The URI is a URL
/// * The URL is accessible
/// * The URL points to a valid JSON file format (ECMA-404 2nd ed.)
/// * The JSON base element is an object
/// then these names of the base element SHALL have special meaning:
/// * "name": A string identifying the item to which `_deedId` grants
/// ownership
/// * "description": A string detailing the item to which `_deedId` grants
/// ownership
/// * "image": A URI pointing to a file of image/* mime type representing
/// the item to which `_deedId` grants ownership
/// Wallets and exchanges MAY display this to the end user.
/// Consider making any images at a width between 320 and 1080 pixels and
/// aspect ratio between 1.91:1 and 4:5 inclusive.
function deedUri(uint256 _deedId) external pure returns (string _uri);
}
/// @dev Implements access control to the DWorld contract.
contract DWorldAccessControl is Claimable, Pausable, CanReclaimToken {
address public cfoAddress;
function DWorldAccessControl() public {
// The creator of the contract is the initial CFO.
cfoAddress = msg.sender;
}
/// @dev Access modifier for CFO-only functionality.
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current contract owner.
/// @param _newCFO The address of the new CFO.
function setCFO(address _newCFO) external onlyOwner {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
}
/// @dev Defines base data structures for DWorld.
contract DWorldBase is DWorldAccessControl {
using SafeMath for uint256;
/// @dev All minted plots (array of plot identifiers). There are
/// 2^16 * 2^16 possible plots (covering the entire world), thus
/// 32 bits are required. This fits in a uint32. Storing
/// the identifiers as uint32 instead of uint256 makes storage
/// cheaper. (The impact of this in mappings is less noticeable,
/// and using uint32 in the mappings below actually *increases*
/// gas cost for minting).
uint32[] public plots;
mapping (uint256 => address) identifierToOwner;
mapping (uint256 => address) identifierToApproved;
mapping (address => uint256) ownershipDeedCount;
/// @dev Event fired when a plot's data are changed. The plot
/// data are not stored in the contract directly, instead the
/// data are logged to the block. This gives significant
/// reductions in gas requirements (~75k for minting with data
/// instead of ~180k). However, it also means plot data are
/// not available from *within* other contracts.
event SetData(uint256 indexed deedId, string name, string description, string imageUrl, string infoUrl);
/// @notice Get all minted plots.
function getAllPlots() external view returns(uint32[]) {
return plots;
}
/// @dev Represent a 2D coordinate as a single uint.
/// @param x The x-coordinate.
/// @param y The y-coordinate.
function coordinateToIdentifier(uint256 x, uint256 y) public pure returns(uint256) {
require(validCoordinate(x, y));
return (y << 16) + x;
}
/// @dev Turn a single uint representation of a coordinate into its x and y parts.
/// @param identifier The uint representation of a coordinate.
function identifierToCoordinate(uint256 identifier) public pure returns(uint256 x, uint256 y) {
require(validIdentifier(identifier));
y = identifier >> 16;
x = identifier - (y << 16);
}
/// @dev Test whether the coordinate is valid.
/// @param x The x-part of the coordinate to test.
/// @param y The y-part of the coordinate to test.
function validCoordinate(uint256 x, uint256 y) public pure returns(bool) {
return x < 65536 && y < 65536; // 2^16
}
/// @dev Test whether an identifier is valid.
/// @param identifier The identifier to test.
function validIdentifier(uint256 identifier) public pure returns(bool) {
return identifier < 4294967296; // 2^16 * 2^16
}
/// @dev Set a plot's data.
/// @param identifier The identifier of the plot to set data for.
function _setPlotData(uint256 identifier, string name, string description, string imageUrl, string infoUrl) internal {
SetData(identifier, name, description, imageUrl, infoUrl);
}
}
/// @dev Holds deed functionality such as approving and transferring. Implements ERC721.
contract DWorldDeed is DWorldBase, ERC721, ERC721Metadata {
/// @notice Name of the collection of deeds (non-fungible token), as defined in ERC721Metadata.
function name() public pure returns (string _deedName) {
_deedName = "DWorld Plots";
}
/// @notice Symbol of the collection of deeds (non-fungible token), as defined in ERC721Metadata.
function symbol() public pure returns (string _deedSymbol) {
_deedSymbol = "DWP";
}
/// @dev ERC-165 (draft) interface signature for itself
bytes4 internal constant INTERFACE_SIGNATURE_ERC165 = // 0x01ffc9a7
bytes4(keccak256('supportsInterface(bytes4)'));
/// @dev ERC-165 (draft) interface signature for ERC721
bytes4 internal constant INTERFACE_SIGNATURE_ERC721 = // 0xda671b9b
bytes4(keccak256('ownerOf(uint256)')) ^
bytes4(keccak256('countOfDeeds()')) ^
bytes4(keccak256('countOfDeedsByOwner(address)')) ^
bytes4(keccak256('deedOfOwnerByIndex(address,uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('takeOwnership(uint256)'));
/// @dev ERC-165 (draft) interface signature for ERC721
bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata = // 0x2a786f11
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('deedUri(uint256)'));
/// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165).
/// Returns true for any standardized interfaces implemented by this contract.
/// (ERC-165 and ERC-721.)
function supportsInterface(bytes4 _interfaceID) external pure returns (bool) {
return (
(_interfaceID == INTERFACE_SIGNATURE_ERC165)
|| (_interfaceID == INTERFACE_SIGNATURE_ERC721)
|| (_interfaceID == INTERFACE_SIGNATURE_ERC721Metadata)
);
}
/// @dev Checks if a given address owns a particular plot.
/// @param _owner The address of the owner to check for.
/// @param _deedId The plot identifier to check for.
function _owns(address _owner, uint256 _deedId) internal view returns (bool) {
return identifierToOwner[_deedId] == _owner;
}
/// @dev Approve a given address to take ownership of a deed.
/// @param _from The address approving taking ownership.
/// @param _to The address to approve taking ownership.
/// @param _deedId The identifier of the deed to give approval for.
function _approve(address _from, address _to, uint256 _deedId) internal {
identifierToApproved[_deedId] = _to;
// Emit event.
Approval(_from, _to, _deedId);
}
/// @dev Checks if a given address has approval to take ownership of a deed.
/// @param _claimant The address of the claimant to check for.
/// @param _deedId The identifier of the deed to check for.
function _approvedFor(address _claimant, uint256 _deedId) internal view returns (bool) {
return identifierToApproved[_deedId] == _claimant;
}
/// @dev Assigns ownership of a specific deed to an address.
/// @param _from The address to transfer the deed from.
/// @param _to The address to transfer the deed to.
/// @param _deedId The identifier of the deed to transfer.
function _transfer(address _from, address _to, uint256 _deedId) internal {
// The number of plots is capped at 2^16 * 2^16, so this cannot
// be overflowed.
ownershipDeedCount[_to]++;
// Transfer ownership.
identifierToOwner[_deedId] = _to;
// When a new deed is minted, the _from address is 0x0, but we
// do not track deed ownership of 0x0.
if (_from != address(0)) {
ownershipDeedCount[_from]--;
// Clear taking ownership approval.
delete identifierToApproved[_deedId];
}
// Emit the transfer event.
Transfer(_from, _to, _deedId);
}
// ERC 721 implementation
/// @notice Returns the total number of deeds currently in existence.
/// @dev Required for ERC-721 compliance.
function countOfDeeds() public view returns (uint256) {
return plots.length;
}
/// @notice Returns the number of deeds owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function countOfDeedsByOwner(address _owner) public view returns (uint256) {
return ownershipDeedCount[_owner];
}
/// @notice Returns the address currently assigned ownership of a given deed.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _deedId) external view returns (address _owner) {
_owner = identifierToOwner[_deedId];
require(_owner != address(0));
}
/// @notice Approve a given address to take ownership of a deed.
/// @param _to The address to approve taking owernship.
/// @param _deedId The identifier of the deed to give approval for.
/// @dev Required for ERC-721 compliance.
function approve(address _to, uint256 _deedId) external whenNotPaused {
uint256[] memory _deedIds = new uint256[](1);
_deedIds[0] = _deedId;
approveMultiple(_to, _deedIds);
}
/// @notice Approve a given address to take ownership of multiple deeds.
/// @param _to The address to approve taking ownership.
/// @param _deedIds The identifiers of the deeds to give approval for.
function approveMultiple(address _to, uint256[] _deedIds) public whenNotPaused {
// Ensure the sender is not approving themselves.
require(msg.sender != _to);
for (uint256 i = 0; i < _deedIds.length; i++) {
uint256 _deedId = _deedIds[i];
// Require the sender is the owner of the deed.
require(_owns(msg.sender, _deedId));
// Perform the approval.
_approve(msg.sender, _to, _deedId);
}
}
/// @notice Transfer a deed to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721, or your
/// deed may be lost forever.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _deedId The identifier of the deed to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(address _to, uint256 _deedId) external whenNotPaused {
uint256[] memory _deedIds = new uint256[](1);
_deedIds[0] = _deedId;
transferMultiple(_to, _deedIds);
}
/// @notice Transfers multiple deeds to another address. If transferring to
/// a smart contract be VERY CAREFUL to ensure that it is aware of ERC-721,
/// or your deeds may be lost forever.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _deedIds The identifiers of the deeds to transfer.
function transferMultiple(address _to, uint256[] _deedIds) public whenNotPaused {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
require(_to != address(this));
for (uint256 i = 0; i < _deedIds.length; i++) {
uint256 _deedId = _deedIds[i];
// One can only transfer their own plots.
require(_owns(msg.sender, _deedId));
// Transfer ownership
_transfer(msg.sender, _to, _deedId);
}
}
/// @notice Transfer a deed owned by another address, for which the calling
/// address has previously been granted transfer approval by the owner.
/// @param _deedId The identifier of the deed to be transferred.
/// @dev Required for ERC-721 compliance.
function takeOwnership(uint256 _deedId) external whenNotPaused {
uint256[] memory _deedIds = new uint256[](1);
_deedIds[0] = _deedId;
takeOwnershipMultiple(_deedIds);
}
/// @notice Transfer multiple deeds owned by another address, for which the
/// calling address has previously been granted transfer approval by the owner.
/// @param _deedIds The identifier of the deed to be transferred.
function takeOwnershipMultiple(uint256[] _deedIds) public whenNotPaused {
for (uint256 i = 0; i < _deedIds.length; i++) {
uint256 _deedId = _deedIds[i];
address _from = identifierToOwner[_deedId];
// Check for transfer approval
require(_approvedFor(msg.sender, _deedId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, msg.sender, _deedId);
}
}
/// @notice Returns a list of all deed identifiers assigned to an address.
/// @param _owner The owner whose deeds we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. It's very
/// expensive and is not supported in contract-to-contract calls as it returns
/// a dynamic array (only supported for web3 calls).
function deedsOfOwner(address _owner) external view returns(uint256[]) {
uint256 deedCount = countOfDeedsByOwner(_owner);
if (deedCount == 0) {
// Return an empty array.
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](deedCount);
uint256 totalDeeds = countOfDeeds();
uint256 resultIndex = 0;
for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) {
uint256 identifier = plots[deedNumber];
if (identifierToOwner[identifier] == _owner) {
result[resultIndex] = identifier;
resultIndex++;
}
}
return result;
}
}
/// @notice Returns a deed identifier of the owner at the given index.
/// @param _owner The address of the owner we want to get a deed for.
/// @param _index The index of the deed we want.
function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256) {
// The index should be valid.
require(_index < countOfDeedsByOwner(_owner));
// Loop through all plots, accounting the number of plots of the owner we've seen.
uint256 seen = 0;
uint256 totalDeeds = countOfDeeds();
for (uint256 deedNumber = 0; deedNumber < totalDeeds; deedNumber++) {
uint256 identifier = plots[deedNumber];
if (identifierToOwner[identifier] == _owner) {
if (seen == _index) {
return identifier;
}
seen++;
}
}
}
/// @notice Returns an (off-chain) metadata url for the given deed.
/// @param _deedId The identifier of the deed to get the metadata
/// url for.
/// @dev Implementation of optional ERC-721 functionality.
function deedUri(uint256 _deedId) external pure returns (string uri) {
require(validIdentifier(_deedId));
var (x, y) = identifierToCoordinate(_deedId);
// Maximum coordinate length in decimals is 5 (65535)
uri = "https://dworld.io/plot/xxxxx/xxxxx";
bytes memory _uri = bytes(uri);
for (uint256 i = 0; i < 5; i++) {
_uri[27 - i] = byte(48 + (x / 10 ** i) % 10);
_uri[33 - i] = byte(48 + (y / 10 ** i) % 10);
}
}
}
/// @dev Implements renting functionality.
contract DWorldRenting is DWorldDeed {
event Rent(address indexed renter, uint256 indexed deedId, uint256 rentPeriodEndTimestamp, uint256 rentPeriod);
mapping (uint256 => address) identifierToRenter;
mapping (uint256 => uint256) identifierToRentPeriodEndTimestamp;
/// @dev Checks if a given address rents a particular plot.
/// @param _renter The address of the renter to check for.
/// @param _deedId The plot identifier to check for.
function _rents(address _renter, uint256 _deedId) internal view returns (bool) {
return identifierToRenter[_deedId] == _renter && identifierToRentPeriodEndTimestamp[_deedId] >= now;
}
/// @dev Rent out a deed to an address.
/// @param _to The address to rent the deed out to.
/// @param _rentPeriod The rent period in seconds.
/// @param _deedId The identifier of the deed to rent out.
function _rentOut(address _to, uint256 _rentPeriod, uint256 _deedId) internal {
// Set the renter and rent period end timestamp
uint256 rentPeriodEndTimestamp = now.add(_rentPeriod);
identifierToRenter[_deedId] = _to;
identifierToRentPeriodEndTimestamp[_deedId] = rentPeriodEndTimestamp;
Rent(_to, _deedId, rentPeriodEndTimestamp, _rentPeriod);
}
/// @notice Rents a plot out to another address.
/// @param _to The address of the renter, can be a user or contract.
/// @param _rentPeriod The rent time period in seconds.
/// @param _deedId The identifier of the plot to rent out.
function rentOut(address _to, uint256 _rentPeriod, uint256 _deedId) external whenNotPaused {
uint256[] memory _deedIds = new uint256[](1);
_deedIds[0] = _deedId;
rentOutMultiple(_to, _rentPeriod, _deedIds);
}
/// @notice Rents multiple plots out to another address.
/// @param _to The address of the renter, can be a user or contract.
/// @param _rentPeriod The rent time period in seconds.
/// @param _deedIds The identifiers of the plots to rent out.
function rentOutMultiple(address _to, uint256 _rentPeriod, uint256[] _deedIds) public whenNotPaused {
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
require(_to != address(this));
for (uint256 i = 0; i < _deedIds.length; i++) {
uint256 _deedId = _deedIds[i];
require(validIdentifier(_deedId));
// There should not be an active renter.
require(identifierToRentPeriodEndTimestamp[_deedId] < now);
// One can only rent out their own plots.
require(_owns(msg.sender, _deedId));
_rentOut(_to, _rentPeriod, _deedId);
}
}
/// @notice Returns the address of the currently assigned renter and
/// end time of the rent period of a given plot.
/// @param _deedId The identifier of the deed to get the renter and
/// rent period for.
function renterOf(uint256 _deedId) external view returns (address _renter, uint256 _rentPeriodEndTimestamp) {
require(validIdentifier(_deedId));
if (identifierToRentPeriodEndTimestamp[_deedId] < now) {
// There is no active renter
_renter = address(0);
_rentPeriodEndTimestamp = 0;
} else {
_renter = identifierToRenter[_deedId];
_rentPeriodEndTimestamp = identifierToRentPeriodEndTimestamp[_deedId];
}
}
}
/// @title The internal clock auction functionality.
/// Inspired by CryptoKitties' clock auction
contract ClockAuctionBase {
// Address of the ERC721 contract this auction is linked to.
ERC721 public deedContract;
// Fee per successful auction in 1/1000th of a percentage.
uint256 public fee;
// Total amount of ether yet to be paid to auction beneficiaries.
uint256 public outstandingEther = 0 ether;
// Amount of ether yet to be paid per beneficiary.
mapping (address => uint256) public addressToEtherOwed;
/// @dev Represents a deed auction.
/// Care has been taken to ensure the auction fits in
/// two 256-bit words.
struct Auction {
address seller;
uint128 startPrice;
uint128 endPrice;
uint64 duration;
uint64 startedAt;
}
mapping (uint256 => Auction) identifierToAuction;
// Events
event AuctionCreated(address indexed seller, uint256 indexed deedId, uint256 startPrice, uint256 endPrice, uint256 duration);
event AuctionSuccessful(address indexed buyer, uint256 indexed deedId, uint256 totalPrice);
event AuctionCancelled(uint256 indexed deedId);
/// @dev Modifier to check whether the value can be stored in a 64 bit uint.
modifier fitsIn64Bits(uint256 _value) {
require (_value == uint256(uint64(_value)));
_;
}
/// @dev Modifier to check whether the value can be stored in a 128 bit uint.
modifier fitsIn128Bits(uint256 _value) {
require (_value == uint256(uint128(_value)));
_;
}
function ClockAuctionBase(address _deedContractAddress, uint256 _fee) public {
deedContract = ERC721(_deedContractAddress);
// Contract must indicate support for ERC721 through its interface signature.
require(deedContract.supportsInterface(0xda671b9b));
// Fee must be between 0 and 100%.
require(0 <= _fee && _fee <= 100000);
fee = _fee;
}
/// @dev Checks whether the given auction is active.
/// @param auction The auction to check for activity.
function _activeAuction(Auction storage auction) internal view returns (bool) {
return auction.startedAt > 0;
}
/// @dev Put the deed into escrow, thereby taking ownership of it.
/// @param _deedId The identifier of the deed to place into escrow.
function _escrow(uint256 _deedId) internal {
// Throws if the transfer fails
deedContract.takeOwnership(_deedId);
}
/// @dev Create the auction.
/// @param _deedId The identifier of the deed to create the auction for.
/// @param auction The auction to create.
function _createAuction(uint256 _deedId, Auction auction) internal {
// Add the auction to the auction mapping.
identifierToAuction[_deedId] = auction;
// Trigger auction created event.
AuctionCreated(auction.seller, _deedId, auction.startPrice, auction.endPrice, auction.duration);
}
/// @dev Bid on an auction.
/// @param _buyer The address of the buyer.
/// @param _value The value sent by the sender (in ether).
/// @param _deedId The identifier of the deed to bid on.
function _bid(address _buyer, uint256 _value, uint256 _deedId) internal {
Auction storage auction = identifierToAuction[_deedId];
// The auction must be active.
require(_activeAuction(auction));
// Calculate the auction's current price.
uint256 price = _currentPrice(auction);
// Make sure enough funds were sent.
require(_value >= price);
address seller = auction.seller;
if (price > 0) {
uint256 totalFee = _calculateFee(price);
uint256 proceeds = price - totalFee;
// Assign the proceeds to the seller.
// We do not send the proceeds directly, as to prevent
// malicious sellers from denying auctions (and burning
// the buyer's gas).
_assignProceeds(seller, proceeds);
}
AuctionSuccessful(_buyer, _deedId, price);
// The bid was won!
_winBid(seller, _buyer, _deedId, price);
// Remove the auction (we do this at the end, as
// winBid might require some additional information
// that will be removed when _removeAuction is
// called. As we do not transfer funds here, we do
// not have to worry about re-entry attacks.
_removeAuction(_deedId);
}
/// @dev Perform the bid win logic (in this case: transfer the deed).
/// @param _seller The address of the seller.
/// @param _winner The address of the winner.
/// @param _deedId The identifier of the deed.
/// @param _price The price the auction was bought at.
function _winBid(address _seller, address _winner, uint256 _deedId, uint256 _price) internal {
_transfer(_winner, _deedId);
}
/// @dev Cancel an auction.
/// @param _deedId The identifier of the deed for which the auction should be cancelled.
/// @param auction The auction to cancel.
function _cancelAuction(uint256 _deedId, Auction auction) internal {
// Remove the auction
_removeAuction(_deedId);
// Transfer the deed back to the seller
_transfer(auction.seller, _deedId);
// Trigger auction cancelled event.
AuctionCancelled(_deedId);
}
/// @dev Remove an auction.
/// @param _deedId The identifier of the deed for which the auction should be removed.
function _removeAuction(uint256 _deedId) internal {
delete identifierToAuction[_deedId];
}
/// @dev Transfer a deed owned by this contract to another address.
/// @param _to The address to transfer the deed to.
/// @param _deedId The identifier of the deed.
function _transfer(address _to, uint256 _deedId) internal {
// Throws if the transfer fails
deedContract.transfer(_to, _deedId);
}
/// @dev Assign proceeds to an address.
/// @param _to The address to assign proceeds to.
/// @param _value The proceeds to assign.
function _assignProceeds(address _to, uint256 _value) internal {
outstandingEther += _value;
addressToEtherOwed[_to] += _value;
}
/// @dev Calculate the current price of an auction.
function _currentPrice(Auction storage _auction) internal view returns (uint256) {
require(now >= _auction.startedAt);
uint256 secondsPassed = now - _auction.startedAt;
if (secondsPassed >= _auction.duration) {
return _auction.endPrice;
} else {
// Negative if the end price is higher than the start price!
int256 totalPriceChange = int256(_auction.endPrice) - int256(_auction.startPrice);
// Calculate the current price based on the total change over the entire
// auction duration, and the amount of time passed since the start of the
// auction.
int256 currentPriceChange = totalPriceChange * int256(secondsPassed) / int256(_auction.duration);
// Calculate the final price. Note this once again
// is representable by a uint256, as the price can
// never be negative.
int256 price = int256(_auction.startPrice) + currentPriceChange;
// This never throws.
assert(price >= 0);
return uint256(price);
}
}
/// @dev Calculate the fee for a given price.
/// @param _price The price to calculate the fee for.
function _calculateFee(uint256 _price) internal view returns (uint256) {
// _price is guaranteed to fit in a uint128 due to the createAuction entry
// modifiers, so this cannot overflow.
return _price * fee / 100000;
}
}
contract ClockAuction is ClockAuctionBase, Pausable {
function ClockAuction(address _deedContractAddress, uint256 _fee)
ClockAuctionBase(_deedContractAddress, _fee)
public
{}
/// @notice Update the auction fee.
/// @param _fee The new fee.
function setFee(uint256 _fee) external onlyOwner {
require(0 <= _fee && _fee <= 100000);
fee = _fee;
}
/// @notice Get the auction for the given deed.
/// @param _deedId The identifier of the deed to get the auction for.
/// @dev Throws if there is no auction for the given deed.
function getAuction(uint256 _deedId) external view returns (
address seller,
uint256 startPrice,
uint256 endPrice,
uint256 duration,
uint256 startedAt
)
{
Auction storage auction = identifierToAuction[_deedId];
// The auction must be active
require(_activeAuction(auction));
return (
auction.seller,
auction.startPrice,
auction.endPrice,
auction.duration,
auction.startedAt
);
}
/// @notice Create an auction for a given deed.
/// Must previously have been given approval to take ownership of the deed.
/// @param _deedId The identifier of the deed to create an auction for.
/// @param _startPrice The starting price of the auction.
/// @param _endPrice The ending price of the auction.
/// @param _duration The duration in seconds of the dynamic pricing part of the auction.
function createAuction(uint256 _deedId, uint256 _startPrice, uint256 _endPrice, uint256 _duration)
public
fitsIn128Bits(_startPrice)
fitsIn128Bits(_endPrice)
fitsIn64Bits(_duration)
whenNotPaused
{
// Get the owner of the deed to be auctioned
address deedOwner = deedContract.ownerOf(_deedId);
// Caller must either be the deed contract or the owner of the deed
// to prevent abuse.
require(
msg.sender == address(deedContract) ||
msg.sender == deedOwner
);
// The duration of the auction must be at least 60 seconds.
require(_duration >= 60);
// Throws if placing the deed in escrow fails (the contract requires
// transfer approval prior to creating the auction).
_escrow(_deedId);
// Auction struct
Auction memory auction = Auction(
deedOwner,
uint128(_startPrice),
uint128(_endPrice),
uint64(_duration),
uint64(now)
);
_createAuction(_deedId, auction);
}
/// @notice Cancel an auction
/// @param _deedId The identifier of the deed to cancel the auction for.
function cancelAuction(uint256 _deedId) external whenNotPaused {
Auction storage auction = identifierToAuction[_deedId];
// The auction must be active.
require(_activeAuction(auction));
// The auction can only be cancelled by the seller
require(msg.sender == auction.seller);
_cancelAuction(_deedId, auction);
}
/// @notice Bid on an auction.
/// @param _deedId The identifier of the deed to bid on.
function bid(uint256 _deedId) external payable whenNotPaused {
// Throws if the bid does not succeed.
_bid(msg.sender, msg.value, _deedId);
}
/// @dev Returns the current price of an auction.
/// @param _deedId The identifier of the deed to get the currency price for.
function getCurrentPrice(uint256 _deedId) external view returns (uint256) {
Auction storage auction = identifierToAuction[_deedId];
// The auction must be active.
require(_activeAuction(auction));
return _currentPrice(auction);
}
/// @notice Withdraw ether owed to a beneficiary.
/// @param beneficiary The address to withdraw the auction balance for.
function withdrawAuctionBalance(address beneficiary) external {
// The sender must either be the beneficiary or the core deed contract.
require(
msg.sender == beneficiary ||
msg.sender == address(deedContract)
);
uint256 etherOwed = addressToEtherOwed[beneficiary];
// Ensure ether is owed to the beneficiary.
require(etherOwed > 0);
// Set ether owed to 0
delete addressToEtherOwed[beneficiary];
// Subtract from total outstanding balance. etherOwed is guaranteed
// to be less than or equal to outstandingEther, so this cannot
// underflow.
outstandingEther -= etherOwed;
// Transfer ether owed to the beneficiary (not susceptible to re-entry
// attack, as the ether owed is set to 0 before the transfer takes place).
beneficiary.transfer(etherOwed);
}
/// @notice Withdraw (unowed) contract balance.
function withdrawFreeBalance() external {
// Calculate the free (unowed) balance. This never underflows, as
// outstandingEther is guaranteed to be less than or equal to the
// contract balance.
uint256 freeBalance = this.balance - outstandingEther;
address deedContractAddress = address(deedContract);
require(
msg.sender == owner ||
msg.sender == deedContractAddress
);
deedContractAddress.transfer(freeBalance);
}
}
contract RentAuction is ClockAuction {
function RentAuction(address _deedContractAddress, uint256 _fee) ClockAuction(_deedContractAddress, _fee) public {}
/// @dev Allows other contracts to check whether this is the expected contract.
bool public isRentAuction = true;
mapping (uint256 => uint256) public identifierToRentPeriod;
/// @notice Create an auction for a given deed. Be careful when calling
/// createAuction for a RentAuction, that this overloaded function (including
/// the _rentPeriod parameter) is used. Otherwise the rent period defaults to
/// a week.
/// Must previously have been given approval to take ownership of the deed.
/// @param _deedId The identifier of the deed to create an auction for.
/// @param _startPrice The starting price of the auction.
/// @param _endPrice The ending price of the auction.
/// @param _duration The duration in seconds of the dynamic pricing part of the auction.
/// @param _rentPeriod The rent period in seconds being auctioned.
function createAuction(
uint256 _deedId,
uint256 _startPrice,
uint256 _endPrice,
uint256 _duration,
uint256 _rentPeriod
)
external
{
// Require the rent period to be at least one hour.
require(_rentPeriod >= 3600);
// Require there to be no active renter.
DWorldRenting dWorldRentingContract = DWorldRenting(deedContract);
var (renter,) = dWorldRentingContract.renterOf(_deedId);
require(renter == address(0));
// Set the rent period.
identifierToRentPeriod[_deedId] = _rentPeriod;
// Throws (reverts) if creating the auction fails.
createAuction(_deedId, _startPrice, _endPrice, _duration);
}
/// @dev Perform the bid win logic (in this case: give renter status to the winner).
/// @param _seller The address of the seller.
/// @param _winner The address of the winner.
/// @param _deedId The identifier of the deed.
/// @param _price The price the auction was bought at.
function _winBid(address _seller, address _winner, uint256 _deedId, uint256 _price) internal {
DWorldRenting dWorldRentingContract = DWorldRenting(deedContract);
uint256 rentPeriod = identifierToRentPeriod[_deedId];
if (rentPeriod == 0) {
rentPeriod = 604800; // 1 week by default
}
// Rent the deed out to the winner.
dWorldRentingContract.rentOut(_winner, identifierToRentPeriod[_deedId], _deedId);
// Transfer the deed back to the seller.
_transfer(_seller, _deedId);
}
/// @dev Remove an auction.
/// @param _deedId The identifier of the deed for which the auction should be removed.
function _removeAuction(uint256 _deedId) internal {
delete identifierToAuction[_deedId];
delete identifierToRentPeriod[_deedId];
}
}
| @notice Symbol of the collection of deeds (non-fungible token), as defined in ERC721Metadata. | function symbol() public pure returns (string _deedSymbol) {
_deedSymbol = "DWP";
}
bytes4(keccak256('countOfDeeds()')) ^
bytes4(keccak256('countOfDeedsByOwner(address)')) ^
bytes4(keccak256('deedOfOwnerByIndex(address,uint256)')) ^
bytes4(keccak256('approve(address,uint256)')) ^
bytes4(keccak256('takeOwnership(uint256)'));
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('deedUri(uint256)'));
| 12,995,697 | [
1,
5335,
434,
326,
1849,
434,
443,
9765,
261,
5836,
17,
12125,
75,
1523,
1147,
3631,
487,
2553,
316,
4232,
39,
27,
5340,
2277,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
3273,
1435,
1071,
16618,
1135,
261,
1080,
389,
323,
329,
5335,
13,
288,
203,
3639,
389,
323,
329,
5335,
273,
315,
40,
20265,
14432,
203,
565,
289,
203,
377,
203,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
1883,
951,
758,
9765,
11866,
3719,
3602,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
1883,
951,
758,
9765,
858,
5541,
12,
2867,
2506,
3719,
3602,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
323,
329,
951,
5541,
21268,
12,
2867,
16,
11890,
5034,
2506,
3719,
3602,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
12908,
537,
12,
2867,
16,
11890,
5034,
2506,
3719,
3602,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
22188,
5460,
12565,
12,
11890,
5034,
2506,
10019,
203,
540,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
7175,
11866,
3719,
3602,
203,
3639,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
323,
329,
3006,
12,
11890,
5034,
2506,
10019,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// File: @openzeppelin/contracts/math/Math.sol
pragma solidity ^0.5.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* 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.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.5.0;
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// File: contracts/strategies/curve/interfaces/Gauge.sol
pragma solidity 0.5.16;
interface Gauge {
function deposit(uint) external;
function balanceOf(address) external view returns (uint);
function withdraw(uint) external;
function user_checkpoint(address) external;
}
interface VotingEscrow {
function create_lock(uint256 v, uint256 time) external;
function increase_amount(uint256 _value) external;
function increase_unlock_time(uint256 _unlock_time) external;
function withdraw() external;
}
interface Mintr {
function mint(address) external;
}
// File: contracts/strategies/curve/interfaces/ICurveFiWbtc.sol
pragma solidity 0.5.16;
interface ICurveFiWbtc {
function get_virtual_price() external view returns (uint);
function add_liquidity(
uint256[2] calldata amounts,
uint256 min_mint_amount
) external;
function remove_liquidity_imbalance(
uint256[2] calldata amounts,
uint256 max_burn_amount
) external;
function remove_liquidity(
uint256 _amount,
uint256[2] calldata amounts
) external;
function exchange(
int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount
) external;
function calc_token_amount(
uint256[2] calldata amounts,
bool deposit
) external view returns(uint);
function calc_withdraw_one_coin(
uint256 _token_amount, int128 i) external view returns (uint256);
function remove_liquidity_one_coin(uint256 _token_amount, int128 i,
uint256 min_amount) external;
}
// File: contracts/hardworkInterface/IController.sol
pragma solidity 0.5.16;
interface IController {
// [Grey list]
// An EOA can safely interact with the system no matter what.
// If you're using Metamask, you're using an EOA.
// Only smart contracts may be affected by this grey list.
//
// This contract will not be able to ban any EOA from the system
// even if an EOA is being added to the greyList, he/she will still be able
// to interact with the whole system as if nothing happened.
// Only smart contracts will be affected by being added to the greyList.
// This grey list is only used in Vault.sol, see the code there for reference
function greyList(address _target) external returns(bool);
function addVaultAndStrategy(address _vault, address _strategy) external;
function doHardWork(address _vault) external;
function hasVault(address _vault) external returns(bool);
function salvage(address _token, uint256 amount) external;
function salvageStrategy(address _strategy, address _token, uint256 amount) external;
function notifyFee(address _underlying, uint256 fee) external;
function profitSharingNumerator() external view returns (uint256);
function profitSharingDenominator() external view returns (uint256);
}
// File: contracts/Storage.sol
pragma solidity 0.5.16;
contract Storage {
address public governance;
address public controller;
constructor() public {
governance = msg.sender;
}
modifier onlyGovernance() {
require(isGovernance(msg.sender), "Not governance");
_;
}
function setGovernance(address _governance) public onlyGovernance {
require(_governance != address(0), "new governance shouldn't be empty");
governance = _governance;
}
function setController(address _controller) public onlyGovernance {
require(_controller != address(0), "new controller shouldn't be empty");
controller = _controller;
}
function isGovernance(address account) public view returns (bool) {
return account == governance;
}
function isController(address account) public view returns (bool) {
return account == controller;
}
}
// File: contracts/Governable.sol
pragma solidity 0.5.16;
contract Governable {
Storage public store;
constructor(address _store) public {
require(_store != address(0), "new storage shouldn't be empty");
store = Storage(_store);
}
modifier onlyGovernance() {
require(store.isGovernance(msg.sender), "Not governance");
_;
}
function setStorage(address _store) public onlyGovernance {
require(_store != address(0), "new storage shouldn't be empty");
store = Storage(_store);
}
function governance() public view returns (address) {
return store.governance();
}
}
// File: contracts/Controllable.sol
pragma solidity 0.5.16;
contract Controllable is Governable {
constructor(address _storage) Governable(_storage) public {
}
modifier onlyController() {
require(store.isController(msg.sender), "Not a controller");
_;
}
modifier onlyControllerOrGovernance(){
require((store.isController(msg.sender) || store.isGovernance(msg.sender)),
"The caller must be controller or governance");
_;
}
function controller() public view returns (address) {
return store.controller();
}
}
// File: contracts/strategies/ProfitNotifier.sol
pragma solidity 0.5.16;
contract ProfitNotifier is Controllable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 public profitSharingNumerator;
uint256 public profitSharingDenominator;
address public underlying;
event ProfitLog(
uint256 oldBalance,
uint256 newBalance,
uint256 feeAmount,
uint256 timestamp
);
constructor(
address _storage,
address _underlying
) public Controllable(_storage){
underlying = _underlying;
// persist in the state for immutability of the fee
profitSharingNumerator = 30; //IController(controller()).profitSharingNumerator();
profitSharingDenominator = 100; //IController(controller()).profitSharingDenominator();
require(profitSharingNumerator < profitSharingDenominator, "invalid profit share");
}
function notifyProfit(uint256 oldBalance, uint256 newBalance) internal {
if (newBalance > oldBalance) {
uint256 profit = newBalance.sub(oldBalance);
uint256 feeAmount = profit.mul(profitSharingNumerator).div(profitSharingDenominator);
emit ProfitLog(oldBalance, newBalance, feeAmount, block.timestamp);
IERC20(underlying).safeApprove(controller(), 0);
IERC20(underlying).safeApprove(controller(), feeAmount);
IController(controller()).notifyFee(
underlying,
feeAmount
);
} else {
emit ProfitLog(oldBalance, newBalance, 0, block.timestamp);
}
}
}
// File: contracts/hardworkInterface/IStrategy.sol
pragma solidity 0.5.16;
interface IStrategy {
function unsalvagableTokens(address tokens) external view returns (bool);
function governance() external view returns (address);
function controller() external view returns (address);
function underlying() external view returns (address);
function vault() external view returns (address);
function withdrawAllToVault() external;
function withdrawToVault(uint256 amount) external;
function investedUnderlyingBalance() external view returns (uint256); // itsNotMuch()
// should only be called by controller
function salvage(address recipient, address token, uint256 amount) external;
function doHardWork() external;
function depositArbCheck() external view returns(bool);
}
// File: contracts/uniswap/interfaces/IUniswapV2Router01.sol
pragma solidity >=0.5.0;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// File: contracts/uniswap/interfaces/IUniswapV2Router02.sol
pragma solidity >=0.5.0;
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File: contracts/strategies/curve/CRVStrategyWRenBTCMix.sol
pragma solidity 0.5.16;
contract CRVStrategyWRenBTCMix is IStrategy, ProfitNotifier {
enum TokenIndex {REN_BTC, WBTC}
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
// wbtc token address (or ren if we want both)
address public wbtc;
// the matching enum record used to determine the index
TokenIndex tokenIndex;
// our vault holding the wbtc asset
address public vault;
// the address of mixToken token
address public mixToken;
// the address of underlying token
address public underlying;
// the address of the Curve protocol's pool for REN + WBTC
address public curve;
// these tokens cannot be claimed by the governance
mapping(address => bool) public unsalvagableTokens;
// the wbtc gauge in Curve
address public gauge;
// the reward minter
address public mintr;
// the address for the CRV token
address public crv;
// uniswap router address
address public uni;
// liquidation path to be used
address[] public uniswap_CRV2WBTC;
// a flag for disabling selling for simplified emergency exit
bool public sell = true;
// minimum CRV amount to be liquidation
uint256 public sellFloor = 12e18;
event Liquidating(uint256 amount);
event NotLiquidating(uint256 amount);
event ProfitsNotCollected();
modifier restricted() {
require(msg.sender == vault || msg.sender == controller()
|| msg.sender == governance(),
"The sender has to be the controller, governance, or vault");
_;
}
constructor(
address _storage,
address _wbtc,
address _vault,
uint256 _tokenIndex,
address _mixToken,
address _curvePool,
address _crv,
address _weth,
address _gauge,
address _mintr,
address _uniswap
)
ProfitNotifier(_storage, _wbtc) public {
vault = _vault;
underlying = _mixToken;
wbtc = _wbtc;
tokenIndex = TokenIndex(_tokenIndex);
mixToken = _mixToken;
curve = _curvePool;
gauge = _gauge;
crv = _crv;
uni = _uniswap;
mintr = _mintr;
uniswap_CRV2WBTC = [_crv, _weth, _wbtc];
// set these tokens to be not salvageable
unsalvagableTokens[wbtc] = true;
unsalvagableTokens[mixToken] = true;
unsalvagableTokens[crv] = true;
}
function depositArbCheck() public view returns(bool) {
return true;
}
/**
* Uses the Curve protocol to convert the wbtc asset into to mixed renwbtc token.
*/
function mixFromWBTC() internal {
uint256 wbtcBalance = IERC20(wbtc).balanceOf(address(this));
if (wbtcBalance > 0) {
IERC20(wbtc).safeApprove(curve, 0);
IERC20(wbtc).safeApprove(curve, wbtcBalance);
// we can accept 0 as minimum because this is called only by a trusted role
uint256 minimum = 0;
uint256[2] memory coinAmounts = wrapCoinAmount(wbtcBalance);
ICurveFiWbtc(curve).add_liquidity(
coinAmounts, minimum
);
}
// now we have the mixed token
}
/**
* Withdraws an wbtc asset from the strategy to the vault in the specified amount by asking
* by removing imbalanced liquidity from the Curve protocol. The rest is deposited back to the
* Curve protocol pool. If the amount requested cannot be obtained, the method will get as much
* as we have.
*/
function withdrawToVault(uint256 amountUnderlying) external restricted {
// withdraw all from gauge
Gauge(gauge).withdraw(Gauge(gauge).balanceOf(address(this)));
// we can transfer the asset to the vault
uint256 actualBalance = IERC20(underlying).balanceOf(address(this));
if (actualBalance > 0) {
IERC20(underlying).safeTransfer(vault, Math.min(amountUnderlying, actualBalance));
}
// invest back the rest
investAllUnderlying();
}
/**
* Withdraws all assets from the vault.
*/
function withdrawAllToVault() external restricted {
// withdraw all from gauge
Gauge(gauge).withdraw(Gauge(gauge).balanceOf(address(this)));
// we can transfer the asset to the vault
uint256 actualBalance = IERC20(underlying).balanceOf(address(this));
if (actualBalance > 0) {
IERC20(underlying).safeTransfer(vault, actualBalance);
}
}
/**
* Invests all wbtc assets into our mixToken vault.
*/
function investAllUnderlying() internal {
// then deposit into the mixToken vault
uint256 mixTokenBalance = IERC20(underlying).balanceOf(address(this));
if (mixTokenBalance > 0) {
IERC20(underlying).safeApprove(gauge, 0);
IERC20(underlying).safeApprove(gauge, mixTokenBalance);
Gauge(gauge).deposit(mixTokenBalance);
}
}
/**
* The hard work only invests all wbtc assets, and then tells the controller to call hard
* work on the mixToken vault.
*/
function doHardWork() public restricted {
claimAndLiquidateCrv();
investAllUnderlying();
}
/**
* Salvages a token. We cannot salvage mixToken tokens, CRV, or wbtc assets.
*/
function salvage(address recipient, address token, uint256 amount) public onlyGovernance {
// To make sure that governance cannot come in and take away the coins
require(!unsalvagableTokens[token], "token is defined as not salvageable");
IERC20(token).safeTransfer(recipient, amount);
}
/**
* Returns the wbtc invested balance. The is the wbtc amount in this stragey, plus the gauge
* amount of the mixed token converted back to wbtc.
*/
function investedUnderlyingBalance() public view returns (uint256) {
uint256 gaugeBalance = Gauge(gauge).balanceOf(address(this));
uint256 underlyingBalance = IERC20(underlying).balanceOf(address(this));
if (gaugeBalance == 0) {
// !!! if we have 0 balance in gauge, the conversion to wbtc reverts in Curve
// !!! this if-statement is necessary to avoid transaction reverts
return underlyingBalance;
}
return gaugeBalance.add(underlyingBalance);
}
/**
* Wraps the coin amount in the array for interacting with the Curve protocol
*/
function wrapCoinAmount(uint256 amount) internal view returns (uint256[2] memory) {
uint256[2] memory amounts = [uint256(0), uint256(0)];
amounts[uint56(tokenIndex)] = amount;
return amounts;
}
/**
* Claims the CRV crop, converts it to WBTC/renWBTC on Uniswap
*/
function claimAndLiquidateCrv() internal {
if (!sell) {
// Profits can be disabled for possible simplified and rapid exit
emit ProfitsNotCollected();
return;
}
Mintr(mintr).mint(gauge);
// claiming rewards and liquidating them
uint256 crvBalance = IERC20(crv).balanceOf(address(this));
if (crvBalance > sellFloor) {
emit Liquidating(crvBalance);
uint256 wbtcBalanceBefore = IERC20(wbtc).balanceOf(address(this));
IERC20(crv).safeApprove(uni, 0);
IERC20(crv).safeApprove(uni, crvBalance);
// we can accept 1 as the minimum because this will be called only by a trusted worker
IUniswapV2Router02(uni).swapExactTokensForTokens(
crvBalance, 1, uniswap_CRV2WBTC, address(this), block.timestamp
);
// now we have WBTC
notifyProfit(wbtcBalanceBefore, IERC20(wbtc).balanceOf(address(this)));
// Convert WBTC into mixBTC
mixFromWBTC();
} else {
emit NotLiquidating(crvBalance);
}
}
/**
* Can completely disable claiming CRV rewards and selling. Good for emergency withdraw in the
* simplest possible way.
*/
function setSell(bool s) public onlyGovernance {
sell = s;
}
/**
* Sets the minimum amount of CRV needed to trigger a sale.
*/
function setSellFloor(uint256 floor) public onlyGovernance {
sellFloor = floor;
}
}
// File: contracts/strategies/curve/interfaces/IPriceConvertor.sol
pragma solidity 0.5.16;
interface IPriceConvertor {
function yCrvToUnderlying(uint256 _token_amount, uint256 i) external view returns (uint256);
}
// File: contracts/strategies/curve/PriceConvertor.sol
pragma solidity 0.5.16;
interface IConvertor {
function calc_withdraw_one_coin(uint256 _token_amount, int128 i) external view returns (uint256);
}
contract PriceConvertor is IPriceConvertor {
IConvertor public zap = IConvertor(0xbBC81d23Ea2c3ec7e56D39296F0cbB648873a5d3);
function yCrvToUnderlying(uint256 _token_amount, uint256 i) public view returns (uint256) {
// this returning the DAI amount, not yDAI
return zap.calc_withdraw_one_coin(_token_amount, int128(i));
}
}
contract MockPriceConvertor is IPriceConvertor {
function yCrvToUnderlying(uint256 _token_amount, uint256 /* i */) public view returns (uint256) {
// counting 1:1
return _token_amount;
}
}
// File: contracts/strategies/curve/CRVStrategyWRenBTCMixMainnet.sol
pragma solidity 0.5.16;
/**
* Adds the mainnet addresses to the CRVStrategyWBTC
*/
contract CRVStrategyWRenBTCMixMainnet is CRVStrategyWRenBTCMix {
// token addresses
address constant public __wbtc = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
address constant public __wbtcMix = address(0x49849C98ae39Fff122806C06791Fa73784FB3675);
address constant public __crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52);
address constant public __weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address constant public __gauge = address(0xB1F2cdeC61db658F091671F5f199635aEF202CAC);
address constant public __mintr = address(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0); // _mintr
// protocols
address constant public __curve = address(0x93054188d876f558f4a66B2EF1d97d16eDf0895B);
address constant public __uniswap = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uint256 constant public __tokenIndex = 1;
constructor(
address _storage,
address _vault
)
CRVStrategyWRenBTCMix(
_storage,
__wbtc,
_vault,
__tokenIndex, // token index for WBTC
__wbtcMix,
__curve, // curve protocol's pool for WBTC
__crv, // the CRV token address
__weth,
__gauge,
__mintr,
__uniswap // uniswap
)
public {
}
} | * Adds the mainnet addresses to the CRVStrategyWBTC/ token addresses protocols | contract CRVStrategyWRenBTCMixMainnet is CRVStrategyWRenBTCMix {
address constant public __wbtc = address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
address constant public __wbtcMix = address(0x49849C98ae39Fff122806C06791Fa73784FB3675);
address constant public __crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52);
address constant public __weth = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address constant public __gauge = address(0xB1F2cdeC61db658F091671F5f199635aEF202CAC);
address constant public __curve = address(0x93054188d876f558f4a66B2EF1d97d16eDf0895B);
address constant public __uniswap = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uint256 constant public __tokenIndex = 1;
constructor(
address _storage,
address _vault
)
CRVStrategyWRenBTCMix(
_storage,
__wbtc,
_vault,
__wbtcMix,
__weth,
__gauge,
__mintr,
)
public {
}
} | 227,847 | [
1,
3655,
326,
2774,
2758,
6138,
358,
326,
6732,
58,
4525,
59,
38,
15988,
19,
1147,
6138,
16534,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
6732,
58,
4525,
7181,
275,
38,
56,
9611,
697,
6376,
2758,
353,
6732,
58,
4525,
7181,
275,
38,
56,
9611,
697,
288,
203,
203,
225,
1758,
5381,
1071,
1001,
9464,
5111,
273,
1758,
12,
20,
92,
3787,
4848,
2046,
39,
25,
41,
2539,
9452,
69,
4700,
23,
37,
69,
6334,
74,
16283,
3030,
40,
74,
27,
39,
3657,
23,
13459,
22,
39,
25,
2733,
1769,
203,
225,
1758,
5381,
1071,
1001,
9464,
5111,
21294,
273,
1758,
12,
20,
92,
7616,
5193,
29,
39,
10689,
8906,
5520,
42,
1403,
22266,
3672,
26,
39,
7677,
7235,
21,
29634,
27,
6418,
5193,
22201,
5718,
5877,
1769,
203,
225,
1758,
5381,
1071,
1001,
3353,
90,
273,
1758,
12,
20,
17593,
25,
3707,
69,
29,
7616,
5608,
20,
9897,
3707,
7677,
72,
23635,
6743,
14509,
507,
29,
713,
70,
37,
4630,
24,
4315,
9401,
1769,
203,
225,
1758,
5381,
1071,
1001,
91,
546,
273,
1758,
12,
20,
14626,
3103,
7598,
37,
5520,
70,
3787,
23,
8090,
28,
40,
20,
37,
20,
73,
25,
39,
24,
42,
5324,
73,
1880,
29,
6840,
23,
39,
27,
4313,
39,
71,
22,
1769,
203,
225,
1758,
5381,
1071,
1001,
75,
8305,
273,
1758,
12,
20,
20029,
21,
42,
22,
71,
323,
39,
9498,
1966,
26,
8204,
42,
5908,
2313,
11212,
42,
25,
74,
19818,
4449,
25,
69,
26897,
18212,
26022,
1769,
203,
203,
225,
1758,
5381,
1071,
1001,
16683,
273,
1758,
12,
20,
92,
29,
5082,
6564,
2643,
28,
72,
28,
6669,
74,
2539,
28,
74,
24,
69,
6028,
38,
22,
26897,
2
]
|
./partial_match/1/0x3922B97e2519C05C1596F62833b863c969D593Aa/sources/Aligator.sol | * @dev Sets the value of the `decimals`. This value is immutable, it can only be set once during construction./ | constructor () ERC20('Aligator Finance', 'ALIGATOR') {
_mint(_msgSender(), _totalSupply);
}
| 2,758,920 | [
1,
2785,
326,
460,
434,
326,
1375,
31734,
8338,
1220,
460,
353,
11732,
16,
518,
848,
1338,
506,
444,
3647,
4982,
16171,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
1832,
4232,
39,
3462,
2668,
1067,
360,
639,
9458,
1359,
2187,
296,
1013,
3047,
3575,
6134,
288,
203,
3639,
389,
81,
474,
24899,
3576,
12021,
9334,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/97/0xfF5C54C5710fBF64744ad1428473d44f89811eb0/sources/project_/contracts/ProjectLaunchpad.sol | Payment Token */* @notice This method is used to add Payment token @param _paymentToken Address of payment token to be added/ | function addPaymentToken(address _paymentToken) external onlyOwner {
require(
!_paymentSupported[_paymentToken],
"ProjectLaunchpad: token already added"
);
_paymentSupported[_paymentToken] = true;
emit AddPaymentToken(_paymentToken);
}
| 3,281,899 | [
1,
6032,
3155,
342,
225,
1220,
707,
353,
1399,
358,
527,
12022,
1147,
225,
389,
9261,
1345,
5267,
434,
5184,
1147,
358,
506,
3096,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
527,
6032,
1345,
12,
2867,
389,
9261,
1345,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
12,
203,
5411,
401,
67,
9261,
7223,
63,
67,
9261,
1345,
6487,
203,
5411,
315,
4109,
9569,
6982,
30,
1147,
1818,
3096,
6,
203,
3639,
11272,
203,
3639,
389,
9261,
7223,
63,
67,
9261,
1345,
65,
273,
638,
31,
203,
3639,
3626,
1436,
6032,
1345,
24899,
9261,
1345,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x61aF004572A538e9B356FD65D81279Aa7197b142/sources/Jamie.sol | /* @title Decimal @author dYdX Library that defines a fixed-point number with 18 decimal places./ ============ Constants ============ ============ Structs ============ | library Decimal {
using SafeMath for uint256;
uint256 constant BASE = 10**18;
Copyright 2019 dYdX Trading Inc.
struct D256 {
uint256 value;
}
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) });
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);
}
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
D256 memory temp = D256({ value: self.value });
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
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);
}
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;
}
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;
}
}
| 2,773,055 | [
1,
19,
225,
11322,
225,
302,
61,
72,
60,
18694,
716,
11164,
279,
5499,
17,
1153,
1300,
598,
6549,
6970,
12576,
18,
19,
422,
1432,
631,
5245,
422,
1432,
631,
422,
1432,
631,
7362,
87,
422,
1432,
631,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
12083,
11322,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
7010,
7010,
565,
2254,
5034,
5381,
10250,
273,
1728,
636,
2643,
31,
203,
7010,
7010,
7010,
565,
25417,
30562,
302,
61,
72,
60,
2197,
7459,
15090,
18,
203,
565,
1958,
463,
5034,
288,
203,
3639,
2254,
5034,
460,
31,
203,
565,
289,
203,
7010,
7010,
565,
445,
3634,
1435,
203,
565,
2713,
203,
565,
16618,
203,
565,
1135,
261,
40,
5034,
3778,
13,
203,
565,
288,
203,
565,
289,
203,
7010,
3639,
327,
463,
5034,
12590,
460,
30,
374,
15549,
203,
565,
445,
1245,
1435,
203,
565,
2713,
203,
565,
16618,
203,
565,
1135,
261,
40,
5034,
3778,
13,
203,
565,
288,
203,
565,
289,
203,
7010,
3639,
327,
463,
5034,
12590,
460,
30,
10250,
15549,
203,
565,
445,
628,
12,
203,
3639,
2254,
5034,
279,
203,
565,
262,
203,
565,
2713,
203,
565,
16618,
203,
565,
1135,
261,
40,
5034,
3778,
13,
203,
565,
288,
203,
565,
289,
203,
7010,
3639,
327,
463,
5034,
12590,
460,
30,
279,
18,
16411,
12,
8369,
13,
15549,
203,
565,
445,
7169,
12,
203,
3639,
2254,
5034,
279,
16,
203,
3639,
2254,
5034,
324,
203,
565,
262,
203,
565,
2713,
203,
565,
16618,
203,
565,
1135,
261,
40,
5034,
3778,
13,
203,
565,
288,
203,
565,
289,
203,
7010,
3639,
327,
463,
5034,
12590,
460,
30,
13657,
649,
12,
69,
16,
10250,
16,
324,
13,
15549,
203,
7010,
565,
445,
527,
12,
203,
3639,
463,
5034,
3778,
365,
16,
203,
3639,
2254,
5034,
324,
2
]
|
./partial_match/1/0xA62fcF90dCdA0f2E942749a121eF2F81c7f1C162/sources/AntexToken.sol | Create a pancake pair for this new token set the rest of the contract variablesexclude owner and this contract from fee exclude from max tx | constructor () public payable {
_rOwned[_msgSender()] = _rTotal;
IPancakeRouter02 _pancakeRouter = IPancakeRouter02(routerAddress);
pancakePair = IPancakeFactory(_pancakeRouter.factory()).createPair(address(this), _pancakeRouter.WETH());
pancakeRouter = _pancakeRouter;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
_isExcludedFromMaxTx[owner()] = true;
_isExcludedFromMaxTx[address(this)] = true;
_isExcludedFromMaxTx[deadWallet] = true;
_isExcludedFromMaxTx[address(0)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
| 4,043,883 | [
1,
1684,
279,
2800,
23780,
3082,
364,
333,
394,
1147,
444,
326,
3127,
434,
326,
6835,
3152,
10157,
3410,
471,
333,
6835,
628,
14036,
4433,
628,
943,
2229,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
3885,
1832,
1071,
8843,
429,
288,
203,
3639,
389,
86,
5460,
329,
63,
67,
3576,
12021,
1435,
65,
273,
389,
86,
5269,
31,
203,
203,
3639,
2971,
19292,
911,
8259,
3103,
389,
7355,
23780,
8259,
273,
2971,
19292,
911,
8259,
3103,
12,
10717,
1887,
1769,
203,
3639,
2800,
23780,
4154,
273,
2971,
19292,
911,
1733,
24899,
7355,
23780,
8259,
18,
6848,
1435,
2934,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
7355,
23780,
8259,
18,
59,
1584,
44,
10663,
203,
203,
3639,
2800,
23780,
8259,
273,
389,
7355,
23780,
8259,
31,
203,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
8443,
1435,
65,
273,
638,
31,
203,
3639,
389,
291,
16461,
1265,
14667,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
203,
3639,
389,
291,
16461,
1265,
2747,
4188,
63,
8443,
1435,
65,
273,
638,
31,
203,
3639,
389,
291,
16461,
1265,
2747,
4188,
63,
2867,
12,
2211,
25887,
273,
638,
31,
203,
3639,
389,
291,
16461,
1265,
2747,
4188,
63,
22097,
16936,
65,
273,
638,
31,
203,
3639,
389,
291,
16461,
1265,
2747,
4188,
63,
2867,
12,
20,
25887,
273,
638,
31,
203,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
389,
3576,
12021,
9334,
389,
88,
5269,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity ^0.4.21;
// File: @gnosis.pm/util-contracts/contracts/Math.sol
/// @title Math library - Allows calculation of logarithmic and exponential functions
/// @author Alan Lu - <[email protected]>
/// @author Stefan George - <[email protected]>
library Math {
/*
* Constants
*/
// This is equal to 1 in our calculations
uint public constant ONE = 0x10000000000000000;
uint public constant LN2 = 0xb17217f7d1cf79ac;
uint public constant LOG2_E = 0x171547652b82fe177;
/*
* Public functions
*/
/// @dev Returns natural exponential function value of given x
/// @param x x
/// @return e**x
function exp(int x)
public
pure
returns (uint)
{
// revert if x is > MAX_POWER, where
// MAX_POWER = int(mp.floor(mp.log(mpf(2**256 - 1) / ONE) * ONE))
require(x <= 2454971259878909886679);
// return 0 if exp(x) is tiny, using
// MIN_POWER = int(mp.floor(mp.log(mpf(1) / ONE) * ONE))
if (x < -818323753292969962227)
return 0;
// Transform so that e^x -> 2^x
x = x * int(ONE) / int(LN2);
// 2^x = 2^whole(x) * 2^frac(x)
// ^^^^^^^^^^ is a bit shift
// so Taylor expand on z = frac(x)
int shift;
uint z;
if (x >= 0) {
shift = x / int(ONE);
z = uint(x % int(ONE));
}
else {
shift = x / int(ONE) - 1;
z = ONE - uint(-x % int(ONE));
}
// 2^x = 1 + (ln 2) x + (ln 2)^2/2! x^2 + ...
//
// Can generate the z coefficients using mpmath and the following lines
// >>> from mpmath import mp
// >>> mp.dps = 100
// >>> ONE = 0x10000000000000000
// >>> print('\n'.join(hex(int(mp.log(2)**i / mp.factorial(i) * ONE)) for i in range(1, 7)))
// 0xb17217f7d1cf79ab
// 0x3d7f7bff058b1d50
// 0xe35846b82505fc5
// 0x276556df749cee5
// 0x5761ff9e299cc4
// 0xa184897c363c3
uint zpow = z;
uint result = ONE;
result += 0xb17217f7d1cf79ab * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x3d7f7bff058b1d50 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xe35846b82505fc5 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x276556df749cee5 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x5761ff9e299cc4 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xa184897c363c3 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xffe5fe2c4586 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x162c0223a5c8 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1b5253d395e * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1e4cf5158b * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1e8cac735 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1c3bd650 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x1816193 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x131496 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0xe1b7 * zpow / ONE;
zpow = zpow * z / ONE;
result += 0x9c7 * zpow / ONE;
if (shift >= 0) {
if (result >> (256-shift) > 0)
return (2**256-1);
return result << shift;
}
else
return result >> (-shift);
}
/// @dev Returns natural logarithm value of given x
/// @param x x
/// @return ln(x)
function ln(uint x)
public
pure
returns (int)
{
require(x > 0);
// binary search for floor(log2(x))
int ilog2 = floorLog2(x);
int z;
if (ilog2 < 0)
z = int(x << uint(-ilog2));
else
z = int(x >> uint(ilog2));
// z = x * 2^-⌊log₂x⌋
// so 1 <= z < 2
// and ln z = ln x - ⌊log₂x⌋/log₂e
// so just compute ln z using artanh series
// and calculate ln x from that
int term = (z - int(ONE)) * int(ONE) / (z + int(ONE));
int halflnz = term;
int termpow = term * term / int(ONE) * term / int(ONE);
halflnz += termpow / 3;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 5;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 7;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 9;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 11;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 13;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 15;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 17;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 19;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 21;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 23;
termpow = termpow * term / int(ONE) * term / int(ONE);
halflnz += termpow / 25;
return (ilog2 * int(ONE)) * int(ONE) / int(LOG2_E) + 2 * halflnz;
}
/// @dev Returns base 2 logarithm value of given x
/// @param x x
/// @return logarithmic value
function floorLog2(uint x)
public
pure
returns (int lo)
{
lo = -64;
int hi = 193;
// I use a shift here instead of / 2 because it floors instead of rounding towards 0
int mid = (hi + lo) >> 1;
while((lo + 1) < hi) {
if (mid < 0 && x << uint(-mid) < ONE || mid >= 0 && x >> uint(mid) < ONE)
hi = mid;
else
lo = mid;
mid = (hi + lo) >> 1;
}
}
/// @dev Returns maximum of an array
/// @param nums Numbers to look through
/// @return Maximum number
function max(int[] nums)
public
pure
returns (int maxNum)
{
require(nums.length > 0);
maxNum = -2**255;
for (uint i = 0; i < nums.length; i++)
if (nums[i] > maxNum)
maxNum = nums[i];
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(uint a, uint b)
internal
pure
returns (bool)
{
return a + b >= a;
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(uint a, uint b)
internal
pure
returns (bool)
{
return a >= b;
}
/// @dev Returns whether a multiply operation causes an overflow
/// @param a First factor
/// @param b Second factor
/// @return Did no overflow occur?
function safeToMul(uint a, uint b)
internal
pure
returns (bool)
{
return b == 0 || a * b / b == a;
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(uint a, uint b)
internal
pure
returns (uint)
{
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(uint a, uint b)
internal
pure
returns (uint)
{
require(safeToSub(a, b));
return a - b;
}
/// @dev Returns product if no overflow occurred
/// @param a First factor
/// @param b Second factor
/// @return Product
function mul(uint a, uint b)
internal
pure
returns (uint)
{
require(safeToMul(a, b));
return a * b;
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(int a, int b)
internal
pure
returns (bool)
{
return (b >= 0 && a + b >= a) || (b < 0 && a + b < a);
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(int a, int b)
internal
pure
returns (bool)
{
return (b >= 0 && a - b <= a) || (b < 0 && a - b > a);
}
/// @dev Returns whether a multiply operation causes an overflow
/// @param a First factor
/// @param b Second factor
/// @return Did no overflow occur?
function safeToMul(int a, int b)
internal
pure
returns (bool)
{
return (b == 0) || (a * b / b == a);
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(int a, int b)
internal
pure
returns (int)
{
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(int a, int b)
internal
pure
returns (int)
{
require(safeToSub(a, b));
return a - b;
}
/// @dev Returns product if no overflow occurred
/// @param a First factor
/// @param b Second factor
/// @return Product
function mul(int a, int b)
internal
pure
returns (int)
{
require(safeToMul(a, b));
return a * b;
}
}
// File: @gnosis.pm/util-contracts/contracts/Proxy.sol
/// @title Proxied - indicates that a contract will be proxied. Also defines storage requirements for Proxy.
/// @author Alan Lu - <[email protected]>
contract Proxied {
address public masterCopy;
}
/// @title Proxy - Generic proxy contract allows to execute all transactions applying the code of a master contract.
/// @author Stefan George - <[email protected]>
contract Proxy is Proxied {
/// @dev Constructor function sets address of master copy contract.
/// @param _masterCopy Master copy address.
function Proxy(address _masterCopy)
public
{
require(_masterCopy != 0);
masterCopy = _masterCopy;
}
/// @dev Fallback function forwards all transactions and returns all received return data.
function ()
external
payable
{
address _masterCopy = masterCopy;
assembly {
calldatacopy(0, 0, calldatasize())
let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch success
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
}
// File: @gnosis.pm/util-contracts/contracts/Token.sol
/// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
pragma solidity ^0.4.21;
/// @title Abstract token contract - Functions to be implemented by token contracts
contract Token {
/*
* Events
*/
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
/*
* Public functions
*/
function transfer(address to, uint value) public returns (bool);
function transferFrom(address from, address to, uint value) public returns (bool);
function approve(address spender, uint value) public returns (bool);
function balanceOf(address owner) public view returns (uint);
function allowance(address owner, address spender) public view returns (uint);
function totalSupply() public view returns (uint);
}
// File: @gnosis.pm/util-contracts/contracts/StandardToken.sol
contract StandardTokenData {
/*
* Storage
*/
mapping (address => uint) balances;
mapping (address => mapping (address => uint)) allowances;
uint totalTokens;
}
/// @title Standard token contract with overflow protection
contract StandardToken is Token, StandardTokenData {
using Math for *;
/*
* Public functions
*/
/// @dev Transfers sender's tokens to a given address. Returns success
/// @param to Address of token receiver
/// @param value Number of tokens to transfer
/// @return Was transfer successful?
function transfer(address to, uint value)
public
returns (bool)
{
if ( !balances[msg.sender].safeToSub(value)
|| !balances[to].safeToAdd(value))
return false;
balances[msg.sender] -= value;
balances[to] += value;
emit Transfer(msg.sender, to, value);
return true;
}
/// @dev Allows allowed third party to transfer tokens from one address to another. Returns success
/// @param from Address from where tokens are withdrawn
/// @param to Address to where tokens are sent
/// @param value Number of tokens to transfer
/// @return Was transfer successful?
function transferFrom(address from, address to, uint value)
public
returns (bool)
{
if ( !balances[from].safeToSub(value)
|| !allowances[from][msg.sender].safeToSub(value)
|| !balances[to].safeToAdd(value))
return false;
balances[from] -= value;
allowances[from][msg.sender] -= value;
balances[to] += value;
emit Transfer(from, to, value);
return true;
}
/// @dev Sets approved amount of tokens for spender. Returns success
/// @param spender Address of allowed account
/// @param value Number of approved tokens
/// @return Was approval successful?
function approve(address spender, uint value)
public
returns (bool)
{
allowances[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/// @dev Returns number of allowed tokens for given address
/// @param owner Address of token owner
/// @param spender Address of token spender
/// @return Remaining allowance for spender
function allowance(address owner, address spender)
public
view
returns (uint)
{
return allowances[owner][spender];
}
/// @dev Returns number of tokens owned by given address
/// @param owner Address of token owner
/// @return Balance of owner
function balanceOf(address owner)
public
view
returns (uint)
{
return balances[owner];
}
/// @dev Returns total supply of tokens
/// @return Total supply
function totalSupply()
public
view
returns (uint)
{
return totalTokens;
}
}
// File: contracts/TokenFRT.sol
/// @title Standard token contract with overflow protection
contract TokenFRT is StandardToken {
string public constant symbol = "MGN";
string public constant name = "Magnolia Token";
uint8 public constant decimals = 18;
struct unlockedToken {
uint amountUnlocked;
uint withdrawalTime;
}
/*
* Storage
*/
address public owner;
address public minter;
// user => unlockedToken
mapping (address => unlockedToken) public unlockedTokens;
// user => amount
mapping (address => uint) public lockedTokenBalances;
/*
* Public functions
*/
function TokenFRT(
address _owner
)
public
{
require(_owner != address(0));
owner = _owner;
}
// @dev allows to set the minter of Magnolia tokens once.
// @param _minter the minter of the Magnolia tokens, should be the DX-proxy
function updateMinter(
address _minter
)
public
{
require(msg.sender == owner);
require(_minter != address(0));
minter = _minter;
}
// @dev the intention is to set the owner as the DX-proxy, once it is deployed
// Then only an update of the DX-proxy contract after a 30 days delay could change the minter again.
function updateOwner(
address _owner
)
public
{
require(msg.sender == owner);
require(_owner != address(0));
owner = _owner;
}
function mintTokens(
address user,
uint amount
)
public
{
require(msg.sender == minter);
lockedTokenBalances[user] = add(lockedTokenBalances[user], amount);
totalTokens = add(totalTokens, amount);
}
/// @dev Lock Token
function lockTokens(
uint amount
)
public
returns (uint totalAmountLocked)
{
// Adjust amount by balance
amount = min(amount, balances[msg.sender]);
// Update state variables
balances[msg.sender] = sub(balances[msg.sender], amount);
lockedTokenBalances[msg.sender] = add(lockedTokenBalances[msg.sender], amount);
// Get return variable
totalAmountLocked = lockedTokenBalances[msg.sender];
}
function unlockTokens(
uint amount
)
public
returns (uint totalAmountUnlocked, uint withdrawalTime)
{
// Adjust amount by locked balances
amount = min(amount, lockedTokenBalances[msg.sender]);
if (amount > 0) {
// Update state variables
lockedTokenBalances[msg.sender] = sub(lockedTokenBalances[msg.sender], amount);
unlockedTokens[msg.sender].amountUnlocked = add(unlockedTokens[msg.sender].amountUnlocked, amount);
unlockedTokens[msg.sender].withdrawalTime = now + 24 hours;
}
// Get return variables
totalAmountUnlocked = unlockedTokens[msg.sender].amountUnlocked;
withdrawalTime = unlockedTokens[msg.sender].withdrawalTime;
}
function withdrawUnlockedTokens()
public
{
require(unlockedTokens[msg.sender].withdrawalTime < now);
balances[msg.sender] = add(balances[msg.sender], unlockedTokens[msg.sender].amountUnlocked);
unlockedTokens[msg.sender].amountUnlocked = 0;
}
function min(uint a, uint b)
public
pure
returns (uint)
{
if (a < b) {
return a;
} else {
return b;
}
}
/// @dev Returns whether an add operation causes an overflow
/// @param a First addend
/// @param b Second addend
/// @return Did no overflow occur?
function safeToAdd(uint a, uint b)
public
constant
returns (bool)
{
return a + b >= a;
}
/// @dev Returns whether a subtraction operation causes an underflow
/// @param a Minuend
/// @param b Subtrahend
/// @return Did no underflow occur?
function safeToSub(uint a, uint b)
public
constant
returns (bool)
{
return a >= b;
}
/// @dev Returns sum if no overflow occurred
/// @param a First addend
/// @param b Second addend
/// @return Sum
function add(uint a, uint b)
public
constant
returns (uint)
{
require(safeToAdd(a, b));
return a + b;
}
/// @dev Returns difference if no overflow occurred
/// @param a Minuend
/// @param b Subtrahend
/// @return Difference
function sub(uint a, uint b)
public
constant
returns (uint)
{
require(safeToSub(a, b));
return a - b;
}
} | @dev Returns whether a subtraction operation causes an underflow @param a Minuend @param b Subtrahend @return Did no underflow occur? | function safeToSub(uint a, uint b)
public
constant
returns (bool)
{
return a >= b;
}
| 613,117 | [
1,
1356,
2856,
279,
720,
25693,
1674,
14119,
392,
3613,
2426,
225,
279,
5444,
89,
409,
225,
324,
2592,
2033,
25710,
327,
21148,
1158,
3613,
2426,
3334,
35,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
4183,
774,
1676,
12,
11890,
279,
16,
2254,
324,
13,
203,
3639,
1071,
203,
3639,
5381,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
327,
279,
1545,
324,
31,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// File: zos-lib/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.6.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
uint256 cs;
assembly { cs := extcodesize(address) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: openzeppelin-eth/contracts/ownership/Ownable.sol
pragma solidity ^0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable is Initializable {
address private _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.
*/
function initialize(address sender) public initializer {
_owner = sender;
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(_owner);
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[50] private ______gap;
}
// File: contracts/lib/SafeMathInt.sol
/*
MIT License
Copyright (c) 2018 requestnetwork
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
pragma solidity >=0.4.24;
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b)
internal
pure
returns (int256)
{
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b)
internal
pure
returns (int256)
{
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a)
internal
pure
returns (int256)
{
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
}
// File: contracts/lib/UInt256Lib.sol
pragma solidity >=0.4.24;
/**
* @title Various utilities useful for uint256.
*/
library UInt256Lib {
uint256 private constant MAX_INT256 = ~(uint256(1) << 255);
/**
* @dev Safely converts a uint256 to an int256.
*/
function toInt256Safe(uint256 a)
internal
pure
returns (int256)
{
require(a <= MAX_INT256);
return int256(a);
}
}
// File: contracts/interface/ISeignorageShares.sol
pragma solidity >=0.4.24;
interface ISeigniorageShares {
function setDividendPoints(address account, uint256 totalDividends) external returns (bool);
function mintShares(address account, uint256 amount) external returns (bool);
function lastDividendPoints(address who) external view returns (uint256);
function externalRawBalanceOf(address who) external view returns (uint256);
function externalTotalSupply() external view returns (uint256);
}
// File: openzeppelin-eth/contracts/math/SafeMath.sol
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, 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 numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts 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 Subtracts two numbers, 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 numbers, 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 numbers 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;
}
}
// File: openzeppelin-eth/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-eth/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.4.24;
/**
* @title ERC20Detailed token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract ERC20Detailed is Initializable, IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
function initialize(string name, string symbol, uint8 decimals) public initializer {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @return the name of the token.
*/
function name() public view returns(string) {
return _name;
}
/**
* @return the symbol of the token.
*/
function symbol() public view returns(string) {
return _symbol;
}
/**
* @return the number of decimals of the token.
*/
function decimals() public view returns(uint8) {
return _decimals;
}
uint256[50] private ______gap;
}
// File: contracts/dollars.sol
pragma solidity >=0.4.24;
interface IDollarPolicy {
function getUsdSharePrice() external view returns (uint256 price);
}
/*
* Dollar ERC20
*/
contract Dollars is ERC20Detailed, Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
event LogRebase(uint256 indexed epoch, uint256 totalSupply);
event LogContraction(uint256 indexed epoch, uint256 dollarsToBurn);
event LogRebasePaused(bool paused);
event LogBurn(address indexed from, uint256 value);
event LogClaim(address indexed from, uint256 value);
event LogMonetaryPolicyUpdated(address monetaryPolicy);
// Used for authentication
address public monetaryPolicy;
address public sharesAddress;
modifier onlyMonetaryPolicy() {
require(msg.sender == monetaryPolicy);
_;
}
// Precautionary emergency controls.
bool public rebasePaused;
modifier whenRebaseNotPaused() {
require(!rebasePaused);
_;
}
// coins needing to be burned (9 decimals)
uint256 private _remainingDollarsToBeBurned;
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
uint256 private constant DECIMALS = 9;
uint256 private constant MAX_UINT256 = ~uint256(0);
uint256 private constant INITIAL_DOLLAR_SUPPLY = 1 * 10**6 * 10**DECIMALS;
uint256 private _maxDiscount;
modifier validDiscount(uint256 discount) {
require(discount >= 0, 'POSITIVE_DISCOUNT'); // 0%
require(discount <= _maxDiscount, 'DISCOUNT_TOO_HIGH');
_;
}
uint256 private constant MAX_SUPPLY = ~uint128(0); // (2^128) - 1
uint256 private _totalSupply;
uint256 private constant POINT_MULTIPLIER = 10 ** 9;
uint256 private _totalDividendPoints;
uint256 private _unclaimedDividends;
ISeigniorageShares Shares;
mapping(address => uint256) private _dollarBalances;
// This is denominated in Dollars, because the cents-dollars conversion might change before
// it's fully paid.
mapping (address => mapping (address => uint256)) private _allowedDollars;
IDollarPolicy DollarPolicy;
uint256 public burningDiscount; // percentage (10 ** 9 Decimals)
uint256 public defaultDiscount; // discount on first negative rebase
uint256 public defaultDailyBonusDiscount; // how much the discount increases per day for consecutive contractions
uint256 public minimumBonusThreshold;
bool reEntrancyMutex;
/**
* @param monetaryPolicy_ The address of the monetary policy contract to use for authentication.
*/
function setMonetaryPolicy(address monetaryPolicy_)
external
onlyOwner
{
monetaryPolicy = monetaryPolicy_;
DollarPolicy = IDollarPolicy(monetaryPolicy_);
emit LogMonetaryPolicyUpdated(monetaryPolicy_);
}
function setBurningDiscount(uint256 discount)
external
onlyOwner
validDiscount(discount)
{
burningDiscount = discount;
}
function setMutex(bool _val) external onlyOwner {
reEntrancyMutex = _val;
}
function setDefaultDiscount(uint256 discount)
external
onlyOwner
validDiscount(discount)
{
defaultDiscount = discount;
}
function setMaxDiscount(uint256 discount)
external
onlyOwner
{
_maxDiscount = discount;
}
function setDefaultDailyBonusDiscount(uint256 discount)
external
onlyOwner
validDiscount(discount)
{
defaultDailyBonusDiscount = discount;
}
/**
* @dev Pauses or unpauses the execution of rebase operations.
* @param paused Pauses rebase operations if this is true.
*/
function setRebasePaused(bool paused)
external
onlyOwner
{
rebasePaused = paused;
emit LogRebasePaused(paused);
}
// action of claiming funds
function claimDividends(address account) external updateAccount(account) returns (uint256) {
uint256 owing = dividendsOwing(account);
return owing;
}
function setMinimumBonusThreshold(uint256 minimum)
external
onlyOwner
{
require(minimum >= 0, 'POSITIVE_MINIMUM');
require(minimum < _totalSupply, 'MINIMUM_TOO_HIGH');
minimumBonusThreshold = minimum;
}
/**
* @dev Notifies Dollars contract about a new rebase cycle.
* @param supplyDelta The number of new dollar tokens to add into circulation via expansion.
* @return The total number of dollars after the supply adjustment.
*/
function rebase(uint256 epoch, int256 supplyDelta)
external
onlyMonetaryPolicy
whenRebaseNotPaused
returns (uint256)
{
if (supplyDelta == 0) {
emit LogRebase(epoch, _totalSupply);
return _totalSupply;
}
if (supplyDelta < 0) {
uint256 dollarsToBurn = uint256(supplyDelta.abs());
if (dollarsToBurn > _totalSupply.div(10)) { // maximum contraction is 10% of the total USD Supply
dollarsToBurn = _totalSupply.div(10);
}
if (dollarsToBurn.add(_remainingDollarsToBeBurned) > _totalSupply) {
dollarsToBurn = _totalSupply.sub(_remainingDollarsToBeBurned);
}
if (_remainingDollarsToBeBurned > minimumBonusThreshold) {
burningDiscount = burningDiscount.add(defaultDailyBonusDiscount) > _maxDiscount ?
_maxDiscount : burningDiscount.add(defaultDailyBonusDiscount);
} else {
burningDiscount = defaultDiscount; // default 1%
}
_remainingDollarsToBeBurned = _remainingDollarsToBeBurned.add(dollarsToBurn);
emit LogContraction(epoch, dollarsToBurn);
} else {
disburse(uint256(supplyDelta));
emit LogRebase(epoch, _totalSupply);
if (_totalSupply > MAX_SUPPLY) {
_totalSupply = MAX_SUPPLY;
}
}
return _totalSupply;
}
function initialize(address owner_, address seigniorageAddress)
public
initializer
{
ERC20Detailed.initialize("Dollars", "USD", uint8(DECIMALS));
Ownable.initialize(owner_);
rebasePaused = false;
_totalSupply = INITIAL_DOLLAR_SUPPLY;
sharesAddress = seigniorageAddress;
Shares = ISeigniorageShares(seigniorageAddress);
_dollarBalances[owner_] = _totalSupply;
_maxDiscount = 50 * 10 ** 9; // 50%
defaultDiscount = 1 * 10 ** 9; // 1%
burningDiscount = defaultDiscount;
defaultDailyBonusDiscount = 1 * 10 ** 9; // 1%
minimumBonusThreshold = 100 * 10 ** 9; // 100 dollars is the minimum threshold. Anything above warrants increased discount
emit Transfer(address(0x0), owner_, _totalSupply);
}
function dividendsOwing(address account) public view returns (uint256) {
if (_totalDividendPoints > Shares.lastDividendPoints(account)) {
uint256 newDividendPoints = _totalDividendPoints.sub(Shares.lastDividendPoints(account));
uint256 sharesBalance = Shares.externalRawBalanceOf(account);
return sharesBalance.mul(newDividendPoints).div(POINT_MULTIPLIER);
} else {
return 0;
}
}
// auto claim modifier
// if user is owned, we pay out immedietly
// if user is not owned, we prevent them from claiming until the next rebase
modifier updateAccount(address account) {
require(!reEntrancyMutex);
reEntrancyMutex = true;
uint256 owing = dividendsOwing(account);
if (owing > 0) {
_unclaimedDividends = _unclaimedDividends.sub(owing);
_dollarBalances[account] += owing;
}
Shares.setDividendPoints(account, _totalDividendPoints);
reEntrancyMutex = false;
emit LogClaim(account, owing);
_;
}
/**
* @return The total number of dollars.
*/
function totalSupply()
public
view
returns (uint256)
{
return _totalSupply;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
public
view
returns (uint256)
{
return _dollarBalances[who].add(dividendsOwing(who));
}
function getRemainingDollarsToBeBurned()
public
view
returns (uint256)
{
return _remainingDollarsToBeBurned;
}
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
public
validRecipient(to)
updateAccount(msg.sender)
updateAccount(to)
returns (bool)
{
_dollarBalances[msg.sender] = _dollarBalances[msg.sender].sub(value);
_dollarBalances[to] = _dollarBalances[to].add(value);
emit Transfer(msg.sender, to, value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
public
view
returns (uint256)
{
return _allowedDollars[owner_][spender];
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
public
validRecipient(to)
updateAccount(from)
updateAccount(msg.sender)
updateAccount(to)
returns (bool)
{
_allowedDollars[from][msg.sender] = _allowedDollars[from][msg.sender].sub(value);
_dollarBalances[from] = _dollarBalances[from].sub(value);
_dollarBalances[to] = _dollarBalances[to].add(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. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @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
validRecipient(spender)
updateAccount(msg.sender)
updateAccount(spender)
returns (bool)
{
_allowedDollars[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
updateAccount(msg.sender)
updateAccount(spender)
returns (bool)
{
_allowedDollars[msg.sender][spender] =
_allowedDollars[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedDollars[msg.sender][spender]);
return true;
}
// amount in is 10 ** 9 decimals
function burn(uint256 amount) public updateAccount(msg.sender) {
require(amount > 0, 'AMOUNT_MUST_BE_POSITIVE');
require(burningDiscount >= 0, 'DISCOUNT_NOT_VALID');
require(_remainingDollarsToBeBurned > 0, 'COIN_BURN_MUST_BE_GREATER_THAN_ZERO');
require(amount <= _dollarBalances[msg.sender], 'INSUFFICIENT_DOLLAR_BALANCE');
require(amount <= _remainingDollarsToBeBurned, 'AMOUNT_MUST_BE_LESS_THAN_OR_EQUAL_TO_REMAINING_COINS');
_burn(msg.sender, amount);
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
updateAccount(spender)
updateAccount(msg.sender)
returns (bool)
{
uint256 oldValue = _allowedDollars[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedDollars[msg.sender][spender] = 0;
} else {
_allowedDollars[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedDollars[msg.sender][spender]);
return true;
}
function consultBurn(uint256 amount)
public
returns (uint256)
{
require(amount > 0, 'AMOUNT_MUST_BE_POSITIVE');
require(burningDiscount >= 0, 'DISCOUNT_NOT_VALID');
require(_remainingDollarsToBeBurned > 0, 'COIN_BURN_MUST_BE_GREATER_THAN_ZERO');
require(amount <= _dollarBalances[msg.sender].add(dividendsOwing(msg.sender)), 'INSUFFICIENT_DOLLAR_BALANCE');
require(amount <= _remainingDollarsToBeBurned, 'AMOUNT_MUST_BE_LESS_THAN_OR_EQUAL_TO_REMAINING_COINS');
uint256 usdPerShare = DollarPolicy.getUsdSharePrice(); // 1 share = x dollars
usdPerShare = usdPerShare.sub(usdPerShare.mul(burningDiscount).div(100 * 10 ** 9)); // 10^9
uint256 sharesToMint = amount.mul(10 ** 9).div(usdPerShare); // 10^9
return sharesToMint;
}
function unclaimedDividends()
public
view
returns (uint256)
{
return _unclaimedDividends;
}
function totalDividendPoints()
public
view
returns (uint256)
{
return _totalDividendPoints;
}
function disburse(uint256 amount) internal returns (bool) {
_totalDividendPoints = _totalDividendPoints.add(amount.mul(POINT_MULTIPLIER).div(Shares.externalTotalSupply()));
_totalSupply = _totalSupply.add(amount);
_unclaimedDividends = _unclaimedDividends.add(amount);
return true;
}
function _burn(address account, uint256 amount)
internal
{
require(!reEntrancyMutex);
_totalSupply = _totalSupply.sub(amount);
_dollarBalances[account] = _dollarBalances[account].sub(amount);
reEntrancyMutex = true;
uint256 usdPerShare = DollarPolicy.getUsdSharePrice(); // 1 share = x dollars
usdPerShare = usdPerShare.sub(usdPerShare.mul(burningDiscount).div(100 * 10 ** 9)); // 10^9
uint256 sharesToMint = amount.mul(10 ** 9).div(usdPerShare); // 10^9
Shares.mintShares(account, sharesToMint);
_remainingDollarsToBeBurned = _remainingDollarsToBeBurned.sub(amount);
reEntrancyMutex = false;
emit Transfer(account, address(0), amount);
emit LogBurn(account, amount);
}
}
// File: contracts/dollarsPolicy.sol
pragma solidity >=0.4.24;
/*
* Dollar Policy
*/
interface IDecentralizedOracle {
function update() external;
function consult(address token, uint amountIn) external view returns (uint amountOut);
}
contract DollarsPolicy is Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
using UInt256Lib for uint256;
event LogRebase(
uint256 indexed epoch,
uint256 exchangeRate,
uint256 cpi,
int256 requestedSupplyAdjustment,
uint256 timestampSec
);
Dollars public dollars;
// Provides the current CPI, as an 18 decimal fixed point number.
IDecentralizedOracle public sharesPerUsdOracle;
IDecentralizedOracle public ethPerUsdOracle;
IDecentralizedOracle public ethPerUsdcOracle;
uint256 public deviationThreshold;
uint256 public rebaseLag;
uint256 private cpi;
uint256 public minRebaseTimeIntervalSec;
uint256 public lastRebaseTimestampSec;
uint256 public rebaseWindowOffsetSec;
uint256 public rebaseWindowLengthSec;
uint256 public epoch;
address WETH_ADDRESS;
address SHARE_ADDRESS;
uint256 private constant DECIMALS = 18;
uint256 private constant MAX_RATE = 10**6 * 10**DECIMALS;
uint256 private constant MAX_SUPPLY = ~(uint256(1) << 255) / MAX_RATE;
address public orchestrator;
bool private initializedOracle;
modifier onlyOrchestrator() {
require(msg.sender == orchestrator);
_;
}
function getUsdSharePrice() external view returns (uint256) {
sharesPerUsdOracle.update();
uint256 sharePrice = sharesPerUsdOracle.consult(SHARE_ADDRESS, 1 * 10 ** 9); // 10^9 decimals
return sharePrice;
}
function rebase() external onlyOrchestrator {
require(inRebaseWindow());
require(initializedOracle == true, 'ORACLE_NOT_INITIALIZED');
require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) < now);
lastRebaseTimestampSec = now.sub(
now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec);
epoch = epoch.add(1);
sharesPerUsdOracle.update();
ethPerUsdOracle.update();
ethPerUsdcOracle.update();
uint256 ethUsdcPrice = ethPerUsdcOracle.consult(WETH_ADDRESS, 1 * 10 ** 18); // 10^18 decimals ropsten, 10^6 mainnet
uint256 ethUsdPrice = ethPerUsdOracle.consult(WETH_ADDRESS, 1 * 10 ** 18); // 10^9 decimals
uint256 dollarCoinExchangeRate = ethUsdcPrice.mul(10 ** 21) // 10^18 decimals, 10**9 ropsten, 10**21 on mainnet
.div(ethUsdPrice);
uint256 sharePrice = sharesPerUsdOracle.consult(SHARE_ADDRESS, 1 * 10 ** 9); // 10^9 decimals
uint256 shareExchangeRate = sharePrice.mul(dollarCoinExchangeRate).div(10 ** 9); // 10^18 decimals
uint256 targetRate = cpi;
if (dollarCoinExchangeRate > MAX_RATE) {
dollarCoinExchangeRate = MAX_RATE;
}
// dollarCoinExchangeRate & targetRate arre 10^18 decimals
int256 supplyDelta = computeSupplyDelta(dollarCoinExchangeRate, targetRate); // supplyDelta = 10^9 decimals
// Apply the Dampening factor.
supplyDelta = supplyDelta.div(rebaseLag.toInt256Safe());
// check on the expansionary side
if (supplyDelta > 0 && dollars.totalSupply().add(uint256(supplyDelta)) > MAX_SUPPLY) {
supplyDelta = (MAX_SUPPLY.sub(dollars.totalSupply())).toInt256Safe();
}
// check on the contraction side
if (supplyDelta < 0 && dollars.getRemainingDollarsToBeBurned().add(uint256(supplyDelta.abs())) > MAX_SUPPLY) {
supplyDelta = (MAX_SUPPLY.sub(dollars.getRemainingDollarsToBeBurned())).toInt256Safe();
}
uint256 supplyAfterRebase;
if (supplyDelta < 0) { // contraction, we send the amount of shares to mint
uint256 sharesToMint = uint256(supplyDelta.abs());
supplyAfterRebase = dollars.rebase(epoch, (sharesToMint).toInt256Safe().mul(-1));
} else { // expansion, we send the amount of dollars to mint
supplyAfterRebase = dollars.rebase(epoch, supplyDelta);
}
assert(supplyAfterRebase <= MAX_SUPPLY);
emit LogRebase(epoch, dollarCoinExchangeRate, cpi, supplyDelta, now);
}
function setOrchestrator(address orchestrator_)
external
onlyOwner
{
orchestrator = orchestrator_;
}
function setDeviationThreshold(uint256 deviationThreshold_)
external
onlyOwner
{
deviationThreshold = deviationThreshold_;
}
function setCpi(uint256 cpi_)
external
onlyOwner
{
require(cpi_ > 0);
cpi = cpi_;
}
function setRebaseLag(uint256 rebaseLag_)
external
onlyOwner
{
require(rebaseLag_ > 0);
rebaseLag = rebaseLag_;
}
function initializeOracles(
address sharesPerUsdOracleAddress,
address ethPerUsdOracleAddress,
address ethPerUsdcOracleAddress
) external onlyOwner {
require(initializedOracle == false, 'ALREADY_INITIALIZED_ORACLE');
sharesPerUsdOracle = IDecentralizedOracle(sharesPerUsdOracleAddress);
ethPerUsdOracle = IDecentralizedOracle(ethPerUsdOracleAddress);
ethPerUsdcOracle = IDecentralizedOracle(ethPerUsdcOracleAddress);
initializedOracle = true;
}
function changeOracles(
address sharesPerUsdOracleAddress,
address ethPerUsdOracleAddress,
address ethPerUsdcOracleAddress
) external onlyOwner {
sharesPerUsdOracle = IDecentralizedOracle(sharesPerUsdOracleAddress);
ethPerUsdOracle = IDecentralizedOracle(ethPerUsdOracleAddress);
ethPerUsdcOracle = IDecentralizedOracle(ethPerUsdcOracleAddress);
}
function setWethAddress(address wethAddress)
external
onlyOwner
{
WETH_ADDRESS = wethAddress;
}
function setShareAddress(address shareAddress)
external
onlyOwner
{
SHARE_ADDRESS = shareAddress;
}
function setRebaseTimingParameters(
uint256 minRebaseTimeIntervalSec_,
uint256 rebaseWindowOffsetSec_,
uint256 rebaseWindowLengthSec_)
external
onlyOwner
{
require(minRebaseTimeIntervalSec_ > 0);
require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_);
minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_;
rebaseWindowOffsetSec = rebaseWindowOffsetSec_;
rebaseWindowLengthSec = rebaseWindowLengthSec_;
}
function initialize(address owner_, Dollars dollars_)
public
initializer
{
Ownable.initialize(owner_);
deviationThreshold = 5 * 10 ** (DECIMALS-2);
rebaseLag = 50;
minRebaseTimeIntervalSec = 1 days;
rebaseWindowOffsetSec = 63000; // with stock market, 63000 for 1:30pm EST (debug)
rebaseWindowLengthSec = 15 minutes;
lastRebaseTimestampSec = 0;
cpi = 1 * 10 ** 18;
epoch = 0;
dollars = dollars_;
}
function inRebaseWindow() public view returns (bool) {
return (
now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec &&
now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec))
);
}
function computeSupplyDelta(uint256 rate, uint256 targetRate)
private
view
returns (int256)
{
if (withinDeviationThreshold(rate, targetRate)) {
return 0;
}
int256 targetRateSigned = targetRate.toInt256Safe();
return dollars.totalSupply().toInt256Safe()
.mul(rate.toInt256Safe().sub(targetRateSigned))
.div(targetRateSigned);
}
function withinDeviationThreshold(uint256 rate, uint256 targetRate)
private
view
returns (bool)
{
uint256 absoluteDeviationThreshold = targetRate.mul(deviationThreshold)
.div(10 ** DECIMALS);
return (rate >= targetRate && rate.sub(targetRate) < absoluteDeviationThreshold)
|| (rate < targetRate && targetRate.sub(rate) < absoluteDeviationThreshold);
}
}
// File: contracts/orchestrator.sol
pragma solidity >=0.4.24;
/*
* Orchestrator
*/
contract Orchestrator is Ownable {
struct Transaction {
bool enabled;
address destination;
bytes data;
}
event TransactionFailed(address indexed destination, uint index, bytes data);
Transaction[] public transactions;
DollarsPolicy public policy;
constructor(address policy_) public {
Ownable.initialize(msg.sender);
policy = DollarsPolicy(policy_);
}
function rebase()
external
{
require(msg.sender == tx.origin); // solhint-disable-line avoid-tx-origin
policy.rebase();
for (uint i = 0; i < transactions.length; i++) {
Transaction storage t = transactions[i];
if (t.enabled) {
bool result =
externalCall(t.destination, t.data);
if (!result) {
emit TransactionFailed(t.destination, i, t.data);
revert("Transaction Failed");
}
}
}
}
function addTransaction(address destination, bytes data)
external
onlyOwner
{
transactions.push(Transaction({
enabled: true,
destination: destination,
data: data
}));
}
function removeTransaction(uint index)
external
onlyOwner
{
require(index < transactions.length, "index out of bounds");
if (index < transactions.length - 1) {
transactions[index] = transactions[transactions.length - 1];
}
transactions.length--;
}
function setTransactionEnabled(uint index, bool enabled)
external
onlyOwner
{
require(index < transactions.length, "index must be in range of stored tx list");
transactions[index].enabled = enabled;
}
function transactionsSize()
external
view
returns (uint256)
{
return transactions.length;
}
function externalCall(address destination, bytes data)
internal
returns (bool)
{
bool result;
assembly { // solhint-disable-line no-inline-assembly
// "Allocate" memory for output
// (0x40 is where "free memory" pointer is stored by convention)
let outputAddress := mload(0x40)
// First 32 bytes are the padded length of data, so exclude that
let dataAddress := add(data, 32)
result := call(
// 34710 is the value that solidity is currently emitting
// It includes callGas (700) + callVeryLow (3, to pay for SUB)
// + callValueTransferGas (9000) + callNewAccountGas
// (25000, in case the destination address does not exist and needs creating)
sub(gas, 34710),
destination,
0, // transfer value in wei
dataAddress,
mload(data), // Size of the input, in bytes. Stored in position 0 of the array.
outputAddress,
0 // Output is ignored, therefore the output size is zero
)
}
return result;
}
} | auto claim modifier if user is owned, we pay out immedietly if user is not owned, we prevent them from claiming until the next rebase | modifier updateAccount(address account) {
require(!reEntrancyMutex);
reEntrancyMutex = true;
uint256 owing = dividendsOwing(account);
if (owing > 0) {
_unclaimedDividends = _unclaimedDividends.sub(owing);
_dollarBalances[account] += owing;
}
Shares.setDividendPoints(account, _totalDividendPoints);
reEntrancyMutex = false;
emit LogClaim(account, owing);
_;
}
| 434,482 | [
1,
6079,
7516,
9606,
309,
729,
353,
16199,
16,
732,
8843,
596,
709,
5660,
278,
715,
309,
729,
353,
486,
16199,
16,
732,
5309,
2182,
628,
7516,
310,
3180,
326,
1024,
283,
1969,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
9606,
1089,
3032,
12,
2867,
2236,
13,
288,
203,
3639,
2583,
12,
5,
266,
664,
313,
12514,
11433,
1769,
203,
3639,
283,
664,
313,
12514,
11433,
273,
638,
31,
203,
203,
3639,
2254,
5034,
2523,
310,
273,
3739,
350,
5839,
3494,
310,
12,
4631,
1769,
203,
203,
3639,
309,
261,
543,
310,
405,
374,
13,
288,
203,
5411,
389,
551,
80,
4581,
329,
7244,
350,
5839,
273,
389,
551,
80,
4581,
329,
7244,
350,
5839,
18,
1717,
12,
543,
310,
1769,
203,
5411,
389,
72,
25442,
38,
26488,
63,
4631,
65,
1011,
2523,
310,
31,
203,
3639,
289,
203,
203,
3639,
2638,
4807,
18,
542,
7244,
26746,
5636,
12,
4631,
16,
389,
4963,
7244,
26746,
5636,
1769,
203,
203,
3639,
283,
664,
313,
12514,
11433,
273,
629,
31,
203,
203,
3639,
3626,
1827,
9762,
12,
4631,
16,
2523,
310,
1769,
203,
3639,
389,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/4/0x58096551Cc8B648d31Aa4A67968677625cE5d844/sources/LOAD.sol | never guessdo nothing | function addGuess(uint coin) internal {
uint today = block.timestamp.div(divdDuration).add(1);
checkMigrate();
}else
| 8,532,841 | [
1,
4644,
502,
7274,
2896,
5083,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
527,
15977,
12,
11890,
13170,
13,
2713,
288,
203,
3639,
2254,
10074,
273,
1203,
18,
5508,
18,
2892,
12,
2892,
72,
5326,
2934,
1289,
12,
21,
1769,
203,
3639,
866,
19594,
5621,
203,
5411,
289,
12107,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/56/0x6449Cb6c9F8978a8C4AB92D636169EDe2a7Fcd0F/sources/Lampion.sol | * @dev See {LAMP-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {LAMP}; Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for `sender`'s tokens of at least `amount`./ | function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "LAMP: transfer amount exceeds allowance"));
return true;
}
| 11,236,016 | [
1,
9704,
288,
48,
8900,
17,
13866,
1265,
5496,
7377,
1282,
392,
288,
23461,
97,
871,
11193,
326,
3526,
1699,
1359,
18,
1220,
353,
486,
1931,
635,
326,
512,
2579,
18,
2164,
326,
4721,
622,
326,
8435,
434,
288,
48,
8900,
20451,
29076,
30,
300,
1375,
15330,
68,
471,
1375,
20367,
68,
2780,
506,
326,
3634,
1758,
18,
300,
1375,
15330,
68,
1297,
1240,
279,
11013,
434,
622,
4520,
1375,
8949,
8338,
300,
326,
4894,
1297,
1240,
1699,
1359,
364,
1375,
15330,
11294,
87,
2430,
434,
622,
4520,
1375,
8949,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
7412,
1265,
12,
2867,
5793,
16,
1758,
8027,
16,
2254,
5034,
3844,
13,
3903,
1135,
261,
6430,
13,
288,
203,
565,
389,
13866,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
565,
389,
12908,
537,
12,
15330,
16,
389,
3576,
12021,
9334,
389,
5965,
6872,
63,
15330,
6362,
67,
3576,
12021,
1435,
8009,
1717,
12,
8949,
16,
315,
48,
8900,
30,
7412,
3844,
14399,
1699,
1359,
7923,
1769,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title IERC1155 Non-Fungible Token Creator basic interface
*/
interface IERC1155TokenCreator {
/**
* @dev Gets the creator of the token
* @param _tokenId uint256 ID of the token
* @return address of the creator
*/
function tokenCreator(uint256 _tokenId)
external
view
returns (address payable);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @dev Interface for interacting with the Nafter contract that holds Nafter beta tokens.
*/
interface INafter {
/**
* @dev Gets the creator of the token
* @param _tokenId uint256 ID of the token
* @return address of the creator
*/
function creatorOfToken(uint256 _tokenId)
external
view
returns (address payable);
/**
* @dev Gets the Service Fee
* @param _tokenId uint256 ID of the token
* @return address of the creator
*/
function getServiceFee(uint256 _tokenId)
external
view
returns (uint8);
/**
* @dev Gets the price type
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
* @return get the price type
*/
function getPriceType(uint256 _tokenId, address _owner)
external
view
returns (uint8);
/**
* @dev update price only from auction.
* @param _price price of the token
* @param _tokenId uint256 id of the token.
* @param _owner address of the token owner
*/
function setPrice(uint256 _price, uint256 _tokenId, address _owner) external;
/**
* @dev update bids only from auction.
* @param _bid bid Amount
* @param _bidder bidder address
* @param _tokenId uint256 id of the token.
* @param _owner address of the token owner
*/
function setBid(uint256 _bid, address _bidder, uint256 _tokenId, address _owner) external;
/**
* @dev remove token from sale
* @param _tokenId uint256 id of the token.
* @param _owner owner of the token
*/
function removeFromSale(uint256 _tokenId, address _owner) external;
/**
* @dev get tokenIds length
*/
function getTokenIdsLength() external view returns (uint256);
/**
* @dev get token Id
* @param _index uint256 index
*/
function getTokenId(uint256 _index) external view returns (uint256);
/**
* @dev Gets the owners
* @param _tokenId uint256 ID of the token
*/
function getOwners(uint256 _tokenId)
external
view
returns (address[] memory owners);
/**
* @dev Gets the is for sale
* @param _tokenId uint256 ID of the token
* @param _owner address of the token owner
*/
function getIsForSale(uint256 _tokenId, address _owner) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./IERC1155TokenCreator.sol";
/**
* @title IERC1155CreatorRoyalty Token level royalty interface.
*/
interface INafterRoyaltyRegistry is IERC1155TokenCreator {
/**
* @dev Get the royalty fee percentage for a specific ERC1155 contract.
* @param _tokenId uint256 token ID.
* @return uint8 wei royalty fee.
*/
function getTokenRoyaltyPercentage(
uint256 _tokenId
) external view returns (uint8);
/**
* @dev Utililty function to calculate the royalty fee for a token.
* @param _tokenId uint256 token ID.
* @param _amount uint256 wei amount.
* @return uint256 wei fee.
*/
function calculateRoyaltyFee(
uint256 _tokenId,
uint256 _amount
) external view returns (uint256);
/**
* @dev Sets the royalty percentage set for an Nafter token
* Requirements:
* - `_percentage` must be <= 100.
* - only the owner of this contract or the creator can call this method.
* @param _tokenId uint256 token ID.
* @param _percentage uint8 wei royalty fee.
*/
function setPercentageForTokenRoyalty(
uint256 _tokenId,
uint8 _percentage
) external returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/**
* @title IERC721 Non-Fungible Token Creator basic interface
*/
interface INafterTokenCreatorRegistry {
/**
* @dev Gets the creator of the token
* @param _tokenId uint256 ID of the token
* @return address of the creator
*/
function tokenCreator(uint256 _tokenId)
external
view
returns (address payable);
/**
* @dev Sets the creator of the token
* @param _tokenId uint256 ID of the token
* @param _creator address of the creator for the token
*/
function setTokenCreator(
uint256 _tokenId,
address payable _creator
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./INafterRoyaltyRegistry.sol";
import "./INafterTokenCreatorRegistry.sol";
import "./INafter.sol";
/**
* @title IERC1155 Non-Fungible Token Creator basic interface
*/
contract NafterTokenCreatorRegistry is Ownable, INafterTokenCreatorRegistry {
using SafeMath for uint256;
/////////////////////////////////////////////////////////////////////////
// State Variables
/////////////////////////////////////////////////////////////////////////
// Mapping of ERC1155 token to it's creator.
mapping(uint256 => address payable)
private tokenCreators;
address public nafter;
/////////////////////////////////////////////////////////////////////////
// tokenCreator
/////////////////////////////////////////////////////////////////////////
/**
* @dev Gets the creator of the token
* @param _tokenId uint256 ID of the token
* @return address of the creator
*/
function tokenCreator(uint256 _tokenId)
external
view
override
returns (address payable)
{
if (tokenCreators[_tokenId] != address(0)) {
return tokenCreators[_tokenId];
}
return address(0);
}
/////////////////////////////////////////////////////////////////////////
// setNafter
/////////////////////////////////////////////////////////////////////////
/**
* @dev Set nafter contract address
* @param _nafter uint256 ID of the token
*/
function setNafter(address _nafter) external onlyOwner {
nafter = _nafter;
}
/////////////////////////////////////////////////////////////////////////
// setTokenCreator
/////////////////////////////////////////////////////////////////////////
/**
* @dev Sets the creator of the token
* @param _tokenId uint256 ID of the token
* @param _creator address of the creator for the token
*/
function setTokenCreator(
uint256 _tokenId,
address payable _creator
) external override {
require(
_creator != address(0),
"setTokenCreator::Cannot set null address as creator"
);
require(msg.sender == nafter || msg.sender == owner(), "setTokenCreator::only nafter and owner allowed");
tokenCreators[_tokenId] = _creator;
}
/**
* @dev restore data from old contract, only call by owner
* @param _oldAddress address of old contract.
* @param _oldNafterAddress get the token ids from the old nafter contract.
* @param _startIndex start index of array
* @param _endIndex end index of array
*/
function restore(address _oldAddress, address _oldNafterAddress, uint256 _startIndex, uint256 _endIndex) external onlyOwner {
NafterTokenCreatorRegistry oldContract = NafterTokenCreatorRegistry(_oldAddress);
INafter oldNafterContract = INafter(_oldNafterAddress);
uint256 length = oldNafterContract.getTokenIdsLength();
require(_startIndex < length, "wrong start index");
require(_endIndex <= length, "wrong end index");
for (uint i = _startIndex; i < _endIndex; i++) {
uint256 tokenId = oldNafterContract.getTokenId(i);
if (tokenCreators[tokenId] != address(0)) {
tokenCreators[tokenId] = oldContract.tokenCreator(tokenId);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev 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;
}
}
| * @title IERC721 Non-Fungible Token Creator basic interface/ | interface INafterTokenCreatorRegistry {
function tokenCreator(uint256 _tokenId)
external
view
returns (address payable);
function setTokenCreator(
uint256 _tokenId,
address payable _creator
) external;
}
}
| 13,867,897 | [
1,
45,
654,
39,
27,
5340,
3858,
17,
42,
20651,
1523,
3155,
29525,
5337,
1560,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
5831,
2120,
5205,
1345,
10636,
4243,
288,
203,
565,
445,
1147,
10636,
12,
11890,
5034,
389,
2316,
548,
13,
203,
565,
3903,
203,
565,
1476,
203,
565,
1135,
261,
2867,
8843,
429,
1769,
203,
203,
565,
445,
22629,
10636,
12,
203,
3639,
2254,
5034,
389,
2316,
548,
16,
203,
3639,
1758,
8843,
429,
389,
20394,
203,
565,
262,
3903,
31,
203,
97,
203,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/3/0xCa7D3968Ab18aaEC68FAf3E3BCF0F743dDe41FA2/sources/browser/contracts/MyContract.sol | uint256 amountTobuy = msg.value; | function buy(address from, uint256 amountTobuy) payable public {
require(amountTobuy > 0, "You need to send some Ether");
uint256 dexBalance = token.balanceOf(from);
require(amountTobuy <= dexBalance, "Not enough tokens in the reserve");
token.transferFrom(from, msg.sender, amountTobuy);
emit Bought(amountTobuy);
}
| 8,180,493 | [
1,
11890,
5034,
3844,
774,
70,
9835,
273,
1234,
18,
1132,
31,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
30143,
12,
2867,
628,
16,
2254,
5034,
3844,
774,
70,
9835,
13,
8843,
429,
1071,
288,
203,
3639,
2583,
12,
8949,
774,
70,
9835,
405,
374,
16,
315,
6225,
1608,
358,
1366,
2690,
512,
1136,
8863,
203,
3639,
2254,
5034,
302,
338,
13937,
273,
1147,
18,
12296,
951,
12,
2080,
1769,
203,
3639,
2583,
12,
8949,
774,
70,
9835,
1648,
302,
338,
13937,
16,
315,
1248,
7304,
2430,
316,
326,
20501,
8863,
203,
3639,
1147,
18,
13866,
1265,
12,
2080,
16,
1234,
18,
15330,
16,
3844,
774,
70,
9835,
1769,
203,
3639,
3626,
17980,
9540,
12,
8949,
774,
70,
9835,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./full_match/80001/0xF120b7f6d7D9E57A905FFe5D6d6d92bd0cbDE0a8/sources/project_/con2/SyntheticToken/ERC1363.sol | * @dev Transfer tokens from one address to another and then execute a callback on `to`. @param from The address which you want to send tokens from @param to The address which you want to transfer to @param amount The amount of tokens to be transferred @param data Additional data with no specified format @return A boolean that indicates if the operation was successful./ | function transferFromAndCall(
address from,
address to,
uint256 amount,
bytes memory data
) public virtual override returns (bool) {
transferFrom(from, to, amount);
require(
_checkOnTransferReceived(from, to, amount, data),
"ERC1363: receiver returned wrong data"
);
return true;
}
| 5,619,757 | [
1,
5912,
2430,
628,
1245,
1758,
358,
4042,
471,
1508,
1836,
279,
1348,
603,
1375,
869,
8338,
225,
628,
1021,
1758,
1492,
1846,
2545,
358,
1366,
2430,
628,
225,
358,
1021,
1758,
1492,
1846,
2545,
358,
7412,
358,
225,
3844,
1021,
3844,
434,
2430,
358,
506,
906,
4193,
225,
501,
15119,
501,
598,
1158,
1269,
740,
327,
432,
1250,
716,
8527,
309,
326,
1674,
1703,
6873,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
7412,
1265,
1876,
1477,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
16,
203,
3639,
1731,
3778,
501,
203,
565,
262,
1071,
5024,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
7412,
1265,
12,
2080,
16,
358,
16,
3844,
1769,
203,
3639,
2583,
12,
203,
5411,
389,
1893,
1398,
5912,
8872,
12,
2080,
16,
358,
16,
3844,
16,
501,
3631,
203,
5411,
315,
654,
39,
3437,
4449,
30,
5971,
2106,
7194,
501,
6,
203,
3639,
11272,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
pragma solidity 0.4.24;
/**
* @title SafeMath
* @notice Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @notice Multiplies two numbers, throws on overflow.
* @param a Multiplier
* @param b Multiplicand
* @return {"result" : "Returns product"}
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 result) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "Error: Unsafe multiplication operation!");
return c;
}
/**
* @notice Integer division of two numbers, truncating the quotient.
* @param a Dividend
* @param b Divisor
* @return {"result" : "Returns quotient"}
*/
function div(uint256 a, uint256 b) internal pure returns (uint256 result) {
// @dev require(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// @dev require(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @notice Subtracts two numbers, throws on underflow.
* @param a Subtrahend
* @param b Minuend
* @return {"result" : "Returns difference"}
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256 result) {
// @dev throws on overflow (i.e. if subtrahend is greater than minuend)
require(b <= a, "Error: Unsafe subtraction operation!");
return a - b;
}
/**
* @notice Adds two numbers, throws on overflow.
* @param a First addend
* @param b Second addend
* @return {"result" : "Returns summation"}
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 result) {
uint256 c = a + b;
require(c >= a, "Error: Unsafe addition operation!");
return c;
}
}
/**
COPYRIGHT 2018 Token, Inc.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@title Ownable
@dev The Ownable contract has an owner address, and provides basic authorization control
functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
mapping(address => bool) public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event AllowOwnership(address indexed allowedAddress);
event RevokeOwnership(address indexed allowedAddress);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner[msg.sender] = true;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner[msg.sender], "Error: Transaction sender is not allowed by the contract.");
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
* @return {"success" : "Returns true when successfully transferred ownership"}
*/
function transferOwnership(address newOwner) public onlyOwner returns (bool success) {
require(newOwner != address(0), "Error: newOwner cannot be null!");
emit OwnershipTransferred(msg.sender, newOwner);
owner[newOwner] = true;
owner[msg.sender] = false;
return true;
}
/**
* @dev Allows interface contracts and accounts to access contract methods (e.g. Storage contract)
* @param allowedAddress The address of new owner
* @return {"success" : "Returns true when successfully allowed ownership"}
*/
function allowOwnership(address allowedAddress) public onlyOwner returns (bool success) {
owner[allowedAddress] = true;
emit AllowOwnership(allowedAddress);
return true;
}
/**
* @dev Disallows interface contracts and accounts to access contract methods (e.g. Storage contract)
* @param allowedAddress The address to disallow ownership
* @return {"success" : "Returns true when successfully allowed ownership"}
*/
function removeOwnership(address allowedAddress) public onlyOwner returns (bool success) {
owner[allowedAddress] = false;
emit RevokeOwnership(allowedAddress);
return true;
}
}
/**
COPYRIGHT 2018 Token, Inc.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@title TokenIOStorage - Serves as derived contract for TokenIO contract and
is used to upgrade interfaces in the event of deprecating the main contract.
@author Ryan Tate <[email protected]>, Sean Pollock <[email protected]>
@notice Storage contract
@dev In the event that the main contract becomes deprecated, the upgraded contract
will be set as the owner of this contract, and use this contract's storage to
maintain data consistency between contract.
@notice NOTE: This contract is based on the RocketPool Storage Contract,
found here: https://github.com/rocket-pool/rocketpool/blob/master/contracts/RocketStorage.sol
And this medium article: https://medium.com/rocket-pool/upgradable-solidity-contract-design-54789205276d
Changes:
- setting primitive mapping view to internal;
- setting method views to public;
@dev NOTE: When deprecating the main TokenIO contract, the upgraded contract
must take ownership of the TokenIO contract, it will require using the public methods
to update changes to the underlying data. The updated contract must use a
standard call to original TokenIO contract such that the request is made from
the upgraded contract and not the transaction origin (tx.origin) of the signing
account.
@dev NOTE: The reasoning for using the storage contract is to abstract the interface
from the data of the contract on chain, limiting the need to migrate data to
new contracts.
*/
contract TokenIOStorage is Ownable {
/// @dev mapping for Primitive Data Types;
/// @notice primitive data mappings have `internal` view;
/// @dev only the derived contract can use the internal methods;
/// @dev key == `keccak256(param1, param2...)`
/// @dev Nested mapping can be achieved using multiple params in keccak256 hash;
mapping(bytes32 => uint256) internal uIntStorage;
mapping(bytes32 => string) internal stringStorage;
mapping(bytes32 => address) internal addressStorage;
mapping(bytes32 => bytes) internal bytesStorage;
mapping(bytes32 => bool) internal boolStorage;
mapping(bytes32 => int256) internal intStorage;
constructor() public {
/// @notice owner is set to msg.sender by default
/// @dev consider removing in favor of setting ownership in inherited
/// contract
owner[msg.sender] = true;
}
/// @dev Set Key Methods
/**
* @notice Set value for Address associated with bytes32 id key
* @param _key Pointer identifier for value in storage
* @param _value The Address value to be set
* @return { "success" : "Returns true when successfully called from another contract" }
*/
function setAddress(bytes32 _key, address _value) public onlyOwner returns (bool success) {
addressStorage[_key] = _value;
return true;
}
/**
* @notice Set value for Uint associated with bytes32 id key
* @param _key Pointer identifier for value in storage
* @param _value The Uint value to be set
* @return { "success" : "Returns true when successfully called from another contract" }
*/
function setUint(bytes32 _key, uint _value) public onlyOwner returns (bool success) {
uIntStorage[_key] = _value;
return true;
}
/**
* @notice Set value for String associated with bytes32 id key
* @param _key Pointer identifier for value in storage
* @param _value The String value to be set
* @return { "success" : "Returns true when successfully called from another contract" }
*/
function setString(bytes32 _key, string _value) public onlyOwner returns (bool success) {
stringStorage[_key] = _value;
return true;
}
/**
* @notice Set value for Bytes associated with bytes32 id key
* @param _key Pointer identifier for value in storage
* @param _value The Bytes value to be set
* @return { "success" : "Returns true when successfully called from another contract" }
*/
function setBytes(bytes32 _key, bytes _value) public onlyOwner returns (bool success) {
bytesStorage[_key] = _value;
return true;
}
/**
* @notice Set value for Bool associated with bytes32 id key
* @param _key Pointer identifier for value in storage
* @param _value The Bool value to be set
* @return { "success" : "Returns true when successfully called from another contract" }
*/
function setBool(bytes32 _key, bool _value) public onlyOwner returns (bool success) {
boolStorage[_key] = _value;
return true;
}
/**
* @notice Set value for Int associated with bytes32 id key
* @param _key Pointer identifier for value in storage
* @param _value The Int value to be set
* @return { "success" : "Returns true when successfully called from another contract" }
*/
function setInt(bytes32 _key, int _value) public onlyOwner returns (bool success) {
intStorage[_key] = _value;
return true;
}
/// @dev Delete Key Methods
/// @dev delete methods may be unnecessary; Use set methods to set values
/// to default?
/**
* @notice Delete value for Address associated with bytes32 id key
* @param _key Pointer identifier for value in storage
* @return { "success" : "Returns true when successfully called from another contract" }
*/
function deleteAddress(bytes32 _key) public onlyOwner returns (bool success) {
delete addressStorage[_key];
return true;
}
/**
* @notice Delete value for Uint associated with bytes32 id key
* @param _key Pointer identifier for value in storage
* @return { "success" : "Returns true when successfully called from another contract" }
*/
function deleteUint(bytes32 _key) public onlyOwner returns (bool success) {
delete uIntStorage[_key];
return true;
}
/**
* @notice Delete value for String associated with bytes32 id key
* @param _key Pointer identifier for value in storage
* @return { "success" : "Returns true when successfully called from another contract" }
*/
function deleteString(bytes32 _key) public onlyOwner returns (bool success) {
delete stringStorage[_key];
return true;
}
/**
* @notice Delete value for Bytes associated with bytes32 id key
* @param _key Pointer identifier for value in storage
* @return { "success" : "Returns true when successfully called from another contract" }
*/
function deleteBytes(bytes32 _key) public onlyOwner returns (bool success) {
delete bytesStorage[_key];
return true;
}
/**
* @notice Delete value for Bool associated with bytes32 id key
* @param _key Pointer identifier for value in storage
* @return { "success" : "Returns true when successfully called from another contract" }
*/
function deleteBool(bytes32 _key) public onlyOwner returns (bool success) {
delete boolStorage[_key];
return true;
}
/**
* @notice Delete value for Int associated with bytes32 id key
* @param _key Pointer identifier for value in storage
* @return { "success" : "Returns true when successfully called from another contract" }
*/
function deleteInt(bytes32 _key) public onlyOwner returns (bool success) {
delete intStorage[_key];
return true;
}
/// @dev Get Key Methods
/**
* @notice Get value for Address associated with bytes32 id key
* @param _key Pointer identifier for value in storage
* @return { "_value" : "Returns the Address value associated with the id key" }
*/
function getAddress(bytes32 _key) public view returns (address _value) {
return addressStorage[_key];
}
/**
* @notice Get value for Uint associated with bytes32 id key
* @param _key Pointer identifier for value in storage
* @return { "_value" : "Returns the Uint value associated with the id key" }
*/
function getUint(bytes32 _key) public view returns (uint _value) {
return uIntStorage[_key];
}
/**
* @notice Get value for String associated with bytes32 id key
* @param _key Pointer identifier for value in storage
* @return { "_value" : "Returns the String value associated with the id key" }
*/
function getString(bytes32 _key) public view returns (string _value) {
return stringStorage[_key];
}
/**
* @notice Get value for Bytes associated with bytes32 id key
* @param _key Pointer identifier for value in storage
* @return { "_value" : "Returns the Bytes value associated with the id key" }
*/
function getBytes(bytes32 _key) public view returns (bytes _value) {
return bytesStorage[_key];
}
/**
* @notice Get value for Bool associated with bytes32 id key
* @param _key Pointer identifier for value in storage
* @return { "_value" : "Returns the Bool value associated with the id key" }
*/
function getBool(bytes32 _key) public view returns (bool _value) {
return boolStorage[_key];
}
/**
* @notice Get value for Int associated with bytes32 id key
* @param _key Pointer identifier for value in storage
* @return { "_value" : "Returns the Int value associated with the id key" }
*/
function getInt(bytes32 _key) public view returns (int _value) {
return intStorage[_key];
}
}
/**
COPYRIGHT 2018 Token, Inc.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@title TokenIOLib
@author Ryan Tate <[email protected]>, Sean Pollock <[email protected]>
@notice This library proxies the TokenIOStorage contract for the interface contract,
allowing the library and the interfaces to remain stateless, and share a universally
available storage contract between interfaces.
*/
library TokenIOLib {
/// @dev all math operating are using SafeMath methods to check for overflow/underflows
using SafeMath for uint;
/// @dev the Data struct uses the Storage contract for stateful setters
struct Data {
TokenIOStorage Storage;
}
/// @notice Not using `Log` prefix for events to be consistent with ERC20 named events;
event Approval(address indexed owner, address indexed spender, uint amount);
event Deposit(string currency, address indexed account, uint amount, string issuerFirm);
event Withdraw(string currency, address indexed account, uint amount, string issuerFirm);
event Transfer(string currency, address indexed from, address indexed to, uint amount, bytes data);
event KYCApproval(address indexed account, bool status, string issuerFirm);
event AccountStatus(address indexed account, bool status, string issuerFirm);
event FxSwap(string tokenASymbol,string tokenBSymbol,uint tokenAValue,uint tokenBValue, uint expiration, bytes32 transactionHash);
event AccountForward(address indexed originalAccount, address indexed forwardedAccount);
event NewAuthority(address indexed authority, string issuerFirm);
/**
* @notice Set the token name for Token interfaces
* @dev This method must be set by the token interface's setParams() method
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param tokenName Name of the token contract
* @return {"success" : "Returns true when successfully called from another contract"}
*/
function setTokenName(Data storage self, string tokenName) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('token.name', address(this)));
require(
self.Storage.setString(id, tokenName),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."
);
return true;
}
/**
* @notice Set the token symbol for Token interfaces
* @dev This method must be set by the token interface's setParams() method
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param tokenSymbol Symbol of the token contract
* @return {"success" : "Returns true when successfully called from another contract"}
*/
function setTokenSymbol(Data storage self, string tokenSymbol) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('token.symbol', address(this)));
require(
self.Storage.setString(id, tokenSymbol),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."
);
return true;
}
/**
* @notice Set the token three letter abreviation (TLA) for Token interfaces
* @dev This method must be set by the token interface's setParams() method
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param tokenTLA TLA of the token contract
* @return {"success" : "Returns true when successfully called from another contract"}
*/
function setTokenTLA(Data storage self, string tokenTLA) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('token.tla', address(this)));
require(
self.Storage.setString(id, tokenTLA),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."
);
return true;
}
/**
* @notice Set the token version for Token interfaces
* @dev This method must be set by the token interface's setParams() method
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param tokenVersion Semantic (vMAJOR.MINOR.PATCH | e.g. v0.1.0) version of the token contract
* @return {"success" : "Returns true when successfully called from another contract"}
*/
function setTokenVersion(Data storage self, string tokenVersion) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('token.version', address(this)));
require(
self.Storage.setString(id, tokenVersion),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."
);
return true;
}
/**
* @notice Set the token decimals for Token interfaces
* @dev This method must be set by the token interface's setParams() method
* @dev | This method has an `internal` view
* @dev This method is not set to the address of the contract, rather is maped to currency
* @dev To derive decimal value, divide amount by 10^decimal representation (e.g. 10132 / 10**2 == 101.32)
* @param self Internal storage proxying TokenIOStorage contract
* @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)
* @param tokenDecimals Decimal representation of the token contract unit amount
* @return {"success" : "Returns true when successfully called from another contract"}
*/
function setTokenDecimals(Data storage self, string currency, uint tokenDecimals) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('token.decimals', currency));
require(
self.Storage.setUint(id, tokenDecimals),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."
);
return true;
}
/**
* @notice Set basis point fee for contract interface
* @dev Transaction fees can be set by the TokenIOFeeContract
* @dev Fees vary by contract interface specified `feeContract`
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param feeBPS Basis points fee for interface contract transactions
* @return {"success" : "Returns true when successfully called from another contract"}
*/
function setFeeBPS(Data storage self, uint feeBPS) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('fee.bps', address(this)));
require(
self.Storage.setUint(id, feeBPS),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."
);
return true;
}
/**
* @notice Set minimum fee for contract interface
* @dev Transaction fees can be set by the TokenIOFeeContract
* @dev Fees vary by contract interface specified `feeContract`
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param feeMin Minimum fee for interface contract transactions
* @return {"success" : "Returns true when successfully called from another contract"}
*/
function setFeeMin(Data storage self, uint feeMin) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('fee.min', address(this)));
require(
self.Storage.setUint(id, feeMin),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."
);
return true;
}
/**
* @notice Set maximum fee for contract interface
* @dev Transaction fees can be set by the TokenIOFeeContract
* @dev Fees vary by contract interface specified `feeContract`
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param feeMax Maximum fee for interface contract transactions
* @return {"success" : "Returns true when successfully called from another contract"}
*/
function setFeeMax(Data storage self, uint feeMax) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('fee.max', address(this)));
require(
self.Storage.setUint(id, feeMax),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."
);
return true;
}
/**
* @notice Set flat fee for contract interface
* @dev Transaction fees can be set by the TokenIOFeeContract
* @dev Fees vary by contract interface specified `feeContract`
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param feeFlat Flat fee for interface contract transactions
* @return {"success" : "Returns true when successfully called from another contract"}
*/
function setFeeFlat(Data storage self, uint feeFlat) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('fee.flat', address(this)));
require(
self.Storage.setUint(id, feeFlat),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."
);
return true;
}
/**
* @notice Set fee message for contract interface
* @dev Default fee messages can be set by the TokenIOFeeContract (e.g. "tx_fees")
* @dev Fee messages vary by contract interface specified `feeContract`
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param feeMsg Fee message included in a transaction with fees
* @return {"success" : "Returns true when successfully called from another contract"}
*/
function setFeeMsg(Data storage self, bytes feeMsg) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('fee.msg', address(this)));
require(
self.Storage.setBytes(id, feeMsg),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."
);
return true;
}
/**
* @notice Set fee contract for a contract interface
* @dev feeContract must be a TokenIOFeeContract storage approved contract
* @dev Fees vary by contract interface specified `feeContract`
* @dev | This method has an `internal` view
* @dev | This must be called directly from the interface contract
* @param self Internal storage proxying TokenIOStorage contract
* @param feeContract Set the fee contract for `this` contract address interface
* @return {"success" : "Returns true when successfully called from another contract"}
*/
function setFeeContract(Data storage self, address feeContract) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('fee.account', address(this)));
require(
self.Storage.setAddress(id, feeContract),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."
);
return true;
}
/**
* @notice Set contract interface associated with a given TokenIO currency symbol (e.g. USDx)
* @dev | This should only be called once from a token interface contract;
* @dev | This method has an `internal` view
* @dev | This method is experimental and may be deprecated/refactored
* @param self Internal storage proxying TokenIOStorage contract
* @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)
* @return {"success" : "Returns true when successfully called from another contract"}
*/
function setTokenNameSpace(Data storage self, string currency) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('token.namespace', currency));
require(
self.Storage.setAddress(id, address(this)),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."
);
return true;
}
/**
* @notice Set the KYC approval status (true/false) for a given account
* @dev | This method has an `internal` view
* @dev | Every account must be KYC'd to be able to use transfer() & transferFrom() methods
* @dev | To gain approval for an account, register at https://tsm.token.io/sign-up
* @param self Internal storage proxying TokenIOStorage contract
* @param account Ethereum address of account holder
* @param isApproved Boolean (true/false) KYC approval status for a given account
* @param issuerFirm Firm name for issuing KYC approval
* @return {"success" : "Returns true when successfully called from another contract"}
*/
function setKYCApproval(Data storage self, address account, bool isApproved, string issuerFirm) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('account.kyc', getForwardedAccount(self, account)));
require(
self.Storage.setBool(id, isApproved),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."
);
/// @dev NOTE: Issuer is logged for setting account KYC status
emit KYCApproval(account, isApproved, issuerFirm);
return true;
}
/**
* @notice Set the global approval status (true/false) for a given account
* @dev | This method has an `internal` view
* @dev | Every account must be permitted to be able to use transfer() & transferFrom() methods
* @dev | To gain approval for an account, register at https://tsm.token.io/sign-up
* @param self Internal storage proxying TokenIOStorage contract
* @param account Ethereum address of account holder
* @param isAllowed Boolean (true/false) global status for a given account
* @param issuerFirm Firm name for issuing approval
* @return {"success" : "Returns true when successfully called from another contract"}
*/
function setAccountStatus(Data storage self, address account, bool isAllowed, string issuerFirm) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('account.allowed', getForwardedAccount(self, account)));
require(
self.Storage.setBool(id, isAllowed),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."
);
/// @dev NOTE: Issuer is logged for setting account status
emit AccountStatus(account, isAllowed, issuerFirm);
return true;
}
/**
* @notice Set a forwarded address for an account.
* @dev | This method has an `internal` view
* @dev | Forwarded accounts must be set by an authority in case of account recovery;
* @dev | Additionally, the original owner can set a forwarded account (e.g. add a new device, spouse, dependent, etc)
* @dev | All transactions will be logged under the same KYC information as the original account holder;
* @param self Internal storage proxying TokenIOStorage contract
* @param originalAccount Original registered Ethereum address of the account holder
* @param forwardedAccount Forwarded Ethereum address of the account holder
* @return {"success" : "Returns true when successfully called from another contract"}
*/
function setForwardedAccount(Data storage self, address originalAccount, address forwardedAccount) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('master.account', forwardedAccount));
require(
self.Storage.setAddress(id, originalAccount),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."
);
return true;
}
/**
* @notice Get the original address for a forwarded account
* @dev | This method has an `internal` view
* @dev | Will return the registered account for the given forwarded account
* @param self Internal storage proxying TokenIOStorage contract
* @param account Ethereum address of account holder
* @return { "registeredAccount" : "Will return the original account of a forwarded account or the account itself if no account found"}
*/
function getForwardedAccount(Data storage self, address account) internal view returns (address registeredAccount) {
bytes32 id = keccak256(abi.encodePacked('master.account', account));
address originalAccount = self.Storage.getAddress(id);
if (originalAccount != 0x0) {
return originalAccount;
} else {
return account;
}
}
/**
* @notice Get KYC approval status for the account holder
* @dev | This method has an `internal` view
* @dev | All forwarded accounts will use the original account's status
* @param self Internal storage proxying TokenIOStorage contract
* @param account Ethereum address of account holder
* @return { "status" : "Returns the KYC approval status for an account holder" }
*/
function getKYCApproval(Data storage self, address account) internal view returns (bool status) {
bytes32 id = keccak256(abi.encodePacked('account.kyc', getForwardedAccount(self, account)));
return self.Storage.getBool(id);
}
/**
* @notice Get global approval status for the account holder
* @dev | This method has an `internal` view
* @dev | All forwarded accounts will use the original account's status
* @param self Internal storage proxying TokenIOStorage contract
* @param account Ethereum address of account holder
* @return { "status" : "Returns the global approval status for an account holder" }
*/
function getAccountStatus(Data storage self, address account) internal view returns (bool status) {
bytes32 id = keccak256(abi.encodePacked('account.allowed', getForwardedAccount(self, account)));
return self.Storage.getBool(id);
}
/**
* @notice Get the contract interface address associated with token symbol
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)
* @return { "contractAddress" : "Returns the contract interface address for a symbol" }
*/
function getTokenNameSpace(Data storage self, string currency) internal view returns (address contractAddress) {
bytes32 id = keccak256(abi.encodePacked('token.namespace', currency));
return self.Storage.getAddress(id);
}
/**
* @notice Get the token name for Token interfaces
* @dev This method must be set by the token interface's setParams() method
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param contractAddress Contract address of the queryable interface
* @return {"tokenName" : "Name of the token contract"}
*/
function getTokenName(Data storage self, address contractAddress) internal view returns (string tokenName) {
bytes32 id = keccak256(abi.encodePacked('token.name', contractAddress));
return self.Storage.getString(id);
}
/**
* @notice Get the token symbol for Token interfaces
* @dev This method must be set by the token interface's setParams() method
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param contractAddress Contract address of the queryable interface
* @return {"tokenSymbol" : "Symbol of the token contract"}
*/
function getTokenSymbol(Data storage self, address contractAddress) internal view returns (string tokenSymbol) {
bytes32 id = keccak256(abi.encodePacked('token.symbol', contractAddress));
return self.Storage.getString(id);
}
/**
* @notice Get the token Three letter abbreviation (TLA) for Token interfaces
* @dev This method must be set by the token interface's setParams() method
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param contractAddress Contract address of the queryable interface
* @return {"tokenTLA" : "TLA of the token contract"}
*/
function getTokenTLA(Data storage self, address contractAddress) internal view returns (string tokenTLA) {
bytes32 id = keccak256(abi.encodePacked('token.tla', contractAddress));
return self.Storage.getString(id);
}
/**
* @notice Get the token version for Token interfaces
* @dev This method must be set by the token interface's setParams() method
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param contractAddress Contract address of the queryable interface
* @return {"tokenVersion" : "Semantic version of the token contract"}
*/
function getTokenVersion(Data storage self, address contractAddress) internal view returns (string) {
bytes32 id = keccak256(abi.encodePacked('token.version', contractAddress));
return self.Storage.getString(id);
}
/**
* @notice Get the token decimals for Token interfaces
* @dev This method must be set by the token interface's setParams() method
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)
* @return {"tokenDecimals" : "Decimals of the token contract"}
*/
function getTokenDecimals(Data storage self, string currency) internal view returns (uint tokenDecimals) {
bytes32 id = keccak256(abi.encodePacked('token.decimals', currency));
return self.Storage.getUint(id);
}
/**
* @notice Get the basis points fee of the contract address; typically TokenIOFeeContract
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param contractAddress Contract address of the queryable interface
* @return { "feeBps" : "Returns the basis points fees associated with the contract address"}
*/
function getFeeBPS(Data storage self, address contractAddress) internal view returns (uint feeBps) {
bytes32 id = keccak256(abi.encodePacked('fee.bps', contractAddress));
return self.Storage.getUint(id);
}
/**
* @notice Get the minimum fee of the contract address; typically TokenIOFeeContract
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param contractAddress Contract address of the queryable interface
* @return { "feeMin" : "Returns the minimum fees associated with the contract address"}
*/
function getFeeMin(Data storage self, address contractAddress) internal view returns (uint feeMin) {
bytes32 id = keccak256(abi.encodePacked('fee.min', contractAddress));
return self.Storage.getUint(id);
}
/**
* @notice Get the maximum fee of the contract address; typically TokenIOFeeContract
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param contractAddress Contract address of the queryable interface
* @return { "feeMax" : "Returns the maximum fees associated with the contract address"}
*/
function getFeeMax(Data storage self, address contractAddress) internal view returns (uint feeMax) {
bytes32 id = keccak256(abi.encodePacked('fee.max', contractAddress));
return self.Storage.getUint(id);
}
/**
* @notice Get the flat fee of the contract address; typically TokenIOFeeContract
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param contractAddress Contract address of the queryable interface
* @return { "feeFlat" : "Returns the flat fees associated with the contract address"}
*/
function getFeeFlat(Data storage self, address contractAddress) internal view returns (uint feeFlat) {
bytes32 id = keccak256(abi.encodePacked('fee.flat', contractAddress));
return self.Storage.getUint(id);
}
/**
* @notice Get the flat message of the contract address; typically TokenIOFeeContract
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param contractAddress Contract address of the queryable interface
* @return { "feeMsg" : "Returns the fee message (bytes) associated with the contract address"}
*/
function getFeeMsg(Data storage self, address contractAddress) internal view returns (bytes feeMsg) {
bytes32 id = keccak256(abi.encodePacked('fee.msg', contractAddress));
return self.Storage.getBytes(id);
}
/**
* @notice Set the master fee contract used as the default fee contract when none is provided
* @dev | This method has an `internal` view
* @dev | This value is set in the TokenIOAuthority contract
* @param self Internal storage proxying TokenIOStorage contract
* @param contractAddress Contract address of the queryable interface
* @return { "success" : "Returns true when successfully called from another contract"}
*/
function setMasterFeeContract(Data storage self, address contractAddress) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('fee.contract.master'));
require(
self.Storage.setAddress(id, contractAddress),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."
);
return true;
}
/**
* @notice Get the master fee contract set via the TokenIOAuthority contract
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @return { "masterFeeContract" : "Returns the master fee contract set for TSM."}
*/
function getMasterFeeContract(Data storage self) internal view returns (address masterFeeContract) {
bytes32 id = keccak256(abi.encodePacked('fee.contract.master'));
return self.Storage.getAddress(id);
}
/**
* @notice Get the fee contract set for a contract interface
* @dev | This method has an `internal` view
* @dev | Custom fee pricing can be set by assigning a fee contract to transactional contract interfaces
* @dev | If a fee contract has not been set by an interface contract, then the master fee contract will be returned
* @param self Internal storage proxying TokenIOStorage contract
* @param contractAddress Contract address of the queryable interface
* @return { "feeContract" : "Returns the fee contract associated with a contract interface"}
*/
function getFeeContract(Data storage self, address contractAddress) internal view returns (address feeContract) {
bytes32 id = keccak256(abi.encodePacked('fee.account', contractAddress));
address feeAccount = self.Storage.getAddress(id);
if (feeAccount == 0x0) {
return getMasterFeeContract(self);
} else {
return feeAccount;
}
}
/**
* @notice Get the token supply for a given TokenIO TSM currency symbol (e.g. USDx)
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)
* @return { "supply" : "Returns the token supply of the given currency"}
*/
function getTokenSupply(Data storage self, string currency) internal view returns (uint supply) {
bytes32 id = keccak256(abi.encodePacked('token.supply', currency));
return self.Storage.getUint(id);
}
/**
* @notice Get the token spender allowance for a given account
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param account Ethereum address of account holder
* @param spender Ethereum address of spender
* @return { "allowance" : "Returns the allowance of a given spender for a given account"}
*/
function getTokenAllowance(Data storage self, string currency, address account, address spender) internal view returns (uint allowance) {
bytes32 id = keccak256(abi.encodePacked('token.allowance', currency, getForwardedAccount(self, account), getForwardedAccount(self, spender)));
return self.Storage.getUint(id);
}
/**
* @notice Get the token balance for a given account
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)
* @param account Ethereum address of account holder
* @return { "balance" : "Return the balance of a given account for a specified currency"}
*/
function getTokenBalance(Data storage self, string currency, address account) internal view returns (uint balance) {
bytes32 id = keccak256(abi.encodePacked('token.balance', currency, getForwardedAccount(self, account)));
return self.Storage.getUint(id);
}
/**
* @notice Get the frozen token balance for a given account
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)
* @param account Ethereum address of account holder
* @return { "frozenBalance" : "Return the frozen balance of a given account for a specified currency"}
*/
function getTokenFrozenBalance(Data storage self, string currency, address account) internal view returns (uint frozenBalance) {
bytes32 id = keccak256(abi.encodePacked('token.frozen', currency, getForwardedAccount(self, account)));
return self.Storage.getUint(id);
}
/**
* @notice Set the frozen token balance for a given account
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)
* @param account Ethereum address of account holder
* @param amount Amount of tokens to freeze for account
* @return { "success" : "Return true if successfully called from another contract"}
*/
function setTokenFrozenBalance(Data storage self, string currency, address account, uint amount) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('token.frozen', currency, getForwardedAccount(self, account)));
require(
self.Storage.setUint(id, amount),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract."
);
return true;
}
/**
* @notice Set the frozen token balance for a given account
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param contractAddress Contract address of the fee contract
* @param amount Transaction value
* @return { "calculatedFees" : "Return the calculated transaction fees for a given amount and fee contract" }
*/
function calculateFees(Data storage self, address contractAddress, uint amount) internal view returns (uint calculatedFees) {
uint maxFee = self.Storage.getUint(keccak256(abi.encodePacked('fee.max', contractAddress)));
uint minFee = self.Storage.getUint(keccak256(abi.encodePacked('fee.min', contractAddress)));
uint bpsFee = self.Storage.getUint(keccak256(abi.encodePacked('fee.bps', contractAddress)));
uint flatFee = self.Storage.getUint(keccak256(abi.encodePacked('fee.flat', contractAddress)));
uint fees = ((amount.mul(bpsFee)).div(10000)).add(flatFee);
if (fees > maxFee) {
return maxFee;
} else if (fees < minFee) {
return minFee;
} else {
return fees;
}
}
/**
* @notice Verified KYC and global status for two accounts and return true or throw if either account is not verified
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param accountA Ethereum address of first account holder to verify
* @param accountB Ethereum address of second account holder to verify
* @return { "verified" : "Returns true if both accounts are successfully verified" }
*/
function verifyAccounts(Data storage self, address accountA, address accountB) internal view returns (bool verified) {
require(
verifyAccount(self, accountA),
"Error: Account is not verified for operation. Please ensure account has been KYC approved."
);
require(
verifyAccount(self, accountB),
"Error: Account is not verified for operation. Please ensure account has been KYC approved."
);
return true;
}
/**
* @notice Verified KYC and global status for a single account and return true or throw if account is not verified
* @dev | This method has an `internal` view
* @param self Internal storage proxying TokenIOStorage contract
* @param account Ethereum address of account holder to verify
* @return { "verified" : "Returns true if account is successfully verified" }
*/
function verifyAccount(Data storage self, address account) internal view returns (bool verified) {
require(
getKYCApproval(self, account),
"Error: Account does not have KYC approval."
);
require(
getAccountStatus(self, account),
"Error: Account status is `false`. Account status must be `true`."
);
return true;
}
/**
* @notice Transfer an amount of currency token from msg.sender account to another specified account
* @dev This function is called by an interface that is accessible directly to the account holder
* @dev | This method has an `internal` view
* @dev | This method uses `forceTransfer()` low-level api
* @param self Internal storage proxying TokenIOStorage contract
* @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)
* @param to Ethereum address of account to send currency amount to
* @param amount Value of currency to transfer
* @param data Arbitrary bytes data to include with the transaction
* @return { "success" : "Return true if successfully called from another contract" }
*/
function transfer(Data storage self, string currency, address to, uint amount, bytes data) internal returns (bool success) {
require(address(to) != 0x0, "Error: `to` address cannot be null." );
require(amount > 0, "Error: `amount` must be greater than zero");
address feeContract = getFeeContract(self, address(this));
uint fees = calculateFees(self, feeContract, amount);
require(
setAccountSpendingAmount(self, msg.sender, getFxUSDAmount(self, currency, amount)),
"Error: Unable to set spending amount for account.");
require(
forceTransfer(self, currency, msg.sender, to, amount, data),
"Error: Unable to transfer funds to account.");
// @dev transfer fees to fee contract
require(
forceTransfer(self, currency, msg.sender, feeContract, fees, getFeeMsg(self, feeContract)),
"Error: Unable to transfer fees to fee contract.");
return true;
}
/**
* @notice Transfer an amount of currency token from account to another specified account via an approved spender account
* @dev This function is called by an interface that is accessible directly to the account spender
* @dev | This method has an `internal` view
* @dev | Transactions will fail if the spending amount exceeds the daily limit
* @dev | This method uses `forceTransfer()` low-level api
* @dev | This method implements ERC20 transferFrom() method with approved spender behavior
* @dev | msg.sender == spender; `updateAllowance()` reduces approved limit for account spender
* @param self Internal storage proxying TokenIOStorage contract
* @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)
* @param from Ethereum address of account to send currency amount from
* @param to Ethereum address of account to send currency amount to
* @param amount Value of currency to transfer
* @param data Arbitrary bytes data to include with the transaction
* @return { "success" : "Return true if successfully called from another contract" }
*/
function transferFrom(Data storage self, string currency, address from, address to, uint amount, bytes data) internal returns (bool success) {
require(
address(to) != 0x0,
"Error: `to` address must not be null."
);
address feeContract = getFeeContract(self, address(this));
uint fees = calculateFees(self, feeContract, amount);
/// @dev NOTE: This transaction will fail if the spending amount exceeds the daily limit
require(
setAccountSpendingAmount(self, from, getFxUSDAmount(self, currency, amount)),
"Error: Unable to set account spending amount."
);
/// @dev Attempt to transfer the amount
require(
forceTransfer(self, currency, from, to, amount, data),
"Error: Unable to transfer funds to account."
);
// @dev transfer fees to fee contract
require(
forceTransfer(self, currency, from, feeContract, fees, getFeeMsg(self, feeContract)),
"Error: Unable to transfer fees to fee contract."
);
/// @dev Attempt to update the spender allowance
/// @notice this will throw if the allowance has not been set.
require(
updateAllowance(self, currency, from, amount),
"Error: Unable to update allowance for spender."
);
return true;
}
/**
* @notice Low-level transfer method
* @dev | This method has an `internal` view
* @dev | This method does not include fees or approved allowances.
* @dev | This method is only for authorized interfaces to use (e.g. TokenIOFX)
* @param self Internal storage proxying TokenIOStorage contract
* @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)
* @param from Ethereum address of account to send currency amount from
* @param to Ethereum address of account to send currency amount to
* @param amount Value of currency to transfer
* @param data Arbitrary bytes data to include with the transaction
* @return { "success" : "Return true if successfully called from another contract" }
*/
function forceTransfer(Data storage self, string currency, address from, address to, uint amount, bytes data) internal returns (bool success) {
require(
address(to) != 0x0,
"Error: `to` address must not be null."
);
bytes32 id_a = keccak256(abi.encodePacked('token.balance', currency, getForwardedAccount(self, from)));
bytes32 id_b = keccak256(abi.encodePacked('token.balance', currency, getForwardedAccount(self, to)));
require(
self.Storage.setUint(id_a, self.Storage.getUint(id_a).sub(amount)),
"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract."
);
require(
self.Storage.setUint(id_b, self.Storage.getUint(id_b).add(amount)),
"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract."
);
emit Transfer(currency, from, to, amount, data);
return true;
}
/**
* @notice Low-level method to update spender allowance for account
* @dev | This method is called inside the `transferFrom()` method
* @dev | msg.sender == spender address
* @param self Internal storage proxying TokenIOStorage contract
* @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)
* @param account Ethereum address of account holder
* @param amount Value to reduce allowance by (i.e. the amount spent)
* @return { "success" : "Return true if successfully called from another contract" }
*/
function updateAllowance(Data storage self, string currency, address account, uint amount) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('token.allowance', currency, getForwardedAccount(self, account), getForwardedAccount(self, msg.sender)));
require(
self.Storage.setUint(id, self.Storage.getUint(id).sub(amount)),
"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract."
);
return true;
}
/**
* @notice Low-level method to set the allowance for a spender
* @dev | This method is called inside the `approve()` ERC20 method
* @dev | msg.sender == account holder
* @param self Internal storage proxying TokenIOStorage contract
* @param spender Ethereum address of account spender
* @param amount Value to set for spender allowance
* @return { "success" : "Return true if successfully called from another contract" }
*/
function approveAllowance(Data storage self, address spender, uint amount) internal returns (bool success) {
require(spender != 0x0,
"Error: `spender` address cannot be null.");
string memory currency = getTokenSymbol(self, address(this));
require(
getTokenFrozenBalance(self, currency, getForwardedAccount(self, spender)) == 0,
"Error: Spender must not have a frozen balance directly");
bytes32 id_a = keccak256(abi.encodePacked('token.allowance', currency, getForwardedAccount(self, msg.sender), getForwardedAccount(self, spender)));
bytes32 id_b = keccak256(abi.encodePacked('token.balance', currency, getForwardedAccount(self, msg.sender)));
require(
self.Storage.getUint(id_a) == 0 || amount == 0,
"Error: Allowance must be zero (0) before setting an updated allowance for spender.");
require(
self.Storage.getUint(id_b) >= amount,
"Error: Allowance cannot exceed msg.sender token balance.");
require(
self.Storage.setUint(id_a, amount),
"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.");
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Deposit an amount of currency into the Ethereum account holder
* @dev | The total supply of the token increases only when new funds are deposited 1:1
* @dev | This method should only be called by authorized issuer firms
* @param self Internal storage proxying TokenIOStorage contract
* @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)
* @param account Ethereum address of account holder to deposit funds for
* @param amount Value of currency to deposit for account
* @param issuerFirm Name of the issuing firm authorizing the deposit
* @return { "success" : "Return true if successfully called from another contract" }
*/
function deposit(Data storage self, string currency, address account, uint amount, string issuerFirm) internal returns (bool success) {
bytes32 id_a = keccak256(abi.encodePacked('token.balance', currency, getForwardedAccount(self, account)));
bytes32 id_b = keccak256(abi.encodePacked('token.issued', currency, issuerFirm));
bytes32 id_c = keccak256(abi.encodePacked('token.supply', currency));
require(self.Storage.setUint(id_a, self.Storage.getUint(id_a).add(amount)),
"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.");
require(self.Storage.setUint(id_b, self.Storage.getUint(id_b).add(amount)),
"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.");
require(self.Storage.setUint(id_c, self.Storage.getUint(id_c).add(amount)),
"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.");
emit Deposit(currency, account, amount, issuerFirm);
return true;
}
/**
* @notice Withdraw an amount of currency from the Ethereum account holder
* @dev | The total supply of the token decreases only when new funds are withdrawn 1:1
* @dev | This method should only be called by authorized issuer firms
* @param self Internal storage proxying TokenIOStorage contract
* @param currency Currency symbol of the token (e.g. USDx, JYPx, GBPx)
* @param account Ethereum address of account holder to deposit funds for
* @param amount Value of currency to withdraw for account
* @param issuerFirm Name of the issuing firm authorizing the withdraw
* @return { "success" : "Return true if successfully called from another contract" }
*/
function withdraw(Data storage self, string currency, address account, uint amount, string issuerFirm) internal returns (bool success) {
bytes32 id_a = keccak256(abi.encodePacked('token.balance', currency, getForwardedAccount(self, account)));
bytes32 id_b = keccak256(abi.encodePacked('token.issued', currency, issuerFirm)); // possible for issuer to go negative
bytes32 id_c = keccak256(abi.encodePacked('token.supply', currency));
require(
self.Storage.setUint(id_a, self.Storage.getUint(id_a).sub(amount)),
"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.");
require(
self.Storage.setUint(id_b, self.Storage.getUint(id_b).sub(amount)),
"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.");
require(
self.Storage.setUint(id_c, self.Storage.getUint(id_c).sub(amount)),
"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.");
emit Withdraw(currency, account, amount, issuerFirm);
return true;
}
/**
* @notice Method for setting a registered issuer firm
* @dev | Only Token, Inc. and other authorized institutions may set a registered firm
* @dev | The TokenIOAuthority.sol interface wraps this method
* @dev | If the registered firm is unapproved; all authorized addresses of that firm will also be unapproved
* @param self Internal storage proxying TokenIOStorage contract
* @param issuerFirm Name of the firm to be registered
* @param approved Approval status to set for the firm (true/false)
* @return { "success" : "Return true if successfully called from another contract" }
*/
function setRegisteredFirm(Data storage self, string issuerFirm, bool approved) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('registered.firm', issuerFirm));
require(
self.Storage.setBool(id, approved),
"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract."
);
return true;
}
/**
* @notice Method for setting a registered issuer firm authority
* @dev | Only Token, Inc. and other approved institutions may set a registered firm
* @dev | The TokenIOAuthority.sol interface wraps this method
* @dev | Authority can only be set for a registered issuer firm
* @param self Internal storage proxying TokenIOStorage contract
* @param issuerFirm Name of the firm to be registered to authority
* @param authorityAddress Ethereum address of the firm authority to be approved
* @param approved Approval status to set for the firm authority (true/false)
* @return { "success" : "Return true if successfully called from another contract" }
*/
function setRegisteredAuthority(Data storage self, string issuerFirm, address authorityAddress, bool approved) internal returns (bool success) {
require(
isRegisteredFirm(self, issuerFirm),
"Error: `issuerFirm` must be registered.");
bytes32 id_a = keccak256(abi.encodePacked('registered.authority', issuerFirm, authorityAddress));
bytes32 id_b = keccak256(abi.encodePacked('registered.authority.firm', authorityAddress));
require(
self.Storage.setBool(id_a, approved),
"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.");
require(
self.Storage.setString(id_b, issuerFirm),
"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.");
return true;
}
/**
* @notice Get the issuer firm registered to the authority Ethereum address
* @dev | Only one firm can be registered per authority
* @param self Internal storage proxying TokenIOStorage contract
* @param authorityAddress Ethereum address of the firm authority to query
* @return { "issuerFirm" : "Name of the firm registered to authority" }
*/
function getFirmFromAuthority(Data storage self, address authorityAddress) internal view returns (string issuerFirm) {
bytes32 id = keccak256(abi.encodePacked('registered.authority.firm', getForwardedAccount(self, authorityAddress)));
return self.Storage.getString(id);
}
/**
* @notice Return the boolean (true/false) registration status for an issuer firm
* @param self Internal storage proxying TokenIOStorage contract
* @param issuerFirm Name of the issuer firm
* @return { "registered" : "Return if the issuer firm has been registered" }
*/
function isRegisteredFirm(Data storage self, string issuerFirm) internal view returns (bool registered) {
bytes32 id = keccak256(abi.encodePacked('registered.firm', issuerFirm));
return self.Storage.getBool(id);
}
/**
* @notice Return the boolean (true/false) status if an authority is registered to an issuer firm
* @param self Internal storage proxying TokenIOStorage contract
* @param issuerFirm Name of the issuer firm
* @param authorityAddress Ethereum address of the firm authority to query
* @return { "registered" : "Return if the authority is registered with the issuer firm" }
*/
function isRegisteredToFirm(Data storage self, string issuerFirm, address authorityAddress) internal view returns (bool registered) {
bytes32 id = keccak256(abi.encodePacked('registered.authority', issuerFirm, getForwardedAccount(self, authorityAddress)));
return self.Storage.getBool(id);
}
/**
* @notice Return if an authority address is registered
* @dev | This also checks the status of the registered issuer firm
* @param self Internal storage proxying TokenIOStorage contract
* @param authorityAddress Ethereum address of the firm authority to query
* @return { "registered" : "Return if the authority is registered" }
*/
function isRegisteredAuthority(Data storage self, address authorityAddress) internal view returns (bool registered) {
bytes32 id = keccak256(abi.encodePacked('registered.authority', getFirmFromAuthority(self, getForwardedAccount(self, authorityAddress)), getForwardedAccount(self, authorityAddress)));
return self.Storage.getBool(id);
}
/**
* @notice Return boolean transaction status if the transaction has been used
* @param self Internal storage proxying TokenIOStorage contract
* @param txHash keccak256 ABI tightly packed encoded hash digest of tx params
* @return {"txStatus": "Returns true if the tx hash has already been set using `setTxStatus()` method"}
*/
function getTxStatus(Data storage self, bytes32 txHash) internal view returns (bool txStatus) {
bytes32 id = keccak256(abi.encodePacked('tx.status', txHash));
return self.Storage.getBool(id);
}
/**
* @notice Set transaction status if the transaction has been used
* @param self Internal storage proxying TokenIOStorage contract
* @param txHash keccak256 ABI tightly packed encoded hash digest of tx params
* @return { "success" : "Return true if successfully called from another contract" }
*/
function setTxStatus(Data storage self, bytes32 txHash) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('tx.status', txHash));
/// @dev Ensure transaction has not yet been used;
require(!getTxStatus(self, txHash),
"Error: Transaction status must be false before setting the transaction status.");
/// @dev Update the status of the transaction;
require(self.Storage.setBool(id, true),
"Error: Unable to set storage value. Please ensure contract has allowed permissions with storage contract.");
return true;
}
/**
* @notice Accepts a signed fx request to swap currency pairs at a given amount;
* @dev | This method can be called directly between peers
* @dev | This method does not take transaction fees from the swap
* @param self Internal storage proxying TokenIOStorage contract
* @param requester address Requester is the orginator of the offer and must
* match the signature of the payload submitted by the fulfiller
* @param symbolA Symbol of the currency desired
* @param symbolB Symbol of the currency offered
* @param valueA Amount of the currency desired
* @param valueB Amount of the currency offered
* @param sigV Ethereum secp256k1 signature V value; used by ecrecover()
* @param sigR Ethereum secp256k1 signature R value; used by ecrecover()
* @param sigS Ethereum secp256k1 signature S value; used by ecrecover()
* @param expiration Expiration of the offer; Offer is good until expired
* @return {"success" : "Returns true if successfully called from another contract"}
*/
function execSwap(
Data storage self,
address requester,
string symbolA,
string symbolB,
uint valueA,
uint valueB,
uint8 sigV,
bytes32 sigR,
bytes32 sigS,
uint expiration
) internal returns (bool success) {
bytes32 fxTxHash = keccak256(abi.encodePacked(requester, symbolA, symbolB, valueA, valueB, expiration));
/// @notice check that sender and requester accounts are verified
/// @notice Only verified accounts can perform currency swaps
require(
verifyAccounts(self, msg.sender, requester),
"Error: Only verified accounts can perform currency swaps.");
/// @dev Immediately set this transaction to be confirmed before updating any params;
require(
setTxStatus(self, fxTxHash),
"Error: Failed to set transaction status to fulfilled.");
/// @dev Ensure contract has not yet expired;
require(expiration >= now, "Error: Transaction has expired!");
/// @dev Recover the address of the signature from the hashed digest;
/// @dev Ensure it equals the requester's address
require(
ecrecover(fxTxHash, sigV, sigR, sigS) == requester,
"Error: Address derived from transaction signature does not match the requester address");
/// @dev Transfer funds from each account to another.
require(
forceTransfer(self, symbolA, msg.sender, requester, valueA, "0x0"),
"Error: Unable to transfer funds to account.");
require(
forceTransfer(self, symbolB, requester, msg.sender, valueB, "0x0"),
"Error: Unable to transfer funds to account.");
emit FxSwap(symbolA, symbolB, valueA, valueB, expiration, fxTxHash);
return true;
}
/**
* @notice Deprecate a contract interface
* @dev | This is a low-level method to deprecate a contract interface.
* @dev | This is useful if the interface needs to be updated or becomes out of date
* @param self Internal storage proxying TokenIOStorage contract
* @param contractAddress Ethereum address of the contract interface
* @return {"success" : "Returns true if successfully called from another contract"}
*/
function setDeprecatedContract(Data storage self, address contractAddress) internal returns (bool success) {
require(contractAddress != 0x0,
"Error: cannot deprecate a null address.");
bytes32 id = keccak256(abi.encodePacked('depcrecated', contractAddress));
require(self.Storage.setBool(id, true),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract.");
return true;
}
/**
* @notice Return the deprecation status of a contract
* @param self Internal storage proxying TokenIOStorage contract
* @param contractAddress Ethereum address of the contract interface
* @return {"status" : "Return deprecation status (true/false) of the contract interface"}
*/
function isContractDeprecated(Data storage self, address contractAddress) internal view returns (bool status) {
bytes32 id = keccak256(abi.encodePacked('depcrecated', contractAddress));
return self.Storage.getBool(id);
}
/**
* @notice Set the Account Spending Period Limit as UNIX timestamp
* @dev | Each account has it's own daily spending limit
* @param self Internal storage proxying TokenIOStorage contract
* @param account Ethereum address of the account holder
* @param period Unix timestamp of the spending period
* @return {"success" : "Returns true is successfully called from a contract"}
*/
function setAccountSpendingPeriod(Data storage self, address account, uint period) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('limit.spending.period', account));
require(self.Storage.setUint(id, period),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract.");
return true;
}
/**
* @notice Get the Account Spending Period Limit as UNIX timestamp
* @dev | Each account has it's own daily spending limit
* @dev | If the current spending period has expired, it will be set upon next `transfer()`
* or `transferFrom()` request
* @param self Internal storage proxying TokenIOStorage contract
* @param account Ethereum address of the account holder
* @return {"period" : "Returns Unix timestamp of the current spending period"}
*/
function getAccountSpendingPeriod(Data storage self, address account) internal view returns (uint period) {
bytes32 id = keccak256(abi.encodePacked('limit.spending.period', account));
return self.Storage.getUint(id);
}
/**
* @notice Set the account spending limit amount
* @dev | Each account has it's own daily spending limit
* @param self Internal storage proxying TokenIOStorage contract
* @param account Ethereum address of the account holder
* @param limit Spending limit amount
* @return {"success" : "Returns true is successfully called from a contract"}
*/
function setAccountSpendingLimit(Data storage self, address account, uint limit) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('account.spending.limit', account));
require(self.Storage.setUint(id, limit),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract.");
return true;
}
/**
* @notice Get the account spending limit amount
* @dev | Each account has it's own daily spending limit
* @param self Internal storage proxying TokenIOStorage contract
* @param account Ethereum address of the account holder
* @return {"limit" : "Returns the account spending limit amount"}
*/
function getAccountSpendingLimit(Data storage self, address account) internal view returns (uint limit) {
bytes32 id = keccak256(abi.encodePacked('account.spending.limit', account));
return self.Storage.getUint(id);
}
/**
* @notice Set the account spending amount for the daily period
* @dev | Each account has it's own daily spending limit
* @dev | This transaction will throw if the new spending amount is greater than the limit
* @dev | This method is called in the `transfer()` and `transferFrom()` methods
* @param self Internal storage proxying TokenIOStorage contract
* @param account Ethereum address of the account holder
* @param amount Set the amount spent for the daily period
* @return {"success" : "Returns true is successfully called from a contract"}
*/
function setAccountSpendingAmount(Data storage self, address account, uint amount) internal returns (bool success) {
/// @dev NOTE: Always ensure the period is current when checking the daily spend limit
require(updateAccountSpendingPeriod(self, account),
"Error: Unable to update account spending period.");
uint updatedAmount = getAccountSpendingAmount(self, account).add(amount);
/// @dev Ensure the spend limit is greater than the amount spend for the period
require(
getAccountSpendingLimit(self, account) >= updatedAmount,
"Error: Account cannot exceed its daily spend limit.");
/// @dev Update the spending period amount if within limit
bytes32 id = keccak256(abi.encodePacked('account.spending.amount', account, getAccountSpendingPeriod(self, account)));
require(self.Storage.setUint(id, updatedAmount),
"Error: Unable to set storage value. Please ensure contract interface is allowed by the storage contract.");
return true;
}
/**
* @notice Low-level API to ensure the account spending period is always current
* @dev | This method is internally called by `setAccountSpendingAmount()` to ensure
* spending period is always the most current daily period.
* @param self Internal storage proxying TokenIOStorage contract
* @param account Ethereum address of the account holder
* @return {"success" : "Returns true is successfully called from a contract"}
*/
function updateAccountSpendingPeriod(Data storage self, address account) internal returns (bool success) {
uint begDate = getAccountSpendingPeriod(self, account);
if (begDate > now) {
return true;
} else {
uint duration = 86400; // 86400 seconds in a day
require(
setAccountSpendingPeriod(self, account, begDate.add(((now.sub(begDate)).div(duration).add(1)).mul(duration))),
"Error: Unable to update account spending period.");
return true;
}
}
/**
* @notice Return the amount spent during the current period
* @dev | Each account has it's own daily spending limit
* @param self Internal storage proxying TokenIOStorage contract
* @param account Ethereum address of the account holder
* @return {"amount" : "Returns the amount spent by the account during the current period"}
*/
function getAccountSpendingAmount(Data storage self, address account) internal view returns (uint amount) {
bytes32 id = keccak256(abi.encodePacked('account.spending.amount', account, getAccountSpendingPeriod(self, account)));
return self.Storage.getUint(id);
}
/**
* @notice Return the amount remaining during the current period
* @dev | Each account has it's own daily spending limit
* @param self Internal storage proxying TokenIOStorage contract
* @param account Ethereum address of the account holder
* @return {"amount" : "Returns the amount remaining by the account during the current period"}
*/
function getAccountSpendingRemaining(Data storage self, address account) internal view returns (uint remainingLimit) {
return getAccountSpendingLimit(self, account).sub(getAccountSpendingAmount(self, account));
}
/**
* @notice Set the foreign currency exchange rate to USD in basis points
* @dev | This value should always be relative to USD pair; e.g. JPY/USD, GBP/USD, etc.
* @param self Internal storage proxying TokenIOStorage contract
* @param currency The TokenIO currency symbol (e.g. USDx, JPYx, GBPx)
* @param bpsRate Basis point rate of foreign currency exchange rate to USD
* @return { "success": "Returns true if successfully called from another contract"}
*/
function setFxUSDBPSRate(Data storage self, string currency, uint bpsRate) internal returns (bool success) {
bytes32 id = keccak256(abi.encodePacked('fx.usd.rate', currency));
require(
self.Storage.setUint(id, bpsRate),
"Error: Unable to update account spending period.");
return true;
}
/**
* @notice Return the foreign currency USD exchanged amount in basis points
* @param self Internal storage proxying TokenIOStorage contract
* @param currency The TokenIO currency symbol (e.g. USDx, JPYx, GBPx)
* @return {"usdAmount" : "Returns the foreign currency amount in USD"}
*/
function getFxUSDBPSRate(Data storage self, string currency) internal view returns (uint bpsRate) {
bytes32 id = keccak256(abi.encodePacked('fx.usd.rate', currency));
return self.Storage.getUint(id);
}
/**
* @notice Return the foreign currency USD exchanged amount
* @param self Internal storage proxying TokenIOStorage contract
* @param currency The TokenIO currency symbol (e.g. USDx, JPYx, GBPx)
* @param fxAmount Amount of foreign currency to exchange into USD
* @return {"amount" : "Returns the foreign currency amount in USD"}
*/
function getFxUSDAmount(Data storage self, string currency, uint fxAmount) internal view returns (uint amount) {
uint usdDecimals = getTokenDecimals(self, 'USDx');
uint fxDecimals = getTokenDecimals(self, currency);
/// @dev ensure decimal precision is normalized to USD decimals
uint usdAmount = ((fxAmount.mul(getFxUSDBPSRate(self, currency)).div(10000)).mul(10**usdDecimals)).div(10**fxDecimals);
return usdAmount;
}
}
/*
COPYRIGHT 2018 Token, Inc.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@title ERC20 Compliant Smart Contract for Token, Inc.
@author Ryan Tate <[email protected]>, Sean Pollock <[email protected]>
@notice Contract uses generalized storage contract, `TokenIOStorage`, for
upgradeability of interface contract.
@dev In the event that the main contract becomes deprecated, the upgraded contract
will be set as the owner of this contract, and use this contract's storage to
maintain data consistency between contract.
*/
contract TokenIOERC20FeesApply is Ownable {
using SafeMath for uint;
//// @dev Set reference to TokenIOLib interface which proxies to TokenIOStorage
using TokenIOLib for TokenIOLib.Data;
TokenIOLib.Data lib;
event Transfer(address indexed from, address indexed to, uint256 amount);
/**
* @notice Constructor method for ERC20 contract
* @param _storageContract address of TokenIOStorage contract
*/
constructor(address _storageContract) public {
//// @dev Set the storage contract for the interface
//// @dev This contract will be unable to use the storage constract until
//// @dev contract address is authorized with the storage contract
//// @dev Once authorized, Use the `setParams` method to set storage values
lib.Storage = TokenIOStorage(_storageContract);
//// @dev set owner to contract initiator
owner[msg.sender] = true;
}
/**
@notice Sets erc20 globals and fee paramters
@param _name Full token name 'USD by token.io'
@param _symbol Symbol name 'USDx'
@param _tla Three letter abbreviation 'USD'
@param _version Release version 'v0.0.1'
@param _decimals Decimal precision
@param _feeContract Address of fee contract
@return { "success" : "Returns true if successfully called from another contract"}
*/
function setParams(
string _name,
string _symbol,
string _tla,
string _version,
uint _decimals,
address _feeContract,
uint _fxUSDBPSRate
) onlyOwner public returns (bool success) {
require(lib.setTokenName(_name),
"Error: Unable to set token name. Please check arguments.");
require(lib.setTokenSymbol(_symbol),
"Error: Unable to set token symbol. Please check arguments.");
require(lib.setTokenTLA(_tla),
"Error: Unable to set token TLA. Please check arguments.");
require(lib.setTokenVersion(_version),
"Error: Unable to set token version. Please check arguments.");
require(lib.setTokenDecimals(_symbol, _decimals),
"Error: Unable to set token decimals. Please check arguments.");
require(lib.setFeeContract(_feeContract),
"Error: Unable to set fee contract. Please check arguments.");
require(lib.setFxUSDBPSRate(_symbol, _fxUSDBPSRate),
"Error: Unable to set fx USD basis points rate. Please check arguments.");
return true;
}
/**
* @notice Gets name of token
* @return {"_name" : "Returns name of token"}
*/
function name() public view returns (string _name) {
return lib.getTokenName(address(this));
}
/**
* @notice Gets symbol of token
* @return {"_symbol" : "Returns symbol of token"}
*/
function symbol() public view returns (string _symbol) {
return lib.getTokenSymbol(address(this));
}
/**
* @notice Gets three-letter-abbreviation of token
* @return {"_tla" : "Returns three-letter-abbreviation of token"}
*/
function tla() public view returns (string _tla) {
return lib.getTokenTLA(address(this));
}
/**
* @notice Gets version of token
* @return {"_version" : "Returns version of token"}
*/
function version() public view returns (string _version) {
return lib.getTokenVersion(address(this));
}
/**
* @notice Gets decimals of token
* @return {"_decimals" : "Returns number of decimals"}
*/
function decimals() public view returns (uint _decimals) {
return lib.getTokenDecimals(lib.getTokenSymbol(address(this)));
}
/**
* @notice Gets total supply of token
* @return {"supply" : "Returns current total supply of token"}
*/
function totalSupply() public view returns (uint supply) {
return lib.getTokenSupply(lib.getTokenSymbol(address(this)));
}
/**
* @notice Gets allowance that spender has with approver
* @param account Address of approver
* @param spender Address of spender
* @return {"amount" : "Returns allowance of given account and spender"}
*/
function allowance(address account, address spender) public view returns (uint amount) {
return lib.getTokenAllowance(lib.getTokenSymbol(address(this)), account, spender);
}
/**
* @notice Gets balance of account
* @param account Address for balance lookup
* @return {"balance" : "Returns balance amount"}
*/
function balanceOf(address account) public view returns (uint balance) {
return lib.getTokenBalance(lib.getTokenSymbol(address(this)), account);
}
/**
* @notice Gets fee parameters
* @return {
"bps":"Fee amount as a mesuare of basis points",
"min":"Minimum fee amount",
"max":"Maximum fee amount",
"flat":"Flat fee amount",
"contract":"Address of fee contract"
}
*/
function getFeeParams() public view returns (uint bps, uint min, uint max, uint flat, bytes feeMsg, address feeAccount) {
address feeContract = lib.getFeeContract(address(this));
return (
lib.getFeeBPS(feeContract),
lib.getFeeMin(feeContract),
lib.getFeeMax(feeContract),
lib.getFeeFlat(feeContract),
lib.getFeeMsg(feeContract),
feeContract
);
}
/**
* @notice Calculates fee of a given transfer amount
* @param amount Amount to calculcate fee value
* @return {"fees": "Returns the calculated transaction fees based on the fee contract parameters"}
*/
function calculateFees(uint amount) public view returns (uint fees) {
return lib.calculateFees(lib.getFeeContract(address(this)), amount);
}
/**
* @notice transfers 'amount' from msg.sender to a receiving account 'to'
* @param to Receiving address
* @param amount Transfer amount
* @return {"success" : "Returns true if transfer succeeds"}
*/
function transfer(address to, uint amount) public notDeprecated returns (bool success) {
address feeContract = lib.getFeeContract(address(this));
string memory currency = lib.getTokenSymbol(address(this));
/// @notice send transfer through library
/// @dev !!! mutates storage state
require(
lib.forceTransfer(currency, msg.sender, to, amount, "0x0"),
"Error: Unable to transfer funds to account.");
// @dev transfer fees to fee contract
require(
lib.forceTransfer(currency, msg.sender, feeContract, calculateFees(amount), lib.getFeeMsg(feeContract)),
"Error: Unable to transfer fees to fee contract.");
emit Transfer(msg.sender, to, amount);
return true;
}
/**
* @notice spender transfers from approvers account to the reciving account
* @param from Approver's address
* @param to Receiving address
* @param amount Transfer amount
* @return {"success" : "Returns true if transferFrom succeeds"}
*/
function transferFrom(address from, address to, uint amount) public notDeprecated returns (bool success) {
address feeContract = lib.getFeeContract(address(this));
string memory currency = lib.getTokenSymbol(address(this));
uint fees = calculateFees(amount);
/// @notice sends transferFrom through library
/// @dev !!! mutates storage state
require(
lib.forceTransfer(currency, from, to, amount, "0x0"),
"Error: Unable to transfer funds. Please check your parameters and ensure the spender has the approved amount of funds to transfer."
);
require(
lib.forceTransfer(currency, from, feeContract, fees, lib.getFeeMsg(feeContract)),
"Error: Unable to transfer funds. Please check your parameters and ensure the spender has the approved amount of funds to transfer."
);
/// @notice This transaction will fail if the msg.sender does not have an approved allowance.
require(
lib.updateAllowance(lib.getTokenSymbol(address(this)), from, amount.add(fees)),
"Error: Unable to update allowance for spender."
);
emit Transfer(from, to, amount);
return true;
}
/**
* @notice approves spender a given amount
* @param spender Spender's address
* @param amount Allowance amount
* @return {"success" : "Returns true if approve succeeds"}
*/
function approve(address spender, uint amount) public notDeprecated returns (bool success) {
/// @notice sends approve through library
/// @dev !!! mtuates storage states
require(
lib.approveAllowance(spender, amount),
"Error: Unable to approve allowance for spender. Please ensure spender is not null and does not have a frozen balance."
);
return true;
}
/**
* @notice gets currency status of contract
* @return {"deprecated" : "Returns true if deprecated, false otherwise"}
*/
function deprecateInterface() public onlyOwner returns (bool deprecated) {
require(lib.setDeprecatedContract(address(this)),
"Error: Unable to deprecate contract!");
return true;
}
modifier notDeprecated() {
/// @notice throws if contract is deprecated
require(!lib.isContractDeprecated(address(this)),
"Error: Contract has been deprecated, cannot perform operation!");
_;
}
} | * @notice Gets version of token @return {"_version" : "Returns version of token"}/ | function version() public view returns (string _version) {
return lib.getTokenVersion(address(this));
}
| 12,990,194 | [
1,
3002,
1177,
434,
1147,
327,
12528,
67,
1589,
6,
294,
315,
1356,
1177,
434,
1147,
6,
4004,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1177,
1435,
1071,
1476,
1135,
261,
1080,
389,
1589,
13,
288,
203,
1377,
327,
2561,
18,
588,
1345,
1444,
12,
2867,
12,
2211,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (governance/extensions/GovernorSettings.sol)
pragma solidity ^0.8.0;
import "../Governor.sol";
import "../../utils/Timers.sol";
/**
* @dev Extension of {Governor} for settings updatable through governance.
*
* _Available since v4.4._
*/
abstract contract GovernorSettings is Governor {
uint256 private _contestStart;
uint256 private _votingDelay;
uint256 private _votingPeriod;
uint256 private _contestSnapshot;
uint256 private _proposalThreshold;
uint256 private _numAllowedProposalSubmissions;
uint256 private _maxProposalCount;
address private _creator;
event ContestStartSet(uint256 oldContestStart, uint256 newContestStart);
event VotingDelaySet(uint256 oldVotingDelay, uint256 newVotingDelay);
event VotingPeriodSet(uint256 oldVotingPeriod, uint256 newVotingPeriod);
event ContestSnapshotSet(uint256 oldContestSnapshot, uint256 newContestSnapshot);
event ProposalThresholdSet(uint256 oldProposalThreshold, uint256 newProposalThreshold);
event NumAllowedProposalSubmissionsSet(uint256 oldNumAllowedProposalSubmissions, uint256 newNumAllowedProposalSubmissions);
event MaxProposalCountSet(uint256 oldMaxProposalCount, uint256 newMaxProposalCount);
event CreatorSet(address oldCreator, address newCreator);
/**
* @dev Initialize the governance parameters.
*/
constructor(
uint256 initialContestStart,
uint256 initialVotingDelay,
uint256 initialVotingPeriod,
uint256 initialContestSnapshot,
uint256 initialProposalThreshold,
uint256 initialNumAllowedProposalSubmissions,
uint256 initialMaxProposalCount
) {
_setContestStart(initialContestStart);
_setVotingDelay(initialVotingDelay);
_setVotingPeriod(initialVotingPeriod);
_setContestSnapshot(initialContestSnapshot);
_setProposalThreshold(initialProposalThreshold);
_setNumAllowedProposalSubmissions(initialNumAllowedProposalSubmissions);
_setMaxProposalCount(initialMaxProposalCount);
_setCreator(msg.sender);
}
/**
* @dev See {IGovernor-contestStart}.
*/
function contestStart() public view virtual override returns (uint256) {
return _contestStart;
}
/**
* @dev See {IGovernor-votingDelay}.
*/
function votingDelay() public view virtual override returns (uint256) {
return _votingDelay;
}
/**
* @dev See {IGovernor-votingPeriod}.
*/
function votingPeriod() public view virtual override returns (uint256) {
return _votingPeriod;
}
/**
* @dev See {IGovernor-contestSnapshot}.
*/
function contestSnapshot() public view virtual override returns (uint256) {
return _contestSnapshot;
}
/**
* @dev See {Governor-proposalThreshold}.
*/
function proposalThreshold() public view virtual override returns (uint256) {
return _proposalThreshold;
}
/**
* @dev See {Governor-numAllowedProposalSubmissions}.
*/
function numAllowedProposalSubmissions() public view virtual override returns (uint256) {
return _numAllowedProposalSubmissions;
}
/**
* @dev Max number of proposals allowed in this contest
*/
function maxProposalCount() public view virtual override returns (uint256) {
return _maxProposalCount;
}
/**
* @dev See {IGovernor-creator}.
*/
function creator() public view virtual override returns (address) {
return _creator;
}
/**
* @dev Internal setter for the contestStart.
*
* Emits a {ContestStartSet} event.
*/
function _setContestStart(uint256 newContestStart) internal virtual {
emit ContestStartSet(_contestStart, newContestStart);
_contestStart = newContestStart;
}
/**
* @dev Internal setter for the voting delay.
*
* Emits a {VotingDelaySet} event.
*/
function _setVotingDelay(uint256 newVotingDelay) internal virtual {
emit VotingDelaySet(_votingDelay, newVotingDelay);
_votingDelay = newVotingDelay;
}
/**
* @dev Internal setter for the voting period.
*
* Emits a {VotingPeriodSet} event.
*/
function _setVotingPeriod(uint256 newVotingPeriod) internal virtual {
// voting period must be at least one block long
require(newVotingPeriod > 0, "GovernorSettings: voting period too low");
emit VotingPeriodSet(_votingPeriod, newVotingPeriod);
_votingPeriod = newVotingPeriod;
}
/**
* @dev Internal setter for the contestStart.
*
* Emits a {ContestSnapshotSet} event.
*/
function _setContestSnapshot(uint256 newContestSnapshot) internal virtual {
emit ContestSnapshotSet(_contestSnapshot, newContestSnapshot);
_contestSnapshot = newContestSnapshot;
}
/**
* @dev Internal setter for the proposal threshold.
*
* Emits a {ProposalThresholdSet} event.
*/
function _setProposalThreshold(uint256 newProposalThreshold) internal virtual {
emit ProposalThresholdSet(_proposalThreshold, newProposalThreshold);
_proposalThreshold = newProposalThreshold;
}
/**
* @dev Internal setter for the number of allowed proposal submissions per permissioned address.
*
* Emits a {NumAllowedProposalSubmissionsSet} event.
*/
function _setNumAllowedProposalSubmissions(uint256 newNumAllowedProposalSubmissions) internal virtual {
emit NumAllowedProposalSubmissionsSet(_numAllowedProposalSubmissions, newNumAllowedProposalSubmissions);
_numAllowedProposalSubmissions = newNumAllowedProposalSubmissions;
}
/**
* @dev Internal setter for the max proposal count.
*
* Emits a {MaxProposalCountSet} event.
*/
function _setMaxProposalCount(uint256 newMaxProposalCount) internal virtual {
emit MaxProposalCountSet(_maxProposalCount, newMaxProposalCount);
_maxProposalCount = newMaxProposalCount;
}
/**
* @dev Internal setter for creator.
*
* Emits a {CreatorSet} event.
*/
function _setCreator(address newCreator) internal virtual {
emit CreatorSet(_creator, newCreator);
_creator = newCreator;
}
}
| * @dev See {IGovernor-contestStart}./ | function contestStart() public view virtual override returns (uint256) {
return _contestStart;
}
| 7,297,529 | [
1,
9704,
288,
3047,
1643,
29561,
17,
1213,
395,
1685,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
466,
395,
1685,
1435,
1071,
1476,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
389,
1213,
395,
1685,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&&BBBBBBBGG&@@@@@@@@@&&&&&&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&P!: :[email protected]@@@&P7^. .^?G&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@&J. :#@@@#7. :Y&@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@&! [email protected]@@B: !&@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@P [email protected]@@~ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@J [email protected]@&. [email protected]@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@G [email protected]@@. [email protected]@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@. &@@Y #@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@& [email protected]@@&##########&&&&&&&&&&&#############@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@& [email protected]@@@@@@@@@@@@@#B######&&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@. &@@@@@@@@@@@@@B~ .:!5&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@B [email protected]@@@@@@@@@@@@@@&! .7#@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@Y [email protected]@@@@@@@@@@@@@@@B. ^#@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@G [email protected]@@@@@@@@@@@@@@@@: [email protected]@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@? [email protected]@@@@@@@@@@@@@@@@. ^@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@5: [email protected]@@@@@@@@@@@@@@B [email protected]@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&G7^. :[email protected]@@@@@@@@@@@@@: #@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&#######BB&@@@@@@@@@@@@@7 [email protected]@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@? [email protected]@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@. ^@@@: [email protected]@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@Y [email protected]@# ^@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@! [email protected]@@: [email protected]@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@Y [email protected]@@^ [email protected]@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@&~ !&@@&. :[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@&?. .J&@@@? [email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#Y~. :!5&@@@#7 .^[email protected]@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&#BGGGB#&@@@@@@@@BPGGGGGGB#&@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
// @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";
import "./common/SaleCommon.sol";
contract ETHSale is AccessControl, SaleCommon {
struct Sale {
uint256 id;
uint256 volume;
uint256 presale;
uint256 starttime; // to start immediately, set starttime = 0
uint256 endtime;
bool active;
bytes32 merkleRoot; // Merkle root of the entrylist Merkle tree, 0x00 for non-merkle sale
uint256 maxQuantity;
uint256 price; // in Wei, where 10^18 Wei = 1 ETH
uint256 startTokenIndex;
uint256 maxPLOTs;
uint256 mintedPLOTs;
}
Sale[] public sales;
mapping(uint256 => mapping(address => uint256)) public minted; // sale ID => account => quantity
/// @notice Constructor
/// @param _plot Storyverse Plot contract
constructor(address _plot) SaleCommon(_plot) {}
/// @notice Get the current sale
/// @return Current sale
function currentSale() public view returns (Sale memory) {
require(sales.length > 0, "no current sale");
return sales[sales.length - 1];
}
/// @notice Get the current sale ID
/// @return Current sale ID
function currentSaleId() public view returns (uint256) {
require(sales.length > 0, "no current sale");
return sales.length - 1;
}
/// @notice Checks if the provided token ID parameters are likely to overlap a previous or current sale
/// @param _startTokenIndex Token index to start the sale from
/// @param _maxPLOTs Maximum number of PLOTs that can be minted in this sale
/// @return valid_ If the current token ID range paramters are likely safe
function isSafeTokenIdRange(uint256 _startTokenIndex, uint256 _maxPLOTs)
external
view
returns (bool valid_)
{
return _isSafeTokenIdRange(_startTokenIndex, _maxPLOTs, sales.length);
}
function _checkSafeTokenIdRange(
uint256 _startTokenIndex,
uint256 _maxPLOTs,
uint256 _maxSaleId
) internal view {
// If _maxSaleId is passed in as the current sale ID, then
// the check will skip the current sale ID in _isSafeTokenIdRange()
// since in that case _maxSaleId == sales.length - 1
require(
_isSafeTokenIdRange(_startTokenIndex, _maxPLOTs, _maxSaleId),
"overlapping token ID range"
);
}
function _isSafeTokenIdRange(
uint256 _startTokenIndex,
uint256 _maxPLOTs,
uint256 _maxSaleId
) internal view returns (bool valid_) {
if (_maxPLOTs == 0) {
return true;
}
for (uint256 i = 0; i < _maxSaleId; i++) {
// if no minted PLOTs in sale, ignore
if (sales[i].mintedPLOTs == 0) {
continue;
}
uint256 saleStartTokenIndex = sales[i].startTokenIndex;
uint256 saleMintedPLOTs = sales[i].mintedPLOTs;
if (_startTokenIndex < saleStartTokenIndex) {
// start index is less than the sale's start token index, so ensure
// it doesn't extend into the sale's range if max PLOTs are minted
if (_startTokenIndex + _maxPLOTs - 1 >= saleStartTokenIndex) {
return false;
}
} else {
// start index greater than or equal to the sale's start token index, so ensure
// it starts after the sale's start token index + the number of PLOTs minted
if (_startTokenIndex <= saleStartTokenIndex + saleMintedPLOTs - 1) {
return false;
}
}
}
return true;
}
/// @notice Adds a new sale
/// @param _volume Volume of the sale
/// @param _presale Presale of the sale
/// @param _starttime Start time of the sale
/// @param _endtime End time of the sale
/// @param _active Whether the sale is active
/// @param _merkleRoot Merkle root of the entry list Merkle tree, 0x00 for non-merkle sale
/// @param _maxQuantity Maximum number of PLOTs per account that can be sold
/// @param _price Price of each PLOT
/// @param _startTokenIndex Token index to start the sale from
/// @param _maxPLOTs Maximum number of PLOTs that can be minted in this sale
function addSale(
uint256 _volume,
uint256 _presale,
uint256 _starttime,
uint256 _endtime,
bool _active,
bytes32 _merkleRoot,
uint256 _maxQuantity,
uint256 _price,
uint256 _startTokenIndex,
uint256 _maxPLOTs
) public onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = sales.length;
checkTokenParameters(_volume, _presale, _startTokenIndex);
_checkSafeTokenIdRange(_startTokenIndex, _maxPLOTs, saleId);
Sale memory sale = Sale({
id: saleId,
volume: _volume,
presale: _presale,
starttime: _starttime,
endtime: _endtime,
active: _active,
merkleRoot: _merkleRoot,
maxQuantity: _maxQuantity,
price: _price,
startTokenIndex: _startTokenIndex,
maxPLOTs: _maxPLOTs,
mintedPLOTs: 0
});
sales.push(sale);
emit SaleAdded(msg.sender, saleId);
}
/// @notice Updates the current sale
/// @param _volume Volume of the sale
/// @param _presale Presale of the sale
/// @param _starttime Start time of the sale
/// @param _endtime End time of the sale
/// @param _active Whether the sale is active
/// @param _merkleRoot Merkle root of the entry list Merkle tree, 0x00 for non-merkle sale
/// @param _maxQuantity Maximum number of PLOTs per account that can be sold
/// @param _price Price of each PLOT
/// @param _startTokenIndex Token index to start the sale from
/// @param _maxPLOTs Maximum number of PLOTs that can be minted in this sale
function updateSale(
uint256 _volume,
uint256 _presale,
uint256 _starttime,
uint256 _endtime,
bool _active,
bytes32 _merkleRoot,
uint256 _maxQuantity,
uint256 _price,
uint256 _startTokenIndex,
uint256 _maxPLOTs
) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
checkTokenParameters(_volume, _presale, _startTokenIndex);
_checkSafeTokenIdRange(_startTokenIndex, _maxPLOTs, saleId);
Sale memory sale = Sale({
id: saleId,
volume: _volume,
presale: _presale,
starttime: _starttime,
endtime: _endtime,
active: _active,
merkleRoot: _merkleRoot,
maxQuantity: _maxQuantity,
price: _price,
startTokenIndex: _startTokenIndex,
maxPLOTs: _maxPLOTs,
mintedPLOTs: sales[saleId].mintedPLOTs
});
sales[saleId] = sale;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the volume of the current sale
/// @param _volume Volume of the sale
function updateSaleVolume(uint256 _volume) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
checkTokenParameters(_volume, sales[saleId].presale, sales[saleId].startTokenIndex);
sales[saleId].volume = _volume;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the presale of the current sale
/// @param _presale Presale of the sale
function updateSalePresale(uint256 _presale) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
checkTokenParameters(sales[saleId].volume, _presale, sales[saleId].startTokenIndex);
sales[saleId].presale = _presale;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the start time of the current sale
/// @param _starttime Start time of the sale
function updateSaleStarttime(uint256 _starttime) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
sales[saleId].starttime = _starttime;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the end time of the current sale
/// @param _endtime End time of the sale
function updateSaleEndtime(uint256 _endtime) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
sales[saleId].endtime = _endtime;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the active status of the current sale
/// @param _active Whether the sale is active
function updateSaleActive(bool _active) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
sales[saleId].active = _active;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the merkle root of the current sale
/// @param _merkleRoot Merkle root of the entry list Merkle tree, 0x00 for non-merkle sale
function updateSaleMerkleRoot(bytes32 _merkleRoot) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
sales[saleId].merkleRoot = _merkleRoot;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the max quantity of the current sale
/// @param _maxQuantity Maximum number of PLOTs per account that can be sold
function updateSaleMaxQuantity(uint256 _maxQuantity) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
sales[saleId].maxQuantity = _maxQuantity;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the price of each PLOT for the current sale
/// @param _price Price of each PLOT
function updateSalePrice(uint256 _price) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
sales[saleId].price = _price;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the start token index of the current sale
/// @param _startTokenIndex Token index to start the sale from
function updateSaleStartTokenIndex(uint256 _startTokenIndex)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
uint256 saleId = currentSaleId();
_checkSafeTokenIdRange(_startTokenIndex, sales[saleId].maxPLOTs, saleId);
checkTokenParameters(sales[saleId].volume, sales[saleId].presale, _startTokenIndex);
sales[saleId].startTokenIndex = _startTokenIndex;
emit SaleUpdated(msg.sender, saleId);
}
/// @notice Updates the of the current sale
/// @param _maxPLOTs Maximum number of PLOTs that can be minted in this sale
function updateSaleMaxPLOTs(uint256 _maxPLOTs) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
_checkSafeTokenIdRange(sales[saleId].startTokenIndex, _maxPLOTs, saleId);
sales[saleId].maxPLOTs = _maxPLOTs;
emit SaleUpdated(msg.sender, saleId);
}
function _mintTo(
address _to,
uint256 _volume,
uint256 _presale,
uint256 _startTokenIndex,
uint256 _quantity
) internal {
require(_quantity > 0, "quantity must be greater than 0");
for (uint256 i = 0; i < _quantity; i++) {
uint256 tokenIndex = _startTokenIndex + i;
uint256 tokenId = buildTokenId(_volume, _presale, tokenIndex);
IStoryversePlot(plot).safeMint(_to, tokenId);
}
emit Minted(msg.sender, _to, _quantity, msg.value);
}
/// @notice Mints new tokens in exchange for ETH
/// @param _to Owner of the newly minted token
/// @param _quantity Quantity of tokens to mint
function mintTo(address _to, uint256 _quantity) external payable nonReentrant {
Sale memory sale = currentSale();
// only proceed if no merkle root is set
require(sale.merkleRoot == bytes32(0), "merkle sale requires valid proof");
// check sale validity
require(sale.active, "sale is inactive");
require(block.timestamp >= sale.starttime, "sale has not started");
require(block.timestamp < sale.endtime, "sale has ended");
// validate payment and authorized quantity
require(msg.value == sale.price * _quantity, "incorrect payment for quantity and price");
require(
minted[sale.id][msg.sender] + _quantity <= sale.maxQuantity,
"exceeds allowed quantity"
);
// check sale supply
require(sale.mintedPLOTs + _quantity <= sale.maxPLOTs, "insufficient supply");
sales[sale.id].mintedPLOTs += _quantity;
minted[sale.id][msg.sender] += _quantity;
_mintTo(
_to,
sale.volume,
sale.presale,
sale.startTokenIndex + sale.mintedPLOTs,
_quantity
);
}
/// @notice Mints new tokens in exchange for ETH based on the sale's entry list
/// @param _proof Merkle proof to validate the caller is on the sale's entry list
/// @param _maxQuantity Max quantity that the caller can mint
/// @param _to Owner of the newly minted token
/// @param _quantity Quantity of tokens to mint
function entryListMintTo(
bytes32[] calldata _proof,
uint256 _maxQuantity,
address _to,
uint256 _quantity
) external payable nonReentrant {
Sale memory sale = currentSale();
// validate merkle proof
bytes32 leaf = keccak256(abi.encodePacked(msg.sender, _maxQuantity));
require(MerkleProof.verify(_proof, sale.merkleRoot, leaf), "invalid proof");
// check sale validity
require(sale.active, "sale is inactive");
require(block.timestamp >= sale.starttime, "sale has not started");
require(block.timestamp < sale.endtime, "sale has ended");
// validate payment and authorized quantity
require(msg.value == sale.price * _quantity, "incorrect payment for quantity and price");
require(
minted[sale.id][msg.sender] + _quantity <= Math.max(sale.maxQuantity, _maxQuantity),
"exceeds allowed quantity"
);
// check sale supply
require(sale.mintedPLOTs + _quantity <= sale.maxPLOTs, "insufficient supply");
sales[sale.id].mintedPLOTs += _quantity;
minted[sale.id][msg.sender] += _quantity;
_mintTo(
_to,
sale.volume,
sale.presale,
sale.startTokenIndex + sale.mintedPLOTs,
_quantity
);
}
/// @notice Administrative mint function within the constraints of the current sale, skipping some checks
/// @param _to Owner of the newly minted token
/// @param _quantity Quantity of tokens to mint
function adminSaleMintTo(address _to, uint256 _quantity) external onlyRole(MINTER_ROLE) {
Sale memory sale = currentSale();
// check sale supply
require(sale.mintedPLOTs + _quantity <= sale.maxPLOTs, "insufficient supply");
sales[sale.id].mintedPLOTs += _quantity;
minted[sale.id][msg.sender] += _quantity;
_mintTo(
_to,
sale.volume,
sale.presale,
sale.startTokenIndex + sale.mintedPLOTs,
_quantity
);
}
/// @notice Administrative mint function
/// @param _to Owner of the newly minted token
/// @param _quantity Quantity of tokens to mint
function adminMintTo(
address _to,
uint256 _volume,
uint256 _presale,
uint256 _startTokenIndex,
uint256 _quantity
) external onlyRole(DEFAULT_ADMIN_ROLE) {
// add a sale (clobbering any current sale) to ensure token ranges
// are respected and recorded
addSale(
_volume,
_presale,
block.timestamp,
block.timestamp,
false,
bytes32(0),
0,
2**256 - 1,
_startTokenIndex,
_quantity
);
// record the sale as fully minted
sales[sales.length - 1].mintedPLOTs = _quantity;
_mintTo(_to, _volume, _presale, _startTokenIndex, _quantity);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merklee tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a / b + (a % b == 0 ? 0 : 1);
}
}
// SPDX-License-Identifier: Unlicensed
pragma solidity 0.8.13;
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "../interfaces/IStoryversePlot.sol";
contract SaleCommon is AccessControl, ReentrancyGuard {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
address public plot;
/// @notice Emitted when a new sale is added to the contract
/// @param who Admin that created the sale
/// @param saleId Sale ID, will be the current sale
event SaleAdded(address who, uint256 saleId);
/// @notice Emitted when the current sale is updated
/// @param who Admin that updated the sale
/// @param saleId Sale ID, will be the current sale
event SaleUpdated(address who, uint256 saleId);
/// @notice Emitted when new tokens are sold and minted
/// @param who Purchaser (payer) for the tokens
/// @param to Owner of the newly minted tokens
/// @param quantity Quantity of tokens minted
/// @param amount Amount paid in Wei
event Minted(address who, address to, uint256 quantity, uint256 amount);
/// @notice Emitted when funds are withdrawn from the contract
/// @param to Recipient of the funds
/// @param amount Amount sent in Wei
event FundsWithdrawn(address to, uint256 amount);
/// @notice Constructor
/// @param _plot Storyverse Plot contract
constructor(address _plot) {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(MINTER_ROLE, msg.sender);
plot = _plot;
}
function checkTokenParameters(
uint256 _volume,
uint256 _presale,
uint256 _tokenIndex
) internal pure {
require(_volume > 0 && _volume < 2**10, "invalid volume");
require(_presale < 2**2, "invalid presale");
require(_tokenIndex < 2**32, "invalid token index");
}
function buildTokenId(
uint256 _volume,
uint256 _presale,
uint256 _tokenIndex
) public view returns (uint256 tokenId_) {
checkTokenParameters(_volume, _presale, _tokenIndex);
uint256 superSecretSpice = uint256(
keccak256(
abi.encodePacked(
(0x4574c8c75d6e88acd28f7e467dac97b5c60c3838d9dad993900bdf402152228e ^
uint256(blockhash(block.number - 1))) + _tokenIndex
)
)
) & 0xffffffff;
tokenId_ = (_volume << 245) | (_presale << 243) | (superSecretSpice << 211) | _tokenIndex;
return tokenId_;
}
/// @notice Decode a token ID into its component parts
/// @param _tokenId Token ID
/// @return volume_ Volume of the sale
/// @return presale_ Presale of the sale
/// @return superSecretSpice_ Super secret spice
/// @return tokenIndex_ Token index
function decodeTokenId(uint256 _tokenId)
external
pure
returns (
uint256 volume_,
uint256 presale_,
uint256 superSecretSpice_,
uint256 tokenIndex_
)
{
volume_ = (_tokenId >> 245) & 0x3ff;
presale_ = (_tokenId >> 243) & 0x3;
superSecretSpice_ = (_tokenId >> 211) & 0xffffffff;
tokenIndex_ = _tokenId & 0xffffffff;
return (volume_, presale_, superSecretSpice_, tokenIndex_);
}
/// @notice Withdraw funds from the contract
/// @param _to Recipient of the funds
/// @param _amount Amount sent, in Wei
function withdrawFunds(address payable _to, uint256 _amount)
external
onlyRole(DEFAULT_ADMIN_ROLE)
nonReentrant
{
require(_amount <= address(this).balance, "not enough funds");
_to.transfer(_amount);
emit FundsWithdrawn(_to, _amount);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: Unlicensed
pragma solidity ~0.8.13;
import "@openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol";
import "@imtbl/imx-contracts/contracts/IMintable.sol";
import "./IExtensionManager.sol";
interface IStoryversePlot is
IERC2981Upgradeable,
IERC721MetadataUpgradeable,
IAccessControlUpgradeable,
IMintable
{
/// @notice Emitted when a new extension manager is set
/// @param who Admin that set the extension manager
/// @param extensionManager New extension manager contract
event ExtensionManagerSet(address indexed who, address indexed extensionManager);
/// @notice Emitted when a new Immutable X is set
/// @param who Admin that set the extension manager
/// @param imx New Immutable X address
event IMXSet(address indexed who, address indexed imx);
/// @notice Emitted when a new token is minted and a blueprint is set
/// @param to Owner of the newly minted token
/// @param tokenId Token ID that was minted
/// @param blueprint Blueprint extracted from the blob
event AssetMinted(address to, uint256 tokenId, bytes blueprint);
/// @notice Emitted when the new base URI is set
/// @param who Admin that set the base URI
event BaseURISet(address indexed who);
/// @notice Emitted when funds are withdrawn from the contract
/// @param to Recipient of the funds
/// @param amount Amount sent in Wei
event FundsWithdrawn(address to, uint256 amount);
/// @notice Get the base URI
/// @return uri_ Base URI
function baseURI() external returns (string memory uri_);
/// @notice Get the extension manager
/// @return extensionManager_ Extension manager
function extensionManager() external returns (IExtensionManager extensionManager_);
/// @notice Get the Immutable X address
/// @return imx_ Immutable X address
function imx() external returns (address imx_);
/// @notice Get the blueprint for a token ID
/// @param _tokenId Token ID
/// @return blueprint_ Blueprint
function blueprints(uint256 _tokenId) external returns (bytes memory blueprint_);
/// @notice Sets a new extension manager
/// @param _extensionManager New extension manager
function setExtensionManager(address _extensionManager) external;
/// @notice Mint a new token
/// @param _to Owner of the newly minted token
/// @param _tokenId Token ID
function safeMint(address _to, uint256 _tokenId) external;
/// @notice Sets a base URI
/// @param _uri Base URI
function setBaseURI(string calldata _uri) external;
/// @notice Get PLOT data for the token ID
/// @param _tokenId Token ID
/// @param _in Input data
/// @return out_ Output data
function getPLOTData(uint256 _tokenId, bytes memory _in) external returns (bytes memory out_);
/// @notice Sets PLOT data for the token ID
/// @param _tokenId Token ID
/// @param _in Input data
/// @return out_ Output data
function setPLOTData(uint256 _tokenId, bytes memory _in) external returns (bytes memory out_);
/// @notice Pays for PLOT data of the token ID
/// @param _tokenId Token ID
/// @param _in Input data
/// @return out_ Output data
function payPLOTData(uint256 _tokenId, bytes memory _in)
external
payable
returns (bytes memory out_);
/// @notice Get data
/// @param _in Input data
/// @return out_ Output data
function getData(bytes memory _in) external returns (bytes memory out_);
/// @notice Sets data
/// @param _in Input data
/// @return out_ Output data
function setData(bytes memory _in) external returns (bytes memory out_);
/// @notice Pays for data
/// @param _in Input data
/// @return out_ Output data
function payData(bytes memory _in) external payable returns (bytes memory out_);
/// @notice Transfers the ownership of the contract
/// @param newOwner New owner of the contract
function transferOwnership(address newOwner) external;
/// @notice Sets the Immutable X address
/// @param _imx New Immutable X
function setIMX(address _imx) external;
/// @notice Withdraw funds from the contract
/// @param _to Recipient of the funds
/// @param _amount Amount sent, in Wei
function withdrawFunds(address payable _to, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/IERC2981.sol)
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*
* _Available since v4.5._
*/
interface IERC2981Upgradeable is IERC165Upgradeable {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be payed in that same unit of exchange.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface IMintable {
function mintFor(
address to,
uint256 quantity,
bytes calldata mintingBlob
) external;
}
// SPDX-License-Identifier: Unlicensed
pragma solidity ~0.8.13;
interface IExtensionManager {
function beforeTokenTransfer(
address _from,
address _to,
uint256 _tokenId
) external;
function afterTokenTransfer(
address _from,
address _to,
uint256 _tokenId
) external;
function beforeTokenApprove(address _to, uint256 _tokenId) external;
function afterTokenApprove(address _to, uint256 _tokenId) external;
function beforeApproveAll(address _operator, bool _approved) external;
function afterApproveAll(address _operator, bool _approved) external;
function tokenURI(uint256 _tokenId) external view returns (string memory uri_);
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
returns (address royaltyReceiver_, uint256 royaltyAmount_);
function getPLOTData(uint256 _tokenId, bytes memory _in)
external
view
returns (bytes memory out_);
function setPLOTData(uint256 _tokenId, bytes memory _in) external returns (bytes memory out_);
function payPLOTData(uint256 _tokenId, bytes memory _in)
external
payable
returns (bytes memory out_);
function getData(bytes memory _in) external view returns (bytes memory out_);
function setData(bytes memory _in) external returns (bytes memory out_);
function payData(bytes memory _in) external payable returns (bytes memory out_);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
} | @notice Updates the of the current sale @param _maxPLOTs Maximum number of PLOTs that can be minted in this sale | function updateSaleMaxPLOTs(uint256 _maxPLOTs) external onlyRole(DEFAULT_ADMIN_ROLE) {
uint256 saleId = currentSaleId();
_checkSafeTokenIdRange(sales[saleId].startTokenIndex, _maxPLOTs, saleId);
sales[saleId].maxPLOTs = _maxPLOTs;
emit SaleUpdated(msg.sender, saleId);
}
| 541,913 | [
1,
5121,
326,
225,
434,
326,
783,
272,
5349,
225,
389,
1896,
20485,
17218,
18848,
1300,
434,
453,
1502,
17218,
716,
848,
506,
312,
474,
329,
316,
333,
272,
5349,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1089,
30746,
2747,
20485,
17218,
12,
11890,
5034,
389,
1896,
20485,
17218,
13,
3903,
1338,
2996,
12,
5280,
67,
15468,
67,
16256,
13,
288,
203,
3639,
2254,
5034,
272,
5349,
548,
273,
783,
30746,
548,
5621,
203,
203,
3639,
389,
1893,
9890,
1345,
548,
2655,
12,
87,
5408,
63,
87,
5349,
548,
8009,
1937,
1345,
1016,
16,
389,
1896,
20485,
17218,
16,
272,
5349,
548,
1769,
203,
203,
3639,
272,
5408,
63,
87,
5349,
548,
8009,
1896,
20485,
17218,
273,
389,
1896,
20485,
17218,
31,
203,
3639,
3626,
348,
5349,
7381,
12,
3576,
18,
15330,
16,
272,
5349,
548,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/1/0x1b6a205358e9378Bf9d6cb75F4D3cCcab38cA796/sources/src/ZeroLiquid.sol | @inheritdoc IZeroLiquidActions | function withdrawUnderlying(
address yieldToken,
uint256 shares,
address recipient,
uint256 minimumAmountOut
)
external
override
lock
returns (uint256)
{
_checkArgument(recipient != address(0));
_checkSupportedYieldToken(yieldToken);
_checkLoss(yieldToken);
uint256 amountYieldTokens = _withdraw(yieldToken, msg.sender, shares, recipient);
return _unwrap(yieldToken, amountYieldTokens, recipient, minimumAmountOut);
}
| 15,484,889 | [
1,
36,
10093,
467,
7170,
48,
18988,
350,
6100,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
598,
9446,
14655,
6291,
12,
203,
3639,
1758,
2824,
1345,
16,
203,
3639,
2254,
5034,
24123,
16,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
5224,
6275,
1182,
203,
565,
262,
203,
3639,
3903,
203,
3639,
3849,
203,
3639,
2176,
203,
3639,
1135,
261,
11890,
5034,
13,
203,
565,
288,
203,
3639,
389,
1893,
1379,
12,
20367,
480,
1758,
12,
20,
10019,
203,
3639,
389,
1893,
7223,
16348,
1345,
12,
23604,
1345,
1769,
203,
3639,
389,
1893,
20527,
12,
23604,
1345,
1769,
203,
203,
3639,
2254,
5034,
3844,
16348,
5157,
273,
389,
1918,
9446,
12,
23604,
1345,
16,
1234,
18,
15330,
16,
24123,
16,
8027,
1769,
203,
203,
3639,
327,
389,
318,
4113,
12,
23604,
1345,
16,
3844,
16348,
5157,
16,
8027,
16,
5224,
6275,
1182,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./RestrictedToken.sol";
import { IRestrictedSwap } from "./interfaces/IRestrictedSwap.sol";
import { IERC1404 } from "./interfaces/IERC1404.sol";
contract RestrictedSwap is IRestrictedSwap, RestrictedToken, ReentrancyGuard {
using SafeERC20 for IERC20;
/// @dev swap number
uint256 public swapNumber = 0;
/// @dev swap number => swap
mapping(uint256 => Swap) private _swap;
modifier onlyValidSwap(uint256 _swapNumber) {
Swap storage swap = _swap[_swapNumber];
require(swap.status != SwapStatus.Canceled, "Already canceled");
require(swap.status != SwapStatus.Complete, "Already completed");
_;
}
constructor(
address transferRules_,
address contractAdmin_,
address tokenReserveAdmin_,
string memory symbol_,
string memory name_,
uint8 decimals_,
uint256 totalSupply_,
uint256 maxTotalSupply_,
address[] memory mintAddresses_,
uint256[] memory mintAmounts_
) RestrictedToken(
transferRules_,
contractAdmin_,
tokenReserveAdmin_,
symbol_,
name_,
decimals_,
totalSupply_,
maxTotalSupply_
) {
require(mintAddresses_.length == mintAmounts_.length, "Must have same number of mint addresses and amounts");
for (uint256 i; i < mintAddresses_.length; i++) {
require(mintAddresses_[i] != address(0), "Cannot have a non-address for mint");
require(totalSupply() + mintAmounts_[i] <= maxTotalSupply_, "Total supply of tokens cannot exceed the max total supply");
_mint(mintAddresses_[i], mintAmounts_[i]);
}
}
/**
* @dev Configures swap and emits an event. This function does not fund tokens. Only for swap configuration.
* @param restrictedTokenSender restricted token sender
* @param quoteTokenSender quote token sender
* @param quoteToken quote token
* @param restrictedTokenAmount restricted token amount
* @param quoteTokenAmount quote token amount
*/
function _configureSwap(
address restrictedTokenSender,
address quoteTokenSender,
address quoteToken,
uint256 restrictedTokenAmount,
uint256 quoteTokenAmount,
SwapStatus configuror
) private {
require(restrictedTokenAmount > 0, "Invalid restricted token amount");
require(quoteTokenAmount > 0, "Invalid quote token amount");
require(quoteToken != address(0), "Invalid quote token address");
uint8 code = detectTransferRestriction(
restrictedTokenSender,
quoteTokenSender,
restrictedTokenAmount);
string memory message = messageForTransferRestriction(code);
require(code == 0, message); // 0 == success
bytes memory data = abi.encodeWithSelector(
IERC1404(quoteToken).detectTransferRestriction.selector,
quoteTokenSender,
restrictedTokenSender,
quoteTokenAmount);
(bool isErc1404, bytes memory returnData) = quoteToken.call(data);
if (isErc1404) {
code = abi.decode(returnData, (uint8));
require(code <= 9, "BAD RESTRICTION CODE");
message = IERC1404(quoteToken).messageForTransferRestriction(code);
require(code == 0, message); // 0 == success
}
swapNumber += 1;
Swap storage swap = _swap[swapNumber];
swap.restrictedTokenSender = restrictedTokenSender;
swap.restrictedTokenAmount = restrictedTokenAmount;
swap.quoteTokenSender = quoteTokenSender;
swap.quoteTokenAmount = quoteTokenAmount;
swap.quoteToken = quoteToken;
swap.status = configuror;
emit SwapConfigured(
swapNumber,
restrictedTokenSender,
restrictedTokenAmount,
quoteToken,
quoteTokenSender,
quoteTokenAmount
);
}
/**
* @dev Configure swap and emit an event with new swap number
* @param restrictedTokenAmount the required amount for the erc1404Sender to send
* @param quoteToken the address of an erc1404 or erc20 that will be swapped
* @param quoteTokenSender the address that is approved to fund quoteToken
* @param quoteTokenAmount the required amount of quoteToken to swap
*/
function configureSell(
uint256 restrictedTokenAmount,
address quoteToken,
address quoteTokenSender,
uint256 quoteTokenAmount
)
external
override
nonReentrant
{
require(quoteTokenSender != address(0), "Invalid quote token sender");
require(balanceOf(msg.sender) >= restrictedTokenAmount, "Insufficient restricted token amount");
_configureSwap(
msg.sender,
quoteTokenSender,
quoteToken,
restrictedTokenAmount,
quoteTokenAmount,
SwapStatus.SellConfigured
);
// fund caller's restricted token into swap
_transfer(msg.sender, address(this), restrictedTokenAmount);
}
/**
* @dev Configure swap and emit an event with new swap number
* @param restrictedTokenAmount the required amount for the erc1404Sender to send
* @param restrictedTokenSender restricted token sender
* @param quoteToken the address of an erc1404 or erc20 that will be swapped
* @param quoteTokenAmount the required amount of quoteToken to swap
*/
function configureBuy(
uint256 restrictedTokenAmount,
address restrictedTokenSender,
address quoteToken,
uint256 quoteTokenAmount
)
external
override
nonReentrant
{
require(restrictedTokenSender != address(0), "Invalid restricted token sender");
_configureSwap(
restrictedTokenSender,
msg.sender,
quoteToken,
restrictedTokenAmount,
quoteTokenAmount,
SwapStatus.BuyConfigured
);
// fund caller's quote token into swap
IERC20(quoteToken).safeTransferFrom(msg.sender, address(this), quoteTokenAmount);
}
/**
* @dev Complete swap with quote token
* @param _swapNumber swap number
*/
function completeSwapWithPaymentToken(uint256 _swapNumber)
external
override
onlyValidSwap(_swapNumber)
nonReentrant
{
Swap storage swap = _swap[_swapNumber];
require(swap.quoteTokenSender == msg.sender, "You are not appropriate token sender for this swap");
uint256 balanceBefore = IERC20(swap.quoteToken).balanceOf(swap.restrictedTokenSender);
// from, to, value
IERC20(swap.quoteToken).safeTransferFrom(msg.sender, swap.restrictedTokenSender, swap.quoteTokenAmount);
uint256 balanceAfter = IERC20(swap.quoteToken).balanceOf(swap.restrictedTokenSender);
require(balanceBefore + swap.quoteTokenAmount == balanceAfter, "Deposit reverted for incorrect result of deposited amount");
swap.status = SwapStatus.Complete;
_transfer(address(this), swap.quoteTokenSender, swap.restrictedTokenAmount);
emit SwapComplete(
_swapNumber,
swap.restrictedTokenSender,
swap.restrictedTokenAmount,
swap.quoteTokenSender,
swap.quoteToken,
swap.quoteTokenAmount
);
}
/**
* @dev Complete swap with restricted token
* @param _swapNumber swap number
*/
function completeSwapWithRestrictedToken(uint256 _swapNumber)
external
override
onlyValidSwap(_swapNumber)
nonReentrant
{
Swap storage swap = _swap[_swapNumber];
require(swap.restrictedTokenSender == msg.sender, "You are not appropriate token sender for this swap");
uint256 balanceBefore = IERC20(swap.quoteToken).balanceOf(swap.restrictedTokenSender);
IERC20(swap.quoteToken).safeTransferFrom(swap.quoteTokenSender, msg.sender, swap.quoteTokenAmount);
uint256 balanceAfter = IERC20(swap.quoteToken).balanceOf(swap.restrictedTokenSender);
require(balanceBefore + swap.quoteTokenAmount == balanceAfter, "Deposit reverted for incorrect result of deposited amount");
swap.status = SwapStatus.Complete;
_transfer(msg.sender, swap.quoteTokenSender, swap.restrictedTokenAmount);
emit SwapComplete(
_swapNumber,
swap.restrictedTokenSender,
swap.restrictedTokenAmount,
swap.quoteTokenSender,
swap.quoteToken,
swap.quoteTokenAmount
);
}
/**
* @dev cancel swap
* @param _swapNumber swap number
*/
function cancelSell(uint256 _swapNumber)
external
override
onlyValidSwap(_swapNumber)
nonReentrant
{
Swap storage swap = _swap[_swapNumber];
require(swap.restrictedTokenSender != address(0), "This swap is not configured");
require(swap.quoteTokenSender != address(0), "This swap is not configured");
if (swap.status == SwapStatus.SellConfigured) {
require(msg.sender == swap.restrictedTokenSender, "Only swap configurator can cancel the swap");
_transfer(address(this), swap.restrictedTokenSender, swap.restrictedTokenAmount);
} else if (swap.status == SwapStatus.BuyConfigured) {
require(msg.sender == swap.quoteTokenSender, "Only swap configurator can cancel the swap");
IERC20(swap.quoteToken).safeTransfer(swap.quoteTokenSender, swap.quoteTokenAmount);
}
swap.status = SwapStatus.Canceled;
emit SwapCanceled(msg.sender, _swapNumber);
}
/**
* @dev Returns the swap status if exists
* @param _swapNumber swap number
* @return SwapStatus status of the swap record
*/
function swapStatus(uint256 _swapNumber)
external
override
view
/*onlyWalletsAdminOrReserveAdmin*/
returns
(SwapStatus)
{
require( _swap[_swapNumber].restrictedTokenSender != address(0), "Swap record not exists" );
return _swap[_swapNumber].status;
}
}
| * @dev Complete swap with quote token @param _swapNumber swap number/ from, to, value | function completeSwapWithPaymentToken(uint256 _swapNumber)
external
override
onlyValidSwap(_swapNumber)
nonReentrant
{
Swap storage swap = _swap[_swapNumber];
require(swap.quoteTokenSender == msg.sender, "You are not appropriate token sender for this swap");
uint256 balanceBefore = IERC20(swap.quoteToken).balanceOf(swap.restrictedTokenSender);
IERC20(swap.quoteToken).safeTransferFrom(msg.sender, swap.restrictedTokenSender, swap.quoteTokenAmount);
uint256 balanceAfter = IERC20(swap.quoteToken).balanceOf(swap.restrictedTokenSender);
require(balanceBefore + swap.quoteTokenAmount == balanceAfter, "Deposit reverted for incorrect result of deposited amount");
swap.status = SwapStatus.Complete;
_transfer(address(this), swap.quoteTokenSender, swap.restrictedTokenAmount);
emit SwapComplete(
_swapNumber,
swap.restrictedTokenSender,
swap.restrictedTokenAmount,
swap.quoteTokenSender,
swap.quoteToken,
swap.quoteTokenAmount
);
}
| 12,614,047 | [
1,
6322,
7720,
598,
3862,
1147,
282,
389,
22270,
1854,
7720,
1300,
19,
628,
16,
358,
16,
460,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
3912,
12521,
1190,
6032,
1345,
12,
11890,
5034,
389,
22270,
1854,
13,
203,
565,
3903,
203,
565,
3849,
203,
565,
1338,
1556,
12521,
24899,
22270,
1854,
13,
203,
565,
1661,
426,
8230,
970,
203,
225,
288,
203,
565,
12738,
2502,
7720,
273,
389,
22270,
63,
67,
22270,
1854,
15533,
203,
203,
565,
2583,
12,
22270,
18,
6889,
1345,
12021,
422,
1234,
18,
15330,
16,
315,
6225,
854,
486,
5505,
1147,
5793,
364,
333,
7720,
8863,
203,
203,
565,
2254,
5034,
11013,
4649,
273,
467,
654,
39,
3462,
12,
22270,
18,
6889,
1345,
2934,
12296,
951,
12,
22270,
18,
29306,
1345,
12021,
1769,
203,
565,
467,
654,
39,
3462,
12,
22270,
18,
6889,
1345,
2934,
4626,
5912,
1265,
12,
3576,
18,
15330,
16,
7720,
18,
29306,
1345,
12021,
16,
7720,
18,
6889,
1345,
6275,
1769,
203,
565,
2254,
5034,
11013,
4436,
273,
467,
654,
39,
3462,
12,
22270,
18,
6889,
1345,
2934,
12296,
951,
12,
22270,
18,
29306,
1345,
12021,
1769,
203,
203,
565,
2583,
12,
12296,
4649,
397,
7720,
18,
6889,
1345,
6275,
422,
11013,
4436,
16,
315,
758,
1724,
15226,
329,
364,
11332,
563,
434,
443,
1724,
329,
3844,
8863,
203,
203,
565,
7720,
18,
2327,
273,
12738,
1482,
18,
6322,
31,
203,
203,
565,
389,
13866,
12,
2867,
12,
2211,
3631,
7720,
18,
6889,
1345,
12021,
16,
7720,
18,
29306,
1345,
6275,
1769,
203,
203,
565,
3626,
12738,
6322,
12,
203,
1377,
389,
22270,
1854,
16,
203,
1377,
7720,
18,
29306,
1345,
12021,
16,
203,
1377,
7720,
18,
29306,
1345,
2
]
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "hardhat/console.sol";
contract WavePortal {
uint256 totalWaves;
uint256 private seed;
event NewWave(address indexed from, uint256 timestamp, string message);
struct Wave {
address waver;
string message;
uint256 eth;
uint256 timestamp;
}
Wave[] waves;
/*
* "address => uint mapping"は、アドレスと数値を関連付ける
*/
mapping(address => uint256) public lastWavedAt;
constructor() payable {
console.log("We have been constructed!");
/*
* 初期シードの設定
*/
seed = (block.timestamp + block.difficulty) % 100;
totalWaves = 1;
}
function sqrt(uint256 x) public pure returns (uint256) {
uint256 z = (x + 1) / 2;
uint256 y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
return y;
}
function isPrime(uint256 n) public pure returns (bool) {
if (n <= 1) {
return false;
}
if (2 == n) {
return true;
}
if (0 == n % 2) {
return false;
}
uint256 _sqrt = sqrt(n);
for (uint256 i = 3; i <= _sqrt; i += 2) {
if (0 == n % i) {
return false;
}
}
return true;
}
function wave(string memory _message) public {
require(
lastWavedAt[msg.sender] + 3 seconds < block.timestamp,
"Wait 3 secconds"
);
/*
* ユーザーの現在のタイムスタンプを更新する
*/
lastWavedAt[msg.sender] = block.timestamp;
totalWaves += 1;
console.log("%s has waved!", msg.sender);
/*
* ユーザーのために乱数を設定
*/
seed = (block.difficulty + block.timestamp + seed) % 100;
if (seed <= 80 && isPrime(totalWaves)) {
console.log("%s won!", msg.sender);
uint256 prizeAmount = 0.0004126 ether;
waves.push(
Wave(msg.sender, _message, prizeAmount, block.timestamp)
);
require(
prizeAmount <= address(this).balance,
"Trying to withdraw more money than they contract has."
);
(bool success, ) = (msg.sender).call{value: prizeAmount}("");
require(success, "Failed to withdraw money from contract.");
} else {
console.log("lose!");
waves.push(Wave(msg.sender, _message, 0 ether, block.timestamp));
}
emit NewWave(msg.sender, block.timestamp, _message);
}
function getAllWaves() public view returns (Wave[] memory) {
return waves;
}
function getTotalWaves() public view returns (uint256) {
return totalWaves;
}
}
| ユーザーの現在のタイムスタンプを更新する/ ユーザーのために乱数を設定/ | function wave(string memory _message) public {
require(
lastWavedAt[msg.sender] + 3 seconds < block.timestamp,
"Wait 3 secconds"
);
lastWavedAt[msg.sender] = block.timestamp;
totalWaves += 1;
console.log("%s has waved!", msg.sender);
seed = (block.difficulty + block.timestamp + seed) % 100;
if (seed <= 80 && isPrime(totalWaves)) {
console.log("%s won!", msg.sender);
uint256 prizeAmount = 0.0004126 ether;
waves.push(
Wave(msg.sender, _message, prizeAmount, block.timestamp)
);
require(
prizeAmount <= address(this).balance,
"Trying to withdraw more money than they contract has."
);
require(success, "Failed to withdraw money from contract.");
console.log("lose!");
waves.push(Wave(msg.sender, _message, 0 ether, block.timestamp));
}
emit NewWave(msg.sender, block.timestamp, _message);
}
| 12,616,800 | [
1,
164,
230,
104,
164,
230,
125,
164,
229,
119,
164,
230,
125,
164,
228,
111,
168,
242,
127,
166,
255,
106,
164,
228,
111,
164,
229,
128,
164,
229,
102,
164,
230,
259,
164,
229,
122,
164,
229,
128,
164,
230,
116,
164,
230,
250,
164,
229,
245,
167,
254,
117,
167,
249,
113,
164,
228,
252,
164,
229,
238,
19,
225,
225,
164,
230,
104,
164,
230,
125,
164,
229,
119,
164,
230,
125,
164,
228,
111,
164,
228,
258,
164,
229,
228,
164,
228,
109,
165,
122,
114,
167,
248,
113,
164,
229,
245,
169,
106,
260,
166,
111,
253,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
10794,
12,
1080,
3778,
389,
2150,
13,
1071,
288,
203,
3639,
2583,
12,
203,
5411,
1142,
59,
8158,
861,
63,
3576,
18,
15330,
65,
397,
890,
3974,
411,
1203,
18,
5508,
16,
203,
5411,
315,
5480,
890,
1428,
20874,
6,
203,
3639,
11272,
203,
203,
3639,
1142,
59,
8158,
861,
63,
3576,
18,
15330,
65,
273,
1203,
18,
5508,
31,
203,
203,
3639,
2078,
59,
6606,
1011,
404,
31,
203,
3639,
2983,
18,
1330,
27188,
87,
711,
341,
8158,
5,
3113,
1234,
18,
15330,
1769,
203,
203,
3639,
5009,
273,
261,
2629,
18,
5413,
21934,
397,
1203,
18,
5508,
397,
5009,
13,
738,
2130,
31,
203,
203,
3639,
309,
261,
12407,
1648,
8958,
597,
353,
23327,
12,
4963,
59,
6606,
3719,
288,
203,
5411,
2983,
18,
1330,
27188,
87,
8462,
5,
3113,
1234,
18,
15330,
1769,
203,
5411,
2254,
5034,
846,
554,
6275,
273,
374,
18,
31262,
25452,
225,
2437,
31,
203,
5411,
341,
6606,
18,
6206,
12,
203,
7734,
24314,
12,
3576,
18,
15330,
16,
389,
2150,
16,
846,
554,
6275,
16,
1203,
18,
5508,
13,
203,
5411,
11272,
203,
203,
5411,
2583,
12,
203,
7734,
846,
554,
6275,
1648,
1758,
12,
2211,
2934,
12296,
16,
203,
7734,
315,
18038,
358,
598,
9446,
1898,
15601,
2353,
2898,
6835,
711,
1199,
203,
5411,
11272,
203,
5411,
2583,
12,
4768,
16,
315,
2925,
358,
598,
9446,
15601,
628,
6835,
1199,
1769,
203,
5411,
2983,
18,
1330,
2932,
2061,
4442,
1769,
203,
5411,
341,
6606,
18,
6206,
12,
22368,
12,
3576,
18,
15330,
16,
2
]
|
./partial_match/56/0xAB966070B18C0230eC40Ce010F38c94c6541CCa7/sources/BvaultsStrategy.sol | Converts dust tokens into earned tokens, which will be reinvested on the next earn(). Converts token0 dust (if any) to earned tokens | function convertDustToEarned() public whenNotPaused {
require(isAutoComp, "!isAutoComp");
require(!isCAKEStaking, "isCAKEStaking");
uint256 _token0Amt = IERC20(token0Address).balanceOf(address(this));
if (token0Address != earnedAddress && _token0Amt > 0) {
_vswapSwapToken(token0Address, earnedAddress, _token0Amt);
}
if (token1Address != earnedAddress && _token1Amt > 0) {
_vswapSwapToken(token1Address, earnedAddress, _token1Amt);
}
}
| 11,047,684 | [
1,
5692,
302,
641,
2430,
1368,
425,
1303,
329,
2430,
16,
1492,
903,
506,
283,
5768,
3149,
603,
326,
1024,
425,
1303,
7675,
20377,
1147,
20,
302,
641,
261,
430,
1281,
13,
358,
425,
1303,
329,
2430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
445,
1765,
40,
641,
774,
41,
1303,
329,
1435,
1071,
1347,
1248,
28590,
288,
203,
3639,
2583,
12,
291,
4965,
2945,
16,
17528,
291,
4965,
2945,
8863,
203,
3639,
2583,
12,
5,
291,
3587,
6859,
510,
6159,
16,
315,
291,
3587,
6859,
510,
6159,
8863,
203,
203,
203,
3639,
2254,
5034,
389,
2316,
20,
31787,
273,
467,
654,
39,
3462,
12,
2316,
20,
1887,
2934,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
3639,
309,
261,
2316,
20,
1887,
480,
425,
1303,
329,
1887,
597,
389,
2316,
20,
31787,
405,
374,
13,
288,
203,
5411,
389,
90,
22270,
12521,
1345,
12,
2316,
20,
1887,
16,
425,
1303,
329,
1887,
16,
389,
2316,
20,
31787,
1769,
203,
3639,
289,
203,
203,
3639,
309,
261,
2316,
21,
1887,
480,
425,
1303,
329,
1887,
597,
389,
2316,
21,
31787,
405,
374,
13,
288,
203,
5411,
389,
90,
22270,
12521,
1345,
12,
2316,
21,
1887,
16,
425,
1303,
329,
1887,
16,
389,
2316,
21,
31787,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721Enumerable.sol";
import "./Ownable.sol";
import "./Strings.sol";
import "./IMintlings.sol";
import "./IMintlingsMetadata.sol";
contract Mintlings is ERC721Enumerable, Ownable, IMintlings, IMintlingsMetadata {
using Strings for uint256;
uint256 public constant GIFT_COUNT = 0;
uint256 public constant PUBLIC_COUNT = 3333;
uint256 public constant MAX_COUNT = GIFT_COUNT + PUBLIC_COUNT;
uint256 public constant PURCHASE_LIMIT = 3333;
uint256 public constant PRICE = 0.069 ether;
bool public isActive = false;
bool public isAllowListActive = false;
string public proof;
uint256 public allowListMaxMint = 20;
/// @dev We will use these to be able to calculate remaining correctly.
uint256 public totalGiftSupply;
uint256 public totalPublicSupply;
mapping(address => bool) private _allowList;
mapping(address => uint256) private _allowListClaimed;
address[] angels;
mapping(address => uint256) private angelPercentages;
mapping(address => uint256) private angelPart;
bool private angelsSet = false;
string private _contractURI = '';
string private _tokenBaseURI = '';
string private _tokenRevealedBaseURI = '';
constructor(string memory name, string memory symbol) ERC721(name, symbol) {}
function addToAllowList(address[] calldata addresses) external override onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Can't add the null address");
_allowList[addresses[i]] = true;
/**
* @dev We don't want to reset _allowListClaimed count
* if we try to add someone more than once.
*/
_allowListClaimed[addresses[i]] > 0 ? _allowListClaimed[addresses[i]] : 0;
}
}
function onAllowList(address addr) external view override returns (bool) {
return _allowList[addr];
}
function removeFromAllowList(address[] calldata addresses) external override onlyOwner {
for (uint256 i = 0; i < addresses.length; i++) {
require(addresses[i] != address(0), "Can't add the null address");
/// @dev We don't want to reset possible _allowListClaimed numbers.
_allowList[addresses[i]] = false;
}
}
/**
* @dev We want to be able to distinguish tokens bought during isAllowListActive
* and tokens bought outside of isAllowListActive
*/
function allowListClaimedBy(address owner) external view override returns (uint256){
require(owner != address(0), 'Zero address not on Allow List');
return _allowListClaimed[owner];
}
function purchase(uint256 numberOfTokens) external override payable {
require(isActive, 'Contract is not active');
require(!isAllowListActive, 'Only allowing from Allow List');
require(totalSupply() < MAX_COUNT, 'All tokens have been minted');
require(numberOfTokens <= PURCHASE_LIMIT, 'Would exceed PURCHASE_LIMIT');
/**
* @dev The last person to purchase might pay too much.
* This way however they can't get sniped.
* If this happens, we'll refund the Eth for the unavailable tokens.
*/
require(totalPublicSupply < PUBLIC_COUNT, 'Purchase would exceed PUBLIC_COUNT');
require(PRICE * numberOfTokens <= msg.value, 'ETH amount is not sufficient');
for (uint256 i = 0; i < numberOfTokens; i++) {
/**
* @dev Since they can get here while exceeding the MAX_COUNT,
* we have to make sure to not mint any additional tokens.
*/
if (totalPublicSupply < PUBLIC_COUNT) {
/**
* @dev Public token numbering starts after GIFT_COUNT.
* And we don't want our tokens to start at 0 but at 1.
*/
uint256 tokenId = GIFT_COUNT + totalPublicSupply + 1;
totalPublicSupply += 1;
_safeMint(msg.sender, tokenId);
}
}
splitFunds();
}
function splitFunds() internal virtual {
for (uint i = 0; i < angels.length; i++) {
uint256 angelShare = (msg.value *
angelPercentages[angels[i]]) / 100;
angelPart[angels[i]] += angelShare;
}
}
function purchaseAllowList(uint256 numberOfTokens) external override payable {
require(isActive, 'Contract is not active');
require(isAllowListActive, 'Allow List is not active');
require(_allowList[msg.sender], 'You are not on the Allow List');
require(totalSupply() < MAX_COUNT, 'All tokens have been minted');
require(numberOfTokens <= allowListMaxMint, 'Cannot purchase this many tokens');
require(totalPublicSupply + numberOfTokens <= PUBLIC_COUNT, 'Purchase would exceed PUBLIC_COUNT');
require(_allowListClaimed[msg.sender] + numberOfTokens <= allowListMaxMint, 'Purchase exceeds max allowed');
require(PRICE * numberOfTokens <= msg.value, 'ETH amount is not sufficient');
for (uint256 i = 0; i < numberOfTokens; i++) {
/**
* @dev Public token numbering starts after GIFT_COUNT.
* We don't want our tokens to start at 0 but at 1.
*/
uint256 tokenId = GIFT_COUNT + totalPublicSupply + 1;
totalPublicSupply += 1;
_allowListClaimed[msg.sender] += 1;
_safeMint(msg.sender, tokenId);
}
}
function gift(address[] calldata to) external override onlyOwner {
require(totalSupply() < MAX_COUNT, 'All tokens have been minted');
require(totalGiftSupply + to.length <= GIFT_COUNT, 'Not enough tokens left to gift');
for(uint256 i = 0; i < to.length; i++) {
/// @dev We don't want our tokens to start at 0 but at 1.
uint256 tokenId = totalGiftSupply + 1;
totalGiftSupply += 1;
_safeMint(to[i], tokenId);
}
}
function setIsActive(bool _isActive) external override onlyOwner {
isActive = _isActive;
}
function setIsAllowListActive(bool _isAllowListActive) external override onlyOwner {
isAllowListActive = _isAllowListActive;
}
function setAllowListMaxMint(uint256 maxMint) external override onlyOwner {
allowListMaxMint = maxMint;
}
function setProof(string calldata proofString) external override onlyOwner {
proof = proofString;
}
function withdraw() external override onlyOwner {}
modifier onlyAngel() {
require(
angelPercentages[_msgSender()] > 0,
"Only angels can call this function"
);
_;
}
function getAngelParts(address angelAddress) public view returns(uint256) {
return angelPart[angelAddress];
}
function getAngelPercentage(address angelAddress) public view returns(uint256) {
return angelPercentages[angelAddress];
}
function withdrawAngel() public onlyAngel() {
uint256 withdrawAmount = angelPart[_msgSender()];
angelPart[_msgSender()] = 0;
payable(_msgSender()).transfer(withdrawAmount);
}
function setAngels(
address[] memory _angels,
uint256[] memory _angelPercentages
) public onlyOwner {
require(!angelsSet);
angels = _angels;
uint256 sharesPercentageTotal = 0;
for (uint i = 0; i < angels.length; i++) {
sharesPercentageTotal += _angelPercentages[i];
angelPercentages[angels[i]] =
_angelPercentages[i];
}
require(sharesPercentageTotal == 100);
angelsSet = true;
}
function setContractURI(string calldata URI) external override onlyOwner {
_contractURI = URI;
}
function setBaseURI(string calldata URI) external override onlyOwner {
_tokenBaseURI = URI;
}
function setRevealedBaseURI(string calldata revealedBaseURI) external override onlyOwner {
_tokenRevealedBaseURI = revealedBaseURI;
}
function contractURI() public view override returns (string memory) {
return _contractURI;
}
function tokenURI(uint256 tokenId) public view override(ERC721) returns (string memory) {
require(_exists(tokenId), 'Token does not exist');
/// @dev Convert string to bytes so we can check if it's empty or not.
string memory revealedBaseURI = _tokenRevealedBaseURI;
return bytes(revealedBaseURI).length > 0 ?
string(abi.encodePacked(revealedBaseURI, tokenId.toString())) :
_tokenBaseURI;
}
} | * @dev The last person to purchase might pay too much. This way however they can't get sniped. If this happens, we'll refund the Eth for the unavailable tokens./* @dev Since they can get here while exceeding the MAX_COUNT, we have to make sure to not mint any additional tokens./ | function purchase(uint256 numberOfTokens) external override payable {
require(isActive, 'Contract is not active');
require(!isAllowListActive, 'Only allowing from Allow List');
require(totalSupply() < MAX_COUNT, 'All tokens have been minted');
require(numberOfTokens <= PURCHASE_LIMIT, 'Would exceed PURCHASE_LIMIT');
require(totalPublicSupply < PUBLIC_COUNT, 'Purchase would exceed PUBLIC_COUNT');
require(PRICE * numberOfTokens <= msg.value, 'ETH amount is not sufficient');
for (uint256 i = 0; i < numberOfTokens; i++) {
if (totalPublicSupply < PUBLIC_COUNT) {
uint256 tokenId = GIFT_COUNT + totalPublicSupply + 1;
totalPublicSupply += 1;
_safeMint(msg.sender, tokenId);
}
splitFunds();
}
| 5,982,902 | [
1,
1986,
1142,
6175,
358,
23701,
4825,
8843,
4885,
9816,
18,
1220,
4031,
14025,
2898,
848,
1404,
336,
4556,
625,
329,
18,
971,
333,
10555,
16,
732,
5614,
16255,
326,
512,
451,
364,
326,
15781,
2430,
18,
19,
225,
7897,
2898,
848,
336,
2674,
1323,
9943,
310,
326,
4552,
67,
7240,
16,
732,
1240,
358,
1221,
3071,
358,
486,
312,
474,
1281,
3312,
2430,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
225,
445,
23701,
12,
11890,
5034,
7922,
5157,
13,
3903,
3849,
8843,
429,
288,
203,
565,
2583,
12,
291,
3896,
16,
296,
8924,
353,
486,
2695,
8284,
203,
565,
2583,
12,
5,
291,
7009,
682,
3896,
16,
296,
3386,
15632,
628,
7852,
987,
8284,
203,
565,
2583,
12,
4963,
3088,
1283,
1435,
411,
4552,
67,
7240,
16,
296,
1595,
2430,
1240,
2118,
312,
474,
329,
8284,
203,
565,
2583,
12,
2696,
951,
5157,
1648,
26345,
1792,
4429,
67,
8283,
16,
296,
59,
1006,
9943,
26345,
1792,
4429,
67,
8283,
8284,
203,
565,
2583,
12,
4963,
4782,
3088,
1283,
411,
17187,
67,
7240,
16,
296,
23164,
4102,
9943,
17187,
67,
7240,
8284,
203,
565,
2583,
12,
7698,
1441,
380,
7922,
5157,
1648,
1234,
18,
1132,
16,
296,
1584,
44,
3844,
353,
486,
18662,
8284,
203,
203,
565,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
7922,
5157,
31,
277,
27245,
288,
203,
1377,
309,
261,
4963,
4782,
3088,
1283,
411,
17187,
67,
7240,
13,
288,
203,
3639,
2254,
5034,
1147,
548,
273,
611,
17925,
67,
7240,
397,
2078,
4782,
3088,
1283,
397,
404,
31,
203,
203,
3639,
2078,
4782,
3088,
1283,
1011,
404,
31,
203,
3639,
389,
4626,
49,
474,
12,
3576,
18,
15330,
16,
1147,
548,
1769,
203,
565,
289,
203,
203,
565,
1416,
42,
19156,
5621,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.9;
/// @notice Emitted when the result overflows uint256.
error PRBMath__MulDivFixedPointOverflow(uint256 prod1);
/// @notice Emitted when the result overflows uint256.
error PRBMath__MulDivOverflow(uint256 prod1, uint256 denominator);
/// @notice Emitted when one of the inputs is type(int256).min.
error PRBMath__MulDivSignedInputTooSmall();
/// @notice Emitted when the intermediary absolute result overflows int256.
error PRBMath__MulDivSignedOverflow(uint256 rAbs);
/// @notice Emitted when the input is MIN_SD59x18.
error PRBMathSD59x18__AbsInputTooSmall();
/// @notice Emitted when ceiling a number overflows SD59x18.
error PRBMathSD59x18__CeilOverflow(int256 x);
/// @notice Emitted when one of the inputs is MIN_SD59x18.
error PRBMathSD59x18__DivInputTooSmall();
/// @notice Emitted when one of the intermediary unsigned results overflows SD59x18.
error PRBMathSD59x18__DivOverflow(uint256 rAbs);
/// @notice Emitted when the input is greater than 133.084258667509499441.
error PRBMathSD59x18__ExpInputTooBig(int256 x);
/// @notice Emitted when the input is greater than 192.
error PRBMathSD59x18__Exp2InputTooBig(int256 x);
/// @notice Emitted when flooring a number underflows SD59x18.
error PRBMathSD59x18__FloorUnderflow(int256 x);
/// @notice Emitted when converting a basic integer to the fixed-point format overflows SD59x18.
error PRBMathSD59x18__FromIntOverflow(int256 x);
/// @notice Emitted when converting a basic integer to the fixed-point format underflows SD59x18.
error PRBMathSD59x18__FromIntUnderflow(int256 x);
/// @notice Emitted when the product of the inputs is negative.
error PRBMathSD59x18__GmNegativeProduct(int256 x, int256 y);
/// @notice Emitted when multiplying the inputs overflows SD59x18.
error PRBMathSD59x18__GmOverflow(int256 x, int256 y);
/// @notice Emitted when the input is less than or equal to zero.
error PRBMathSD59x18__LogInputTooSmall(int256 x);
/// @notice Emitted when one of the inputs is MIN_SD59x18.
error PRBMathSD59x18__MulInputTooSmall();
/// @notice Emitted when the intermediary absolute result overflows SD59x18.
error PRBMathSD59x18__MulOverflow(uint256 rAbs);
/// @notice Emitted when the intermediary absolute result overflows SD59x18.
error PRBMathSD59x18__PowuOverflow(uint256 rAbs);
/// @notice Emitted when the input is negative.
error PRBMathSD59x18__SqrtNegativeInput(int256 x);
/// @notice Emitted when the calculating the square root overflows SD59x18.
error PRBMathSD59x18__SqrtOverflow(int256 x);
/// @notice Emitted when addition overflows UD60x18.
error PRBMathUD60x18__AddOverflow(uint256 x, uint256 y);
/// @notice Emitted when ceiling a number overflows UD60x18.
error PRBMathUD60x18__CeilOverflow(uint256 x);
/// @notice Emitted when the input is greater than 133.084258667509499441.
error PRBMathUD60x18__ExpInputTooBig(uint256 x);
/// @notice Emitted when the input is greater than 192.
error PRBMathUD60x18__Exp2InputTooBig(uint256 x);
/// @notice Emitted when converting a basic integer to the fixed-point format format overflows UD60x18.
error PRBMathUD60x18__FromUintOverflow(uint256 x);
/// @notice Emitted when multiplying the inputs overflows UD60x18.
error PRBMathUD60x18__GmOverflow(uint256 x, uint256 y);
/// @notice Emitted when the input is less than 1.
error PRBMathUD60x18__LogInputTooSmall(uint256 x);
/// @notice Emitted when the calculating the square root overflows UD60x18.
error PRBMathUD60x18__SqrtOverflow(uint256 x);
/// @notice Emitted when subtraction underflows UD60x18.
error PRBMathUD60x18__SubUnderflow(uint256 x, uint256 y);
/// @dev Common mathematical functions used in both PRBMathSD59x18 and PRBMathUD60x18. Note that this shared library
/// does not always assume the signed 59.18-decimal fixed-point or the unsigned 60.18-decimal fixed-point
/// representation. When it does not, it is explicitly mentioned in the NatSpec documentation.
library PRBMath {
/// STRUCTS ///
struct SD59x18 {
int256 value;
}
struct UD60x18 {
uint256 value;
}
/// STORAGE ///
/// @dev How many trailing decimals can be represented.
uint256 internal constant SCALE = 1e18;
/// @dev Largest power of two divisor of SCALE.
uint256 internal constant SCALE_LPOTD = 262144;
/// @dev SCALE inverted mod 2^256.
uint256 internal constant SCALE_INVERSE =
78156646155174841979727994598816262306175212592076161876661_508869554232690281;
/// FUNCTIONS ///
/// @notice Calculates the binary exponent of x using the binary fraction method.
/// @dev Has to use 192.64-bit fixed-point numbers.
/// See https://ethereum.stackexchange.com/a/96594/24693.
/// @param x The exponent as an unsigned 192.64-bit fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function exp2(uint256 x) internal pure returns (uint256 result) {
unchecked {
// Start from 0.5 in the 192.64-bit fixed-point format.
result = 0x800000000000000000000000000000000000000000000000;
// Multiply the result by root(2, 2^-i) when the bit at position i is 1. None of the intermediary results overflows
// because the initial result is 2^191 and all magic factors are less than 2^65.
if (x & 0x8000000000000000 > 0) {
result = (result * 0x16A09E667F3BCC909) >> 64;
}
if (x & 0x4000000000000000 > 0) {
result = (result * 0x1306FE0A31B7152DF) >> 64;
}
if (x & 0x2000000000000000 > 0) {
result = (result * 0x1172B83C7D517ADCE) >> 64;
}
if (x & 0x1000000000000000 > 0) {
result = (result * 0x10B5586CF9890F62A) >> 64;
}
if (x & 0x800000000000000 > 0) {
result = (result * 0x1059B0D31585743AE) >> 64;
}
if (x & 0x400000000000000 > 0) {
result = (result * 0x102C9A3E778060EE7) >> 64;
}
if (x & 0x200000000000000 > 0) {
result = (result * 0x10163DA9FB33356D8) >> 64;
}
if (x & 0x100000000000000 > 0) {
result = (result * 0x100B1AFA5ABCBED61) >> 64;
}
if (x & 0x80000000000000 > 0) {
result = (result * 0x10058C86DA1C09EA2) >> 64;
}
if (x & 0x40000000000000 > 0) {
result = (result * 0x1002C605E2E8CEC50) >> 64;
}
if (x & 0x20000000000000 > 0) {
result = (result * 0x100162F3904051FA1) >> 64;
}
if (x & 0x10000000000000 > 0) {
result = (result * 0x1000B175EFFDC76BA) >> 64;
}
if (x & 0x8000000000000 > 0) {
result = (result * 0x100058BA01FB9F96D) >> 64;
}
if (x & 0x4000000000000 > 0) {
result = (result * 0x10002C5CC37DA9492) >> 64;
}
if (x & 0x2000000000000 > 0) {
result = (result * 0x1000162E525EE0547) >> 64;
}
if (x & 0x1000000000000 > 0) {
result = (result * 0x10000B17255775C04) >> 64;
}
if (x & 0x800000000000 > 0) {
result = (result * 0x1000058B91B5BC9AE) >> 64;
}
if (x & 0x400000000000 > 0) {
result = (result * 0x100002C5C89D5EC6D) >> 64;
}
if (x & 0x200000000000 > 0) {
result = (result * 0x10000162E43F4F831) >> 64;
}
if (x & 0x100000000000 > 0) {
result = (result * 0x100000B1721BCFC9A) >> 64;
}
if (x & 0x80000000000 > 0) {
result = (result * 0x10000058B90CF1E6E) >> 64;
}
if (x & 0x40000000000 > 0) {
result = (result * 0x1000002C5C863B73F) >> 64;
}
if (x & 0x20000000000 > 0) {
result = (result * 0x100000162E430E5A2) >> 64;
}
if (x & 0x10000000000 > 0) {
result = (result * 0x1000000B172183551) >> 64;
}
if (x & 0x8000000000 > 0) {
result = (result * 0x100000058B90C0B49) >> 64;
}
if (x & 0x4000000000 > 0) {
result = (result * 0x10000002C5C8601CC) >> 64;
}
if (x & 0x2000000000 > 0) {
result = (result * 0x1000000162E42FFF0) >> 64;
}
if (x & 0x1000000000 > 0) {
result = (result * 0x10000000B17217FBB) >> 64;
}
if (x & 0x800000000 > 0) {
result = (result * 0x1000000058B90BFCE) >> 64;
}
if (x & 0x400000000 > 0) {
result = (result * 0x100000002C5C85FE3) >> 64;
}
if (x & 0x200000000 > 0) {
result = (result * 0x10000000162E42FF1) >> 64;
}
if (x & 0x100000000 > 0) {
result = (result * 0x100000000B17217F8) >> 64;
}
if (x & 0x80000000 > 0) {
result = (result * 0x10000000058B90BFC) >> 64;
}
if (x & 0x40000000 > 0) {
result = (result * 0x1000000002C5C85FE) >> 64;
}
if (x & 0x20000000 > 0) {
result = (result * 0x100000000162E42FF) >> 64;
}
if (x & 0x10000000 > 0) {
result = (result * 0x1000000000B17217F) >> 64;
}
if (x & 0x8000000 > 0) {
result = (result * 0x100000000058B90C0) >> 64;
}
if (x & 0x4000000 > 0) {
result = (result * 0x10000000002C5C860) >> 64;
}
if (x & 0x2000000 > 0) {
result = (result * 0x1000000000162E430) >> 64;
}
if (x & 0x1000000 > 0) {
result = (result * 0x10000000000B17218) >> 64;
}
if (x & 0x800000 > 0) {
result = (result * 0x1000000000058B90C) >> 64;
}
if (x & 0x400000 > 0) {
result = (result * 0x100000000002C5C86) >> 64;
}
if (x & 0x200000 > 0) {
result = (result * 0x10000000000162E43) >> 64;
}
if (x & 0x100000 > 0) {
result = (result * 0x100000000000B1721) >> 64;
}
if (x & 0x80000 > 0) {
result = (result * 0x10000000000058B91) >> 64;
}
if (x & 0x40000 > 0) {
result = (result * 0x1000000000002C5C8) >> 64;
}
if (x & 0x20000 > 0) {
result = (result * 0x100000000000162E4) >> 64;
}
if (x & 0x10000 > 0) {
result = (result * 0x1000000000000B172) >> 64;
}
if (x & 0x8000 > 0) {
result = (result * 0x100000000000058B9) >> 64;
}
if (x & 0x4000 > 0) {
result = (result * 0x10000000000002C5D) >> 64;
}
if (x & 0x2000 > 0) {
result = (result * 0x1000000000000162E) >> 64;
}
if (x & 0x1000 > 0) {
result = (result * 0x10000000000000B17) >> 64;
}
if (x & 0x800 > 0) {
result = (result * 0x1000000000000058C) >> 64;
}
if (x & 0x400 > 0) {
result = (result * 0x100000000000002C6) >> 64;
}
if (x & 0x200 > 0) {
result = (result * 0x10000000000000163) >> 64;
}
if (x & 0x100 > 0) {
result = (result * 0x100000000000000B1) >> 64;
}
if (x & 0x80 > 0) {
result = (result * 0x10000000000000059) >> 64;
}
if (x & 0x40 > 0) {
result = (result * 0x1000000000000002C) >> 64;
}
if (x & 0x20 > 0) {
result = (result * 0x10000000000000016) >> 64;
}
if (x & 0x10 > 0) {
result = (result * 0x1000000000000000B) >> 64;
}
if (x & 0x8 > 0) {
result = (result * 0x10000000000000006) >> 64;
}
if (x & 0x4 > 0) {
result = (result * 0x10000000000000003) >> 64;
}
if (x & 0x2 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
if (x & 0x1 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
// We're doing two things at the same time:
//
// 1. Multiply the result by 2^n + 1, where "2^n" is the integer part and the one is added to account for
// the fact that we initially set the result to 0.5. This is accomplished by subtracting from 191
// rather than 192.
// 2. Convert the result to the unsigned 60.18-decimal fixed-point format.
//
// This works because 2^(191-ip) = 2^ip / 2^191, where "ip" is the integer part "2^n".
result *= SCALE;
result >>= (191 - (x >> 64));
}
}
/// @notice Finds the zero-based index of the first one in the binary representation of x.
/// @dev See the note on msb in the "Find First Set" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set
/// @param x The uint256 number for which to find the index of the most significant bit.
/// @return msb The index of the most significant bit as an uint256.
function mostSignificantBit(uint256 x) internal pure returns (uint256 msb) {
if (x >= 2**128) {
x >>= 128;
msb += 128;
}
if (x >= 2**64) {
x >>= 64;
msb += 64;
}
if (x >= 2**32) {
x >>= 32;
msb += 32;
}
if (x >= 2**16) {
x >>= 16;
msb += 16;
}
if (x >= 2**8) {
x >>= 8;
msb += 8;
}
if (x >= 2**4) {
x >>= 4;
msb += 4;
}
if (x >= 2**2) {
x >>= 2;
msb += 2;
}
if (x >= 2**1) {
// No need to shift x any more.
msb += 1;
}
}
/// @notice Calculates floor(x*y÷denominator) with full precision.
///
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.
///
/// Requirements:
/// - The denominator cannot be zero.
/// - The result must fit within uint256.
///
/// Caveats:
/// - This function does not work with fixed-point numbers.
///
/// @param x The multiplicand as an uint256.
/// @param y The multiplier as an uint256.
/// @param denominator The divisor as an uint256.
/// @return result The result as an uint256.
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
unchecked {
result = prod0 / denominator;
}
return result;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (prod1 >= denominator) {
revert PRBMath__MulDivOverflow(prod1, denominator);
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
unchecked {
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 lpotdod = denominator & (~denominator + 1);
assembly {
// Divide denominator by lpotdod.
denominator := div(denominator, lpotdod)
// Divide [prod1 prod0] by lpotdod.
prod0 := div(prod0, lpotdod)
// Flip lpotdod such that it is 2^256 / lpotdod. If lpotdod is zero, then it becomes one.
lpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * lpotdod;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/// @notice Calculates floor(x*y÷1e18) with full precision.
///
/// @dev Variant of "mulDiv" with constant folding, i.e. in which the denominator is always 1e18. Before returning the
/// final result, we add 1 if (x * y) % SCALE >= HALF_SCALE. Without this, 6.6e-19 would be truncated to 0 instead of
/// being rounded to 1e-18. See "Listing 6" and text above it at https://accu.org/index.php/journals/1717.
///
/// Requirements:
/// - The result must fit within uint256.
///
/// Caveats:
/// - The body is purposely left uncommented; see the NatSpec comments in "PRBMath.mulDiv" to understand how this works.
/// - It is assumed that the result can never be type(uint256).max when x and y solve the following two equations:
/// 1. x * y = type(uint256).max * SCALE
/// 2. (x * y) % SCALE >= SCALE / 2
///
/// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.
/// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function mulDivFixedPoint(uint256 x, uint256 y) internal pure returns (uint256 result) {
uint256 prod0;
uint256 prod1;
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 >= SCALE) {
revert PRBMath__MulDivFixedPointOverflow(prod1);
}
uint256 remainder;
uint256 roundUpUnit;
assembly {
remainder := mulmod(x, y, SCALE)
roundUpUnit := gt(remainder, 499999999999999999)
}
if (prod1 == 0) {
unchecked {
result = (prod0 / SCALE) + roundUpUnit;
return result;
}
}
assembly {
result := add(
mul(
or(
div(sub(prod0, remainder), SCALE_LPOTD),
mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, SCALE_LPOTD), SCALE_LPOTD), 1))
),
SCALE_INVERSE
),
roundUpUnit
)
}
}
/// @notice Calculates floor(x*y÷denominator) with full precision.
///
/// @dev An extension of "mulDiv" for signed numbers. Works by computing the signs and the absolute values separately.
///
/// Requirements:
/// - None of the inputs can be type(int256).min.
/// - The result must fit within int256.
///
/// @param x The multiplicand as an int256.
/// @param y The multiplier as an int256.
/// @param denominator The divisor as an int256.
/// @return result The result as an int256.
function mulDivSigned(
int256 x,
int256 y,
int256 denominator
) internal pure returns (int256 result) {
if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {
revert PRBMath__MulDivSignedInputTooSmall();
}
// Get hold of the absolute values of x, y and the denominator.
uint256 ax;
uint256 ay;
uint256 ad;
unchecked {
ax = x < 0 ? uint256(-x) : uint256(x);
ay = y < 0 ? uint256(-y) : uint256(y);
ad = denominator < 0 ? uint256(-denominator) : uint256(denominator);
}
// Compute the absolute value of (x*y)÷denominator. The result must fit within int256.
uint256 rAbs = mulDiv(ax, ay, ad);
if (rAbs > uint256(type(int256).max)) {
revert PRBMath__MulDivSignedOverflow(rAbs);
}
// Get the signs of x, y and the denominator.
uint256 sx;
uint256 sy;
uint256 sd;
assembly {
sx := sgt(x, sub(0, 1))
sy := sgt(y, sub(0, 1))
sd := sgt(denominator, sub(0, 1))
}
// XOR over sx, sy and sd. This is checking whether there are one or three negative signs in the inputs.
// If yes, the result should be negative.
result = sx ^ sy ^ sd == 0 ? -int256(rAbs) : int256(rAbs);
}
/// @notice Calculates the square root of x, rounding down.
/// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Caveats:
/// - This function does not work with fixed-point numbers.
///
/// @param x The uint256 number for which to calculate the square root.
/// @return result The result as an uint256.
function sqrt(uint256 x) internal pure returns (uint256 result) {
if (x == 0) {
return 0;
}
// Set the initial guess to the least power of two that is greater than or equal to sqrt(x).
uint256 xAux = uint256(x);
result = 1;
if (xAux >= 0x100000000000000000000000000000000) {
xAux >>= 128;
result <<= 64;
}
if (xAux >= 0x10000000000000000) {
xAux >>= 64;
result <<= 32;
}
if (xAux >= 0x100000000) {
xAux >>= 32;
result <<= 16;
}
if (xAux >= 0x10000) {
xAux >>= 16;
result <<= 8;
}
if (xAux >= 0x100) {
xAux >>= 8;
result <<= 4;
}
if (xAux >= 0x10) {
xAux >>= 4;
result <<= 2;
}
if (xAux >= 0x8) {
result <<= 1;
}
// The operations can never overflow because the result is max 2^127 when it enters this block.
unchecked {
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1; // Seven iterations should be enough
uint256 roundedDownResult = x / result;
return result >= roundedDownResult ? roundedDownResult : result;
}
}
}
/// @title PRBMathSD59x18
/// @author Paul Razvan Berg
/// @notice Smart contract library for advanced fixed-point math that works with int256 numbers considered to have 18
/// trailing decimals. We call this number representation signed 59.18-decimal fixed-point, since the numbers can have
/// a sign and there can be up to 59 digits in the integer part and up to 18 decimals in the fractional part. The numbers
/// are bound by the minimum and the maximum values permitted by the Solidity type int256.
library PRBMathSD59x18 {
/// @dev log2(e) as a signed 59.18-decimal fixed-point number.
int256 internal constant LOG2_E = 1_442695040888963407;
/// @dev Half the SCALE number.
int256 internal constant HALF_SCALE = 5e17;
/// @dev The maximum value a signed 59.18-decimal fixed-point number can have.
int256 internal constant MAX_SD59x18 =
57896044618658097711785492504343953926634992332820282019728_792003956564819967;
/// @dev The maximum whole value a signed 59.18-decimal fixed-point number can have.
int256 internal constant MAX_WHOLE_SD59x18 =
57896044618658097711785492504343953926634992332820282019728_000000000000000000;
/// @dev The minimum value a signed 59.18-decimal fixed-point number can have.
int256 internal constant MIN_SD59x18 =
-57896044618658097711785492504343953926634992332820282019728_792003956564819968;
/// @dev The minimum whole value a signed 59.18-decimal fixed-point number can have.
int256 internal constant MIN_WHOLE_SD59x18 =
-57896044618658097711785492504343953926634992332820282019728_000000000000000000;
/// @dev How many trailing decimals can be represented.
int256 internal constant SCALE = 1e18;
/// INTERNAL FUNCTIONS ///
/// @notice Calculate the absolute value of x.
///
/// @dev Requirements:
/// - x must be greater than MIN_SD59x18.
///
/// @param x The number to calculate the absolute value for.
/// @param result The absolute value of x.
function abs(int256 x) internal pure returns (int256 result) {
unchecked {
if (x == MIN_SD59x18) {
revert PRBMathSD59x18__AbsInputTooSmall();
}
result = x < 0 ? -x : x;
}
}
/// @notice Calculates the arithmetic average of x and y, rounding down.
/// @param x The first operand as a signed 59.18-decimal fixed-point number.
/// @param y The second operand as a signed 59.18-decimal fixed-point number.
/// @return result The arithmetic average as a signed 59.18-decimal fixed-point number.
function avg(int256 x, int256 y) internal pure returns (int256 result) {
// The operations can never overflow.
unchecked {
int256 sum = (x >> 1) + (y >> 1);
if (sum < 0) {
// If at least one of x and y is odd, we add 1 to the result. This is because shifting negative numbers to the
// right rounds down to infinity.
assembly {
result := add(sum, and(or(x, y), 1))
}
} else {
// If both x and y are odd, we add 1 to the result. This is because if both numbers are odd, the 0.5
// remainder gets truncated twice.
result = sum + (x & y & 1);
}
}
}
/// @notice Yields the least greatest signed 59.18 decimal fixed-point number greater than or equal to x.
///
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x must be less than or equal to MAX_WHOLE_SD59x18.
///
/// @param x The signed 59.18-decimal fixed-point number to ceil.
/// @param result The least integer greater than or equal to x, as a signed 58.18-decimal fixed-point number.
function ceil(int256 x) internal pure returns (int256 result) {
if (x > MAX_WHOLE_SD59x18) {
revert PRBMathSD59x18__CeilOverflow(x);
}
unchecked {
int256 remainder = x % SCALE;
if (remainder == 0) {
result = x;
} else {
// Solidity uses C fmod style, which returns a modulus with the same sign as x.
result = x - remainder;
if (x > 0) {
result += SCALE;
}
}
}
}
/// @notice Divides two signed 59.18-decimal fixed-point numbers, returning a new signed 59.18-decimal fixed-point number.
///
/// @dev Variant of "mulDiv" that works with signed numbers. Works by computing the signs and the absolute values separately.
///
/// Requirements:
/// - All from "PRBMath.mulDiv".
/// - None of the inputs can be MIN_SD59x18.
/// - The denominator cannot be zero.
/// - The result must fit within int256.
///
/// Caveats:
/// - All from "PRBMath.mulDiv".
///
/// @param x The numerator as a signed 59.18-decimal fixed-point number.
/// @param y The denominator as a signed 59.18-decimal fixed-point number.
/// @param result The quotient as a signed 59.18-decimal fixed-point number.
function div(int256 x, int256 y) internal pure returns (int256 result) {
if (x == MIN_SD59x18 || y == MIN_SD59x18) {
revert PRBMathSD59x18__DivInputTooSmall();
}
// Get hold of the absolute values of x and y.
uint256 ax;
uint256 ay;
unchecked {
ax = x < 0 ? uint256(-x) : uint256(x);
ay = y < 0 ? uint256(-y) : uint256(y);
}
// Compute the absolute value of (x*SCALE)÷y. The result must fit within int256.
uint256 rAbs = PRBMath.mulDiv(ax, uint256(SCALE), ay);
if (rAbs > uint256(MAX_SD59x18)) {
revert PRBMathSD59x18__DivOverflow(rAbs);
}
// Get the signs of x and y.
uint256 sx;
uint256 sy;
assembly {
sx := sgt(x, sub(0, 1))
sy := sgt(y, sub(0, 1))
}
// XOR over sx and sy. This is basically checking whether the inputs have the same sign. If yes, the result
// should be positive. Otherwise, it should be negative.
result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs);
}
/// @notice Returns Euler's number as a signed 59.18-decimal fixed-point number.
/// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant).
function e() internal pure returns (int256 result) {
result = 2_718281828459045235;
}
/// @notice Calculates the natural exponent of x.
///
/// @dev Based on the insight that e^x = 2^(x * log2(e)).
///
/// Requirements:
/// - All from "log2".
/// - x must be less than 133.084258667509499441.
///
/// Caveats:
/// - All from "exp2".
/// - For any x less than -41.446531673892822322, the result is zero.
///
/// @param x The exponent as a signed 59.18-decimal fixed-point number.
/// @return result The result as a signed 59.18-decimal fixed-point number.
function exp(int256 x) internal pure returns (int256 result) {
// Without this check, the value passed to "exp2" would be less than -59.794705707972522261.
if (x < -41_446531673892822322) {
return 0;
}
// Without this check, the value passed to "exp2" would be greater than 192.
if (x >= 133_084258667509499441) {
revert PRBMathSD59x18__ExpInputTooBig(x);
}
// Do the fixed-point multiplication inline to save gas.
unchecked {
int256 doubleScaleProduct = x * LOG2_E;
result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE);
}
}
/// @notice Calculates the binary exponent of x using the binary fraction method.
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693.
///
/// Requirements:
/// - x must be 192 or less.
/// - The result must fit within MAX_SD59x18.
///
/// Caveats:
/// - For any x less than -59.794705707972522261, the result is zero.
///
/// @param x The exponent as a signed 59.18-decimal fixed-point number.
/// @return result The result as a signed 59.18-decimal fixed-point number.
function exp2(int256 x) internal pure returns (int256 result) {
// This works because 2^(-x) = 1/2^x.
if (x < 0) {
// 2^59.794705707972522262 is the maximum number whose inverse does not truncate down to zero.
if (x < -59_794705707972522261) {
return 0;
}
// Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE.
unchecked {
result = 1e36 / exp2(-x);
}
} else {
// 2^192 doesn't fit within the 192.64-bit format used internally in this function.
if (x >= 192e18) {
revert PRBMathSD59x18__Exp2InputTooBig(x);
}
unchecked {
// Convert x to the 192.64-bit fixed-point format.
uint256 x192x64 = (uint256(x) << 64) / uint256(SCALE);
// Safe to convert the result to int256 directly because the maximum input allowed is 192.
result = int256(PRBMath.exp2(x192x64));
}
}
}
/// @notice Yields the greatest signed 59.18 decimal fixed-point number less than or equal to x.
///
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x must be greater than or equal to MIN_WHOLE_SD59x18.
///
/// @param x The signed 59.18-decimal fixed-point number to floor.
/// @param result The greatest integer less than or equal to x, as a signed 58.18-decimal fixed-point number.
function floor(int256 x) internal pure returns (int256 result) {
if (x < MIN_WHOLE_SD59x18) {
revert PRBMathSD59x18__FloorUnderflow(x);
}
unchecked {
int256 remainder = x % SCALE;
if (remainder == 0) {
result = x;
} else {
// Solidity uses C fmod style, which returns a modulus with the same sign as x.
result = x - remainder;
if (x < 0) {
result -= SCALE;
}
}
}
}
/// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right
/// of the radix point for negative numbers.
/// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part
/// @param x The signed 59.18-decimal fixed-point number to get the fractional part of.
/// @param result The fractional part of x as a signed 59.18-decimal fixed-point number.
function frac(int256 x) internal pure returns (int256 result) {
unchecked {
result = x % SCALE;
}
}
/// @notice Converts a number from basic integer form to signed 59.18-decimal fixed-point representation.
///
/// @dev Requirements:
/// - x must be greater than or equal to MIN_SD59x18 divided by SCALE.
/// - x must be less than or equal to MAX_SD59x18 divided by SCALE.
///
/// @param x The basic integer to convert.
/// @param result The same number in signed 59.18-decimal fixed-point representation.
function fromInt(int256 x) internal pure returns (int256 result) {
unchecked {
if (x < MIN_SD59x18 / SCALE) {
revert PRBMathSD59x18__FromIntUnderflow(x);
}
if (x > MAX_SD59x18 / SCALE) {
revert PRBMathSD59x18__FromIntOverflow(x);
}
result = x * SCALE;
}
}
/// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down.
///
/// @dev Requirements:
/// - x * y must fit within MAX_SD59x18, lest it overflows.
/// - x * y cannot be negative.
///
/// @param x The first operand as a signed 59.18-decimal fixed-point number.
/// @param y The second operand as a signed 59.18-decimal fixed-point number.
/// @return result The result as a signed 59.18-decimal fixed-point number.
function gm(int256 x, int256 y) internal pure returns (int256 result) {
if (x == 0) {
return 0;
}
unchecked {
// Checking for overflow this way is faster than letting Solidity do it.
int256 xy = x * y;
if (xy / x != y) {
revert PRBMathSD59x18__GmOverflow(x, y);
}
// The product cannot be negative.
if (xy < 0) {
revert PRBMathSD59x18__GmNegativeProduct(x, y);
}
// We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE
// during multiplication. See the comments within the "sqrt" function.
result = int256(PRBMath.sqrt(uint256(xy)));
}
}
/// @notice Calculates 1 / x, rounding toward zero.
///
/// @dev Requirements:
/// - x cannot be zero.
///
/// @param x The signed 59.18-decimal fixed-point number for which to calculate the inverse.
/// @return result The inverse as a signed 59.18-decimal fixed-point number.
function inv(int256 x) internal pure returns (int256 result) {
unchecked {
// 1e36 is SCALE * SCALE.
result = 1e36 / x;
}
}
/// @notice Calculates the natural logarithm of x.
///
/// @dev Based on the insight that ln(x) = log2(x) / log2(e).
///
/// Requirements:
/// - All from "log2".
///
/// Caveats:
/// - All from "log2".
/// - This doesn't return exactly 1 for 2718281828459045235, for that we would need more fine-grained precision.
///
/// @param x The signed 59.18-decimal fixed-point number for which to calculate the natural logarithm.
/// @return result The natural logarithm as a signed 59.18-decimal fixed-point number.
function ln(int256 x) internal pure returns (int256 result) {
// Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x)
// can return is 195205294292027477728.
unchecked {
result = (log2(x) * SCALE) / LOG2_E;
}
}
/// @notice Calculates the common logarithm of x.
///
/// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common
/// logarithm based on the insight that log10(x) = log2(x) / log2(10).
///
/// Requirements:
/// - All from "log2".
///
/// Caveats:
/// - All from "log2".
///
/// @param x The signed 59.18-decimal fixed-point number for which to calculate the common logarithm.
/// @return result The common logarithm as a signed 59.18-decimal fixed-point number.
function log10(int256 x) internal pure returns (int256 result) {
if (x <= 0) {
revert PRBMathSD59x18__LogInputTooSmall(x);
}
// Note that the "mul" in this block is the assembly mul operation, not the "mul" function defined in this contract.
// prettier-ignore
assembly {
switch x
case 1 { result := mul(SCALE, sub(0, 18)) }
case 10 { result := mul(SCALE, sub(1, 18)) }
case 100 { result := mul(SCALE, sub(2, 18)) }
case 1000 { result := mul(SCALE, sub(3, 18)) }
case 10000 { result := mul(SCALE, sub(4, 18)) }
case 100000 { result := mul(SCALE, sub(5, 18)) }
case 1000000 { result := mul(SCALE, sub(6, 18)) }
case 10000000 { result := mul(SCALE, sub(7, 18)) }
case 100000000 { result := mul(SCALE, sub(8, 18)) }
case 1000000000 { result := mul(SCALE, sub(9, 18)) }
case 10000000000 { result := mul(SCALE, sub(10, 18)) }
case 100000000000 { result := mul(SCALE, sub(11, 18)) }
case 1000000000000 { result := mul(SCALE, sub(12, 18)) }
case 10000000000000 { result := mul(SCALE, sub(13, 18)) }
case 100000000000000 { result := mul(SCALE, sub(14, 18)) }
case 1000000000000000 { result := mul(SCALE, sub(15, 18)) }
case 10000000000000000 { result := mul(SCALE, sub(16, 18)) }
case 100000000000000000 { result := mul(SCALE, sub(17, 18)) }
case 1000000000000000000 { result := 0 }
case 10000000000000000000 { result := SCALE }
case 100000000000000000000 { result := mul(SCALE, 2) }
case 1000000000000000000000 { result := mul(SCALE, 3) }
case 10000000000000000000000 { result := mul(SCALE, 4) }
case 100000000000000000000000 { result := mul(SCALE, 5) }
case 1000000000000000000000000 { result := mul(SCALE, 6) }
case 10000000000000000000000000 { result := mul(SCALE, 7) }
case 100000000000000000000000000 { result := mul(SCALE, 8) }
case 1000000000000000000000000000 { result := mul(SCALE, 9) }
case 10000000000000000000000000000 { result := mul(SCALE, 10) }
case 100000000000000000000000000000 { result := mul(SCALE, 11) }
case 1000000000000000000000000000000 { result := mul(SCALE, 12) }
case 10000000000000000000000000000000 { result := mul(SCALE, 13) }
case 100000000000000000000000000000000 { result := mul(SCALE, 14) }
case 1000000000000000000000000000000000 { result := mul(SCALE, 15) }
case 10000000000000000000000000000000000 { result := mul(SCALE, 16) }
case 100000000000000000000000000000000000 { result := mul(SCALE, 17) }
case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) }
case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) }
case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) }
case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) }
case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) }
case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) }
case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) }
case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) }
case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) }
case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) }
case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) }
case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) }
case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) }
case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) }
case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) }
case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) }
case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) }
case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) }
case 1000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 36) }
case 10000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 37) }
case 100000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 38) }
case 1000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 39) }
case 10000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 40) }
case 100000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 41) }
case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 42) }
case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 43) }
case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 44) }
case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 45) }
case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 46) }
case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 47) }
case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 48) }
case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 49) }
case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 50) }
case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 51) }
case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 52) }
case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 53) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 54) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 55) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 56) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 57) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 58) }
default {
result := MAX_SD59x18
}
}
if (result == MAX_SD59x18) {
// Do the fixed-point division inline to save gas. The denominator is log2(10).
unchecked {
result = (log2(x) * SCALE) / 3_321928094887362347;
}
}
}
/// @notice Calculates the binary logarithm of x.
///
/// @dev Based on the iterative approximation algorithm.
/// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
///
/// Requirements:
/// - x must be greater than zero.
///
/// Caveats:
/// - The results are not perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation.
///
/// @param x The signed 59.18-decimal fixed-point number for which to calculate the binary logarithm.
/// @return result The binary logarithm as a signed 59.18-decimal fixed-point number.
function log2(int256 x) internal pure returns (int256 result) {
if (x <= 0) {
revert PRBMathSD59x18__LogInputTooSmall(x);
}
unchecked {
// This works because log2(x) = -log2(1/x).
int256 sign;
if (x >= SCALE) {
sign = 1;
} else {
sign = -1;
// Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE.
assembly {
x := div(1000000000000000000000000000000000000, x)
}
}
// Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n).
uint256 n = PRBMath.mostSignificantBit(uint256(x / SCALE));
// The integer part of the logarithm as a signed 59.18-decimal fixed-point number. The operation can't overflow
// because n is maximum 255, SCALE is 1e18 and sign is either 1 or -1.
result = int256(n) * SCALE;
// This is y = x * 2^(-n).
int256 y = x >> n;
// If y = 1, the fractional part is zero.
if (y == SCALE) {
return result * sign;
}
// Calculate the fractional part via the iterative approximation.
// The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster.
for (int256 delta = int256(HALF_SCALE); delta > 0; delta >>= 1) {
y = (y * y) / SCALE;
// Is y^2 > 2 and so in the range [2,4)?
if (y >= 2 * SCALE) {
// Add the 2^(-m) factor to the logarithm.
result += delta;
// Corresponds to z/2 on Wikipedia.
y >>= 1;
}
}
result *= sign;
}
}
/// @notice Multiplies two signed 59.18-decimal fixed-point numbers together, returning a new signed 59.18-decimal
/// fixed-point number.
///
/// @dev Variant of "mulDiv" that works with signed numbers and employs constant folding, i.e. the denominator is
/// always 1e18.
///
/// Requirements:
/// - All from "PRBMath.mulDivFixedPoint".
/// - None of the inputs can be MIN_SD59x18
/// - The result must fit within MAX_SD59x18.
///
/// Caveats:
/// - The body is purposely left uncommented; see the NatSpec comments in "PRBMath.mulDiv" to understand how this works.
///
/// @param x The multiplicand as a signed 59.18-decimal fixed-point number.
/// @param y The multiplier as a signed 59.18-decimal fixed-point number.
/// @return result The product as a signed 59.18-decimal fixed-point number.
function mul(int256 x, int256 y) internal pure returns (int256 result) {
if (x == MIN_SD59x18 || y == MIN_SD59x18) {
revert PRBMathSD59x18__MulInputTooSmall();
}
unchecked {
uint256 ax;
uint256 ay;
ax = x < 0 ? uint256(-x) : uint256(x);
ay = y < 0 ? uint256(-y) : uint256(y);
uint256 rAbs = PRBMath.mulDivFixedPoint(ax, ay);
if (rAbs > uint256(MAX_SD59x18)) {
revert PRBMathSD59x18__MulOverflow(rAbs);
}
uint256 sx;
uint256 sy;
assembly {
sx := sgt(x, sub(0, 1))
sy := sgt(y, sub(0, 1))
}
result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs);
}
}
/// @notice Returns PI as a signed 59.18-decimal fixed-point number.
function pi() internal pure returns (int256 result) {
result = 3_141592653589793238;
}
/// @notice Raises x to the power of y.
///
/// @dev Based on the insight that x^y = 2^(log2(x) * y).
///
/// Requirements:
/// - All from "exp2", "log2" and "mul".
/// - z cannot be zero.
///
/// Caveats:
/// - All from "exp2", "log2" and "mul".
/// - Assumes 0^0 is 1.
///
/// @param x Number to raise to given power y, as a signed 59.18-decimal fixed-point number.
/// @param y Exponent to raise x to, as a signed 59.18-decimal fixed-point number.
/// @return result x raised to power y, as a signed 59.18-decimal fixed-point number.
function pow(int256 x, int256 y) internal pure returns (int256 result) {
if (x == 0) {
result = y == 0 ? SCALE : int256(0);
} else {
result = exp2(mul(log2(x), y));
}
}
/// @notice Raises x (signed 59.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the
/// famous algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring
///
/// Requirements:
/// - All from "abs" and "PRBMath.mulDivFixedPoint".
/// - The result must fit within MAX_SD59x18.
///
/// Caveats:
/// - All from "PRBMath.mulDivFixedPoint".
/// - Assumes 0^0 is 1.
///
/// @param x The base as a signed 59.18-decimal fixed-point number.
/// @param y The exponent as an uint256.
/// @return result The result as a signed 59.18-decimal fixed-point number.
function powu(int256 x, uint256 y) internal pure returns (int256 result) {
uint256 xAbs = uint256(abs(x));
// Calculate the first iteration of the loop in advance.
uint256 rAbs = y & 1 > 0 ? xAbs : uint256(SCALE);
// Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster.
uint256 yAux = y;
for (yAux >>= 1; yAux > 0; yAux >>= 1) {
xAbs = PRBMath.mulDivFixedPoint(xAbs, xAbs);
// Equivalent to "y % 2 == 1" but faster.
if (yAux & 1 > 0) {
rAbs = PRBMath.mulDivFixedPoint(rAbs, xAbs);
}
}
// The result must fit within the 59.18-decimal fixed-point representation.
if (rAbs > uint256(MAX_SD59x18)) {
revert PRBMathSD59x18__PowuOverflow(rAbs);
}
// Is the base negative and the exponent an odd number?
bool isNegative = x < 0 && y & 1 == 1;
result = isNegative ? -int256(rAbs) : int256(rAbs);
}
/// @notice Returns 1 as a signed 59.18-decimal fixed-point number.
function scale() internal pure returns (int256 result) {
result = SCALE;
}
/// @notice Calculates the square root of x, rounding down.
/// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Requirements:
/// - x cannot be negative.
/// - x must be less than MAX_SD59x18 / SCALE.
///
/// @param x The signed 59.18-decimal fixed-point number for which to calculate the square root.
/// @return result The result as a signed 59.18-decimal fixed-point .
function sqrt(int256 x) internal pure returns (int256 result) {
unchecked {
if (x < 0) {
revert PRBMathSD59x18__SqrtNegativeInput(x);
}
if (x > MAX_SD59x18 / SCALE) {
revert PRBMathSD59x18__SqrtOverflow(x);
}
// Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two signed
// 59.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root).
result = int256(PRBMath.sqrt(uint256(x * SCALE)));
}
}
/// @notice Converts a signed 59.18-decimal fixed-point number to basic integer form, rounding down in the process.
/// @param x The signed 59.18-decimal fixed-point number to convert.
/// @return result The same number in basic integer form.
function toInt(int256 x) internal pure returns (int256 result) {
unchecked {
result = x / SCALE;
}
}
}
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/**
* @dev 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 VORSafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function safeAdd(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 safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function safeMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function saveDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function safeMod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20_Ex {
/**
* @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 Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IVORCoordinator {
function getProviderAddress(bytes32 _keyHash) external view returns (address);
function getProviderFee(bytes32 _keyHash) external view returns (uint96);
function getProviderGranularFee(bytes32 _keyHash, address _consumer) external view returns (uint96);
function randomnessRequest(bytes32 keyHash, uint256 consumerSeed, uint256 feePaid) external;
}
/**
* @title VORRequestIDBase
*/
contract VORRequestIDBase {
/**
* @notice returns the seed which is actually input to the VOR coordinator
*
* @dev To prevent repetition of VOR output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VOR seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVORInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
) internal pure returns (uint256) {
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vORInputSeed The seed to be passed directly to the VOR
* @return The id for this request
*
* @dev Note that _vORInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVORInputSeed
*/
function makeRequestId(bytes32 _keyHash, uint256 _vORInputSeed) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_keyHash, _vORInputSeed));
}
}
/**
* @title VORConsumerBase
* @notice Interface for contracts using VOR randomness
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* to Vera the verifier in such a way that Vera can be sure he's not
* making his output up to suit himself. Reggie provides Vera a public key
* to which he knows the secret key. Each time Vera provides a seed to
* Reggie, he gives back a value which is computed completely
* deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* correctly computed once Reggie tells it to her, but without that proof,
* the output is indistinguishable to her from a uniform random sample
* from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* to talk to Vera the verifier about the work Reggie is doing, to provide
* simple access to a verifiable source of randomness.
*
* @dev USAGE
*
* @dev Calling contracts must inherit from VORConsumerBase, and can
* initialize VORConsumerBase's attributes in their constructor as
* shown:
*
* ```
* contract VORConsumer {
* constuctor(<other arguments>, address _vorCoordinator, address _xfund)
* VORConsumerBase(_vorCoordinator, _xfund) public {
* <initialization with other arguments goes here>
* }
* }
* ```
* @dev The oracle will have given you an ID for the VOR keypair they have
* committed to (let's call it keyHash), and have told you the minimum xFUND
* price for VOR service. Make sure your contract has sufficient xFUND, and
* call requestRandomness(keyHash, fee, seed), where seed is the input you
* want to generate randomness from.
*
* @dev Once the VORCoordinator has received and validated the oracle's response
* to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* makeRequestId(keyHash, seed). If your contract could have concurrent
* requests open, you can use the requestId to track which seed is
* associated with which randomness. See VORRequestIDBase.sol for more
* details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* differ. (Which is critical to making unpredictable randomness! See the
* next section.)
*
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* could spoof a VOR response with any random value, so it's critical that
* it cannot be directly called by anything other than this base contract
* (specifically, by the VORConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* from malicious interference, it's best if you can write it so that all
* behaviors implied by a VOR response are executed *during* your
* fulfillRandomness method. If your contract must store the response (or
* anything derived from it) and use it later, you must ensure that any
* user-significant behavior which depends on that stored value cannot be
* manipulated by a subsequent VOR request.
*
* @dev Similarly, both miners and the VOR oracle itself have some influence
* over the order in which VOR responses appear on the blockchain, so if
* your contract could have multiple VOR requests in flight simultaneously,
* you must ensure that the order in which the VOR responses arrive cannot
* be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VOR is mixed with the block hash of the
* block in which the request is made, user-provided seeds have no impact
* on its economic security properties. They are only included for API
* compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* call is mixed into the input to the VOR *last*, a sufficiently powerful
* miner could, in principle, fork the blockchain to evict the block
* containing the request, forcing the request to be included in a
* different block with a different hash, and therefore a different input
* to the VOR. However, such an attack would incur a substantial economic
* cost. This cost scales with the number of blocks the VOR oracle waits
* until it calls responds to a request.
*/
abstract contract VORConsumerBase is VORRequestIDBase {
using VORSafeMath for uint256;
/**
* @notice fulfillRandomness handles the VOR response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VORConsumerBase expects its subcontracts to have a method with this
* signature, and will call it once it has verified the proof
* associated with the randomness. (It is triggered via a call to
* rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VOR output
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual;
/**
* @notice requestRandomness initiates a request for VOR output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* by the Oracle, and verified by the vorCoordinator.
*
* @dev The _keyHash must already be registered with the VORCoordinator, and
* the _fee must exceed the fee specified during registration of the
* _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* compatibility with older versions. It can't *hurt* to mix in some of
* your own randomness, here, but it's not necessary because the VOR
* oracle will mix the hash of the block containing your request into the
* VOR seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of xFUND to send with the request
* @param _seed seed mixed into the input of the VOR.
*
* @return requestId unique ID for this request
*
* The returned requestId can be used to distinguish responses to
* concurrent requests. It is passed as the first argument to
* fulfillRandomness.
*/
function requestRandomness(bytes32 _keyHash, uint256 _fee, uint256 _seed) internal returns (bytes32 requestId) {
IVORCoordinator(vorCoordinator).randomnessRequest(_keyHash, _seed, _fee);
// This is the seed passed to VORCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VOR cryptographic machinery.
uint256 vORSeed = makeVORInputSeed(_keyHash, _seed, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VORCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful VORCoordinator.randomnessRequest.
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash].safeAdd(1);
return makeRequestId(_keyHash, vORSeed);
}
/**
* @notice _increaseVorCoordinatorAllowance is a helper function to increase token allowance for
* the VORCoordinator
* Allows this contract to increase the xFUND allowance for the VORCoordinator contract
* enabling it to pay request fees on behalf of this contract.
* NOTE: it is hightly recommended to wrap this around a function that uses,
* for example, OpenZeppelin's onlyOwner modifier
*
* @param _amount uint256 amount to increase allowance by
*/
function _increaseVorCoordinatorAllowance(uint256 _amount) internal returns (bool) {
require(xFUND.increaseAllowance(vorCoordinator, _amount), "failed to increase allowance");
return true;
}
/**
* @notice _setVORCoordinator is a helper function to enable setting the VORCoordinator address
* NOTE: it is hightly recommended to wrap this around a function that uses,
* for example, OpenZeppelin's onlyOwner modifier
*
* @param _vorCoordinator address new VORCoordinator address
*/
function _setVORCoordinator(address _vorCoordinator) internal {
vorCoordinator = _vorCoordinator;
}
address internal immutable xFUNDAddress;
IERC20_Ex internal immutable xFUND;
address internal vorCoordinator;
// Nonces for each VOR key from which randomness has been requested.
//
// Must stay in sync with VORCoordinator[_keyHash][this]
/* keyHash */
/* nonce */
mapping(bytes32 => uint256) private nonces;
/**
* @param _vorCoordinator address of VORCoordinator contract
* @param _xfund address of xFUND token contract
*/
constructor(address _vorCoordinator, address _xfund) internal {
vorCoordinator = _vorCoordinator;
xFUNDAddress = _xfund;
xFUND = IERC20_Ex(_xfund);
}
/**
* @notice rawFulfillRandomness is called by VORCoordinator when it receives a valid VOR
* proof. rawFulfillRandomness then calls fulfillRandomness, after validating
* the origin of the call
*/
function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external {
require(msg.sender == vorCoordinator, "Only VORCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
/**
* @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 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);
}
/**
* @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 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);
}
}
}
}
/**
* @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);
}
}
/**
* @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 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 {}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @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();
}
}
// @title Base64
// @notice Provides a function for encoding some bytes in base64
// @author Brecht Devos <[email protected]>
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
interface IPlayingCards {
function getCardNumberAsUint(uint8 cardId) external view returns (uint8);
function getCardSuitAsUint(uint8 cardId) external view returns (uint8);
function getCardNumberAsStr(uint8 cardId) external view returns (string memory);
function getCardSuitAsStr(uint8 cardId) external view returns (string memory);
function getCardAsString(uint8 cardId) external view returns (string memory);
function getCardAsSvg(uint8 cardId) external view returns (string memory);
function getCardAsComponents(uint8 cardId) external view returns (uint8 number, uint8 suit);
function getCardBody(uint8 numberId, uint8 suitId, uint256 fX, uint256 sX, uint256 rX) external pure returns (string memory);
function getSuitPath(uint8 suitId) external pure returns (string memory);
function getNumberPath(uint8 numberId) external pure returns (string memory);
}
contract HoldemHeroesBase is ERC721Enumerable, Ownable {
// a start-hand combination
struct Hand {
uint8 card1; // 0 - 51
uint8 card2; // 0 - 51
}
uint256 public constant MAX_NFT_SUPPLY = 1326; // final totalSupply of NFTs
// sha256 hash of all generated and shuffled hands
bytes32 public constant HAND_PROVENANCE = 0xbcd1a23f7cca99ec419590e58d82db68573d59d2cdf88a901c5c25edea2c075d;
// start index for mapping tokenId on to handId - set during the distribution phase
uint256 public startingIndex;
// time after which hands are randomised and allocated to token Ids
uint256 public REVEAL_TIMESTAMP;
// hands have been revealed
bool public REVEALED;
// ranks uploaded - used only during uploadHandRanks function
bool public RANKS_UPLOADED;
// the block number in which the final hands were revealed
uint256 public revealBlock;
// IPFS hash for provenance JSON - will be set when the last hand batch is revealed
string public PROVENANCE_IPFS;
// array of 1326 possible start hand combinations
Hand[1326] public hands;
// used during reveal function to ensure batches are uploaded sequentially
// according to provenance
uint16 public handUploadId;
uint8 public nextExpectedBatchId = 0;
// mapping to ensure batch is not re-uploaded. Only used during reveal function
mapping(bytes32 => bool) private isHandRevealed;
// Mapping to hold hand ranks. Requires populating during contract initialisation
mapping (bytes32 => uint8) public handRanks;
// The playing cards contract on which HEH is built
IPlayingCards public immutable playingCards;
/*
* EVENTS
*/
event BatchRevealed(uint16 startHandId, uint16 endHandId, bytes32 batchHash, uint8 batchId);
event RanksInitialised();
/**
* @dev constructor
* @dev initialises some basic variables.
*
* @param _revealTimestamp uint256 - unix timestamp for when cards will be revealed and distributed
* @param _playingCards address - address of Playing Cards contract
*/
constructor(uint256 _revealTimestamp, address _playingCards)
ERC721("Holdem Heroes", "HEH")
Ownable() {
REVEAL_TIMESTAMP = _revealTimestamp;
REVEALED = false;
RANKS_UPLOADED = false;
handUploadId = 0;
playingCards = IPlayingCards(_playingCards);
}
/*
* ADMIN FUNCTIONS
*/
/**
* @dev uploadHandRanks upload the 169 start hand ranks, which are referenced
* @dev by the hand getter functions. Hand ranks are stored as a mapping of a
* @dev sha256 hash and the integer rank value. The hash is generated from a
* @dev concatenation of the word "rank" and the hand's name. e.g.
* keccak256("rankA5s") => 28
*
* @param rankHashes bytes32[] array of sha256 hashes
* @param ranks uint8[] array of corresponding ranks for rankHashes
*/
function uploadHandRanks(bytes32[] memory rankHashes, uint8[] memory ranks) external onlyOwner {
require(!RANKS_UPLOADED, "uploaded");
for (uint8 i = 0; i < rankHashes.length; i++) {
handRanks[rankHashes[i]] = ranks[i];
}
RANKS_UPLOADED = true;
emit RanksInitialised();
}
/**
* @dev withdrawETH allows contract owner to withdraw ether
*/
function withdrawETH() external onlyOwner {
payable(msg.sender).transfer(address(this).balance);
}
/**
* @dev reveal is used to upload and reveal the generated start hand combinations.
* @dev hands are uploaded in batches, with each batch containing n
* @dev hands. each hand is a uint8[] array of card IDs, e.g. [2, 3]
* @dev with each batch represented as a 2d array of hands, for example, [[2, 3], [3, 4], ...]
* @dev Batches must be uploaded sequentially according to provenance.
*
* @param inputs uint8[2][] batch of hands
* @param batchId uint8 id of the batch being revealed
* @param ipfs string IPFS hash of provenance.json. Sent with final batch only
*/
function reveal(uint8[2][] memory inputs, uint8 batchId, string memory ipfs) public onlyOwner {
require(block.timestamp >= REVEAL_TIMESTAMP, "not yet");
require(handUploadId < 1325, "revealed");
require(batchId == nextExpectedBatchId, "seq incorrect");
bytes32 dataHash = keccak256(abi.encodePacked(inputs));
require(!isHandRevealed[dataHash], "already added");
isHandRevealed[dataHash] = true;
for (uint8 i = 0; i < inputs.length; i++) {
hands[handUploadId] = Hand(inputs[i][0],inputs[i][1]);
handUploadId = handUploadId + 1;
}
emit BatchRevealed(handUploadId - uint16(inputs.length), handUploadId - 1, dataHash, batchId);
if (handUploadId == 1326) {
REVEALED = true;
PROVENANCE_IPFS = ipfs;
revealBlock = block.number;
} else {
nextExpectedBatchId = nextExpectedBatchId + 1;
}
}
/*
* PUBLIC GETTERS
*/
/**
* @dev getHandShape returns the shape for a given hand ID, for example "Suited" or "s"
*
* @param handId uint16 ID of the hand from 0 - 1325
* @param abbreviate bool whether or not to abbreviate ("s" instead of Suited" if true)
* @return string shape of hand
*/
function getHandShape(uint16 handId, bool abbreviate) public validHandId(handId) view returns (string memory) {
uint8 card1N = playingCards.getCardNumberAsUint(hands[handId].card1);
uint8 card2N = playingCards.getCardNumberAsUint(hands[handId].card2);
uint8 card1S = playingCards.getCardSuitAsUint(hands[handId].card1);
uint8 card2S = playingCards.getCardSuitAsUint(hands[handId].card2);
if (card1N == card2N) {
return abbreviate ? "" : "Pair";
} else if (card1S == card2S) {
return abbreviate ? "s" : "Suited";
} else {
return abbreviate ? "o" : "Offsuit";
}
}
/**
* @dev getHandAsCardIds returns the card IDs (0 - 51) for a given hand ID, for example 12,24
*
* @param handId uint16 ID of the hand from 0 - 1325
* @return card1 uint8 ID of card 1 (0 - 51)
* @return card2 uint8 ID of card 2 (0 - 51)
*/
function getHandAsCardIds(uint16 handId) public validHandId(handId) view returns (uint8 card1, uint8 card2) {
Hand storage hand = hands[handId];
if (playingCards.getCardNumberAsUint(hand.card1) > playingCards.getCardNumberAsUint(hand.card2)) {
return (hand.card1, hand.card2);
} else {
return (hand.card2, hand.card1);
}
}
/**
* @dev getHandName returns the canonical name for a given hand ID. This is a concatenation of
* @dev Card1 + Card2 + Shape, with the cards ordered by card number in descending order.
* @dev E.g. A5s
*
* @param handId uint16 ID of the hand from 0 - 1325
* @return string hand name
*/
function getHandName(uint16 handId) public validHandId(handId) view returns (string memory) {
string memory shape = getHandShape(handId, true);
(uint8 card1, uint8 card2) = getHandAsCardIds(handId);
return string(abi.encodePacked(playingCards.getCardNumberAsStr(card1), playingCards.getCardNumberAsStr(card2), shape));
}
/**
* @dev getHandRank returns the canonical rank for a given hand ID. Lower is better
*
* @param handId uint16 ID of the hand from 0 - 1325
* @return string hand rank
*/
function getHandRank(uint16 handId) public validHandId(handId) view returns (uint8) {
return handRanks[keccak256(abi.encodePacked("rank", getHandName(handId)))];
}
/**
* @dev getHandAsString returns a concatenation of the card names
*
* @param handId uint16 ID of the hand from 0 - 1325
* @return string hand - cards names concatenated, e.g. AsAc
*/
function getHandAsString(uint16 handId) public validHandId(handId) view returns (string memory) {
(uint8 card1, uint8 card2) = getHandAsCardIds(handId);
return string(abi.encodePacked(playingCards.getCardAsString(card1), playingCards.getCardAsString(card2)));
}
/**
* @dev getHandAsSvg returns the SVG XML for a hand, which can be rendered as an img src in a UI
*
* @param handId uint16 ID of the hand from 0 - 1325
* @return string SVG XML of a hand of 2 cards
*/
function getHandAsSvg(uint16 handId) public validHandId(handId) view returns (string memory) {
(uint8 card1, uint8 card2) = getHandAsCardIds(handId);
string[4] memory parts;
parts[0] = "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" viewBox=\"0 0 148 62\" width=\"5in\" height=\"2.147in\">";
parts[1] = playingCards.getCardBody(playingCards.getCardNumberAsUint(card1), playingCards.getCardSuitAsUint(card1), 7, 32, 2);
parts[2] = playingCards.getCardBody(playingCards.getCardNumberAsUint(card2), playingCards.getCardSuitAsUint(card2), 82, 107, 76);
parts[3] = "</svg>";
string memory output = string(
abi.encodePacked(parts[0], parts[1], parts[2], parts[3])
);
return output;
}
/**
* @dev getHandHash returns a hand's hash, which can be used to match against the
* @dev published provenance. Hand hashes can be sequentially concatenated and the
* @dev concatenation itself hashed (after removing each hand hash's 0x prefix)
* @dev to get the provenance hash. This provenance hash should match both the published
* @dev hash and the HAND_PROVENANCE constant in this contract
*
* @param handId uint16 ID of the hand from 0 - 1325
* @return string hash of the hand
*/
function getHandHash(uint16 handId) public validHandId(handId) view returns (bytes32) {
(uint8 card1, uint8 card2) = getHandAsCardIds(handId);
return keccak256(abi.encodePacked(
toString(handId),
getHandAsString(handId),
toString(card1),
toString(playingCards.getCardNumberAsUint(card1)),
toString(playingCards.getCardSuitAsUint(card1)),
toString(card2),
toString(playingCards.getCardNumberAsUint(card2)),
toString(playingCards.getCardSuitAsUint(card2))
)
);
}
/**
* @dev tokenIdToHandId maps a given token ID onto its distributed hand ID
* @dev Note - this will only run after all hands have been revealed
* @dev and distributed.
*
* @param _tokenId uint256 ID of the NFT token from 0 - 1325
* @return uint16 hand ID associate to the token
*/
function tokenIdToHandId(uint256 _tokenId) public view returns (uint16) {
require(_tokenId >= 0 && _tokenId < 1326, "invalid id");
require(startingIndex > 0, "not distributed");
return uint16((_tokenId + startingIndex) % MAX_NFT_SUPPLY);
}
/**
* @dev tokenURI generates the base64 encoded JSON of the NFT itself. tokenURI will first call
* @dev tokenIdToHandId to find which hand the token is for. It will then generate
* @dev and output the encoded JSON containing the SVG image, name, description and
* @dev attributes.
* @dev Note - this will only run after all hands have been revealed
* @dev and distributed.
*
* @param _tokenId uint256 ID of the NFT token from 0 - 1325
* @return string the token's NFT JSON
*/
function tokenURI(uint256 _tokenId) public view override returns (string memory) {
// we need to map the token ID onto the assigned hand ID,
// based on the distribution's startingIndex. This is only available
// AFTER distribution has occurred, and will return an error otherwise
uint16 handId = tokenIdToHandId(_tokenId);
string memory handName = getHandAsString(handId);
string memory shape = getHandShape(handId, false);
string memory hand = getHandName(handId);
string memory rank = toString(getHandRank(handId));
string memory json = Base64.encode(
bytes(
string(
abi.encodePacked(
"{\"name\": \"", handName,
"\", \"description\": \"holdemheroes.com\",",
getAttributes(shape, hand, rank),
"\"image\": \"data:image/svg+xml;base64,",
Base64.encode(bytes(getHandAsSvg(handId))),
"\"}"
)
)
)
);
string memory output = string(abi.encodePacked("data:application/json;base64,", json));
return output;
}
/*
* PRIVATE FUNCTIONS
*/
/**
* @dev getAttributes will generate the attributes JSON for embedding into the NFT JSON
*
* @param shape string shape
* @param hand string hand
* @param rank string rank
* @return string attribute JSON
*/
function getAttributes(string memory shape, string memory hand, string memory rank) private pure returns (string memory) {
return string(
abi.encodePacked(
"\"attributes\": [{ \"trait_type\": \"Shape\", \"value\": \"", shape, "\"},",
"{ \"trait_type\": \"Hand\", \"value\": \"", hand, "\"},",
"{ \"trait_type\": \"Rank\", \"value\": \"", rank, "\"}],"
)
);
}
/**
* @dev toString converts a given uint256 to a string. Primarily used in SVG, JSON, string name,
* @dev and hash generation
*
* @param value uint256 number to convert
* @return string number as a string
*/
function toString(uint256 value) private pure returns (string memory) {
// Inspired by OraclizeAPI"s implementation - MIT license
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
uint256 _tmpN = value;
if (_tmpN == 0) {
return "0";
}
uint256 temp = _tmpN;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (_tmpN != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(_tmpN % 10)));
_tmpN /= 10;
}
return string(buffer);
}
/*
* MODIFIERS
*/
/**
* @dev validHandId ensures a given hand Id is valid
*
* @param handId uint16 id of hand
*/
modifier validHandId(uint16 handId) {
require(handId >= 0 && handId < 1326, "invalid handId");
require(REVEALED, "not revealed");
_;
}
}
contract HoldemHeroes is Ownable, HoldemHeroesBase, VORConsumerBase {
using PRBMathSD59x18 for int256;
// max number of NFTs allowed per address
uint256 public MAX_PER_ADDRESS_OR_TX;
// block number for when public sale opens
uint256 public SALE_START_BLOCK_NUM;
uint256 public basePostRevealPrice = 1 ether;
/// ---------------------------
/// ------- CRISP STATE -------
/// ---------------------------
///@notice block on which last purchase occurred
uint256 public lastPurchaseBlock;
///@notice block on which we start decaying price
uint256 public priceDecayStartBlock;
///@notice Starting EMS, before time decay. 59.18-decimal fixed-point
int256 public nextPurchaseStartingEMS;
///@notice Starting price for next purchase, before time decay. 59.18-decimal fixed-point
int256 public nextPurchaseStartingPrice;
/// ---------------------------
/// ---- CRISP PARAMETERS -----
/// ---------------------------
///@notice EMS target. 59.18-decimal fixed-point
int256 public immutable targetEMS;
///@notice controls decay of sales in EMS. 59.18-decimal fixed-point
int256 public immutable saleHalflife;
///@notice controls upward price movement. 59.18-decimal fixed-point
int256 public immutable priceSpeed;
///@notice controls price decay. 59.18-decimal fixed-point
int256 public immutable priceHalflife;
/*
* EVENTS
*/
event DistributionBegun(bytes32 requestId, address sender);
event DistributionResult(bytes32 requestId, uint256 randomness, uint256 startingIndex);
/**
* @dev constructor
* @dev initialises some basic variables.
* @dev CRISP implementation from https://github.com/FrankieIsLost/CRISP/blob/master/src/CRISP.sol
*
* @param _vorCoordinator address - address of VORCoordinator contract
* @param _xfund address - address of xFUND contract
* @param _playingCards address - address of Playing Cards contract
* @param _saleStartBlockNum uint256 - block number for when pre-reveal sale starts. Allows time for card/rank init
* @param _revealTimestamp uint256 - unix timestamp for when cards will be revealed and distributed
* @param _maxNfts address - max number of NFTs a single wallet address can mint
* @param _targetBlocksPerSale int256, e.g. 100
* @param _saleHalflife int256, e.g. 700
* @param _priceSpeed int256, e.g. 1
* @param _priceSpeedDenominator int256, e.g. 4. If _priceSpeed param is 1, final priceSpeed will be 0.25
* @param _priceHalflife int256, e.g. 100
* @param _startingPrice int256, e.g. 100
*/
constructor(
address _vorCoordinator,
address _xfund,
address _playingCards,
uint256 _saleStartBlockNum,
uint256 _revealTimestamp,
uint256 _maxNfts,
int256 _targetBlocksPerSale,
int256 _saleHalflife,
int256 _priceSpeed,
int256 _priceSpeedDenominator,
int256 _priceHalflife,
int256 _startingPrice
)
VORConsumerBase(_vorCoordinator, _xfund)
HoldemHeroesBase(_revealTimestamp, _playingCards)
{
SALE_START_BLOCK_NUM = (_saleStartBlockNum > block.number) ? _saleStartBlockNum : block.number;
MAX_PER_ADDRESS_OR_TX = _maxNfts;
// CRISP
lastPurchaseBlock = SALE_START_BLOCK_NUM;
priceDecayStartBlock = SALE_START_BLOCK_NUM;
// scale parameters - see https://github.com/FrankieIsLost/CRISP/blob/master/src/test/CRISP.t.sol
int256 targetBlocksPerSale = PRBMathSD59x18.fromInt(
_targetBlocksPerSale
);
saleHalflife = PRBMathSD59x18.fromInt(_saleHalflife);
priceSpeed = PRBMathSD59x18.fromInt(_priceSpeed).div(PRBMathSD59x18.fromInt(_priceSpeedDenominator));
priceHalflife = PRBMathSD59x18.fromInt(_priceHalflife);
//calculate target EMS from target blocks per sale
targetEMS = PRBMathSD59x18.fromInt(1).div(
PRBMathSD59x18.fromInt(1) -
PRBMathSD59x18.fromInt(2).pow(
-targetBlocksPerSale.div(saleHalflife)
)
);
nextPurchaseStartingEMS = targetEMS;
nextPurchaseStartingPrice = PRBMathSD59x18.fromInt(int256(_startingPrice));
}
/*
* ADMIN
*/
/**
* @dev setBasePostRevealPrice allows owner to adjust post-reveal price according to market
*
* @param newPrice uint256 new base price in wei
*/
function setBasePostRevealPrice(uint256 newPrice) external onlyOwner {
basePostRevealPrice = newPrice;
}
/*
* CRISP FUNCTIONS
*/
/**
* @dev getCurrentEMS gets current EMS based on block number.
* @dev implemented from https://github.com/FrankieIsLost/CRISP/blob/master/src/CRISP.sol
*
* @return result int256 59.18-decimal fixed-point
*/
function getCurrentEMS() public view returns (int256 result) {
int256 blockInterval = int256(block.number - lastPurchaseBlock);
blockInterval = blockInterval.fromInt();
int256 weightOnPrev = PRBMathSD59x18.fromInt(2).pow(
-blockInterval.div(saleHalflife)
);
result = nextPurchaseStartingEMS.mul(weightOnPrev);
}
/**
* @dev _getNftPrice get quote for purchasing in current block, decaying price as needed.
* @dev implemented from https://github.com/FrankieIsLost/CRISP/blob/master/src/CRISP.sol
*
* @return result int256 59.18-decimal fixed-point
*/
function _getNftPrice() internal view returns (int256 result) {
if (block.number <= priceDecayStartBlock) {
result = nextPurchaseStartingPrice;
}
//decay price if we are past decay start block
else {
int256 decayInterval = int256(block.number - priceDecayStartBlock)
.fromInt();
int256 decay = (-decayInterval).div(priceHalflife).exp();
result = nextPurchaseStartingPrice.mul(decay);
}
}
/**
* @dev getNftPrice get quote for purchasing in current block, decaying price as needed
* @dev implemented from https://github.com/FrankieIsLost/CRISP/blob/master/src/CRISP.sol
*
* @return result uint256 current price in wei
*/
function getNftPrice() public view returns (uint256 result) {
int256 pricePerNft = _getNftPrice();
result = uint256(pricePerNft.toInt());
}
/**
* @dev getPostRevealNftPrice get mint price for revealed tokens, based on the hand Rank
* @dev lower rank = better hand = higher price. e.g. AA = rank 1 = high price
* @dev Note - this can only be used in the event that there are unminted tokens
* @dev once the pre-reveal sale has ended.
*
* @return result uint256 price in wei
*/
function getPostRevealNftPrice(uint256 _tokenId) public view returns (uint256 result) {
uint256 rank = uint256(getHandRank(tokenIdToHandId(_tokenId)));
if(rank == 1) {
result = basePostRevealPrice;
} else {
uint256 m = 100 - ((rank * 100) / 169); // get % as int
m = (m < 10) ? 10 : m;
result = (basePostRevealPrice * m) / 100;
}
}
/**
* @dev getNextStartingPriceGet starting price for next purchase before time decay
* @dev implemented from https://github.com/FrankieIsLost/CRISP/blob/master/src/CRISP.sol
*
* @param lastPurchasePrice int256 last price as 59.18-decimal fixed-point
* @return result int256 59.18-decimal fixed-point
*/
function getNextStartingPrice(int256 lastPurchasePrice)
public
view
returns (int256 result)
{
int256 mismatchRatio = nextPurchaseStartingEMS.div(targetEMS);
if (mismatchRatio > PRBMathSD59x18.fromInt(1)) {
result = lastPurchasePrice.mul(
PRBMathSD59x18.fromInt(1) + mismatchRatio.mul(priceSpeed)
);
} else {
result = lastPurchasePrice;
}
}
/**
* @dev getPriceDecayStartBlock Find block in which time based price decay should start
* @dev implemented from https://github.com/FrankieIsLost/CRISP/blob/master/src/CRISP.sol
*
* @return result uint256 block number
*/
function getPriceDecayStartBlock() internal view returns (uint256 result) {
int256 mismatchRatio = nextPurchaseStartingEMS.div(targetEMS);
//if mismatch ratio above 1, decay should start in future
if (mismatchRatio > PRBMathSD59x18.fromInt(1)) {
uint256 decayInterval = uint256(
saleHalflife.mul(mismatchRatio.log2()).ceil().toInt()
);
result = block.number + decayInterval;
}
//else decay should start at the current block
else {
result = block.number;
}
}
/*
* MINT & DISTRIBUTION FUNCTIONS
*/
/**
* @dev mintNFTPreReveal is a public payable function which any user can call during the pre-reveal
* @dev sale phase. This allows a user to mint up to MAX_PER_ADDRESS_OR_TX tokens. Tokens are
* @dev minted sequentially. Mapping of token IDs on to hand IDs (according to provenance) is
* @dev executed during the reveal & distribution phase, via a call to VOR.
* @dev Correct ether value is expected to pay for tokens.
*
* @param _numberOfNfts uint256 number of NFTs to mint in this Tx
*/
function mintNFTPreReveal(uint256 _numberOfNfts) external payable {
uint256 numberOfNfts = (_numberOfNfts > 0) ? _numberOfNfts : 1;
require(block.number >= SALE_START_BLOCK_NUM, "not started");
require(totalSupply() < MAX_NFT_SUPPLY, "sold out");
require(block.timestamp < REVEAL_TIMESTAMP, "ended");
require(numberOfNfts <= MAX_PER_ADDRESS_OR_TX, "> max per tx");
require(balanceOf(msg.sender) + numberOfNfts <= MAX_PER_ADDRESS_OR_TX, "> mint limit");
require(totalSupply() + numberOfNfts <= MAX_NFT_SUPPLY, "exceeds supply");
int256 pricePerNft = _getNftPrice();
uint256 pricePerNftScaled = uint256(pricePerNft.toInt());
uint256 totalCost = pricePerNftScaled * numberOfNfts;
require(msg.value >= totalCost, "eth too low");
for (uint256 i = 0; i < numberOfNfts; i++) {
uint256 mintIndex = totalSupply();
_safeMint(msg.sender, mintIndex);
}
//update CRISP state
updateCrispState(pricePerNft, numberOfNfts);
}
/**
* @dev mintNFTPostReveal is a public payable function which any user can call AFTER the pre-reveal
* @dev sale phase. This allows a user to mint any available token ID that hasn't been sold yet.
* @dev This function cannot be executed until hands have been revealed and distributed.
* @dev Correct ether value is expected to pay for token.
*
* @param tokenId uint256 NFT Token ID to purchase
*/
function mintNFTPostReveal(uint256 tokenId) external payable {
uint256 price = getPostRevealNftPrice(tokenId);
require(msg.value >= price, "eth too low");
_safeMint(msg.sender, tokenId);
}
/**
* @dev beginDistribution is called to initiate distribution and makes a VOR request to generate
* @dev a random value. Can only be called after hands have been revealed according to provenance.
*
* @param _keyHash bytes32 key hash of the VOR Oracle that will handle the request
* @param _fee uint256 xFUND fee to pay the VOR Oracle
*/
function beginDistribution(bytes32 _keyHash, uint256 _fee) public onlyOwner canDistribute {
_increaseVorCoordinatorAllowance(_fee);
bytes32 requestId = requestRandomness(_keyHash, _fee, uint256(blockhash(block.number-10)));
emit DistributionBegun(requestId, msg.sender);
}
/**
* @dev fallbackDistribution is an emergency fallback function which can be called in the event
* @dev of the fulfillRandomness function failing. It can only be called by the contract owner
* @dev and should only be called if beginDistribution failed.
*/
function fallbackDistribution() public onlyOwner canDistribute {
uint256 sourceBlock = revealBlock;
// Just a sanity check (EVM only stores last 256 block hashes)
if (block.number - revealBlock > 255) {
sourceBlock = block.number-1;
}
uint256 randomness = uint(blockhash(sourceBlock));
checkAndSetStartIdx(randomness);
emit DistributionResult(0x0, 0, startingIndex);
}
/**
* @dev checkAndSetStartIdx is an internal function which will take the generated randomness
* @dev and calculate/set the startingIndex mapping value.
*
* @param _randomness uint256 generated randomness value from VOR etc.
*/
function checkAndSetStartIdx(uint256 _randomness) internal {
// calculate based on randomness
startingIndex = _randomness % (MAX_NFT_SUPPLY-1);
// Prevent default sequence
if (startingIndex == 0) {
startingIndex = 1;
}
if (startingIndex > 1325) {
startingIndex = 1325;
}
}
/**
* @dev fulfillRandomness is called by the VOR Oracle to fulfil the randomness request.
* @dev The randomness value sent is used to calculate the start array Idx onto which
* @dev hand IDs are mapped on to the NFT Token IDs.
* @dev Can only be called by the correct VOR Oracle, and only via the VORCoordinator contract.
*
* @param _requestId bytes32 ID of the request fulfilled by the Oracle
* @param _randomness uint256 the random number generated by the VOR Oracle
*/
function fulfillRandomness(bytes32 _requestId, uint256 _randomness) internal override {
require(startingIndex == 0, "already done");
checkAndSetStartIdx(_randomness);
emit DistributionResult(_requestId, _randomness, startingIndex);
}
/**
* @dev updateCrispState updates the CRISP parameters for dynamic pricing
*
* @param price int256 current price per NFT paid by user
* @param numMinted uint256 number minted in this Tx
*/
function updateCrispState(int256 price, uint256 numMinted) internal {
nextPurchaseStartingEMS = getCurrentEMS() + PRBMathSD59x18.fromInt(int256(numMinted));
nextPurchaseStartingPrice = getNextStartingPrice(price);
priceDecayStartBlock = getPriceDecayStartBlock();
lastPurchaseBlock = block.number;
}
/*
* MODIFIERS
*/
/**
* @dev canDistribute checks it's time to distribute
*/
modifier canDistribute() {
require(startingIndex == 0, "already done");
require(REVEALED, "not revealed");
_;
}
} | IPFS hash for provenance JSON - will be set when the last hand batch is revealed | string public PROVENANCE_IPFS;
| 13,810,291 | [
1,
2579,
4931,
1651,
364,
24185,
1796,
300,
903,
506,
444,
1347,
326,
1142,
948,
2581,
353,
283,
537,
18931,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
565,
533,
1071,
4629,
58,
1157,
4722,
67,
2579,
4931,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
]
|
./partial_match/4/0xeD38Cdc68a44B935C0fCFc72DB9967425224e64e/sources/FatToken.sol | FatToken with Governance. | contract FatToken is ERC20("FAT Token", "FAT"), Ownable {
uint256 private _totalLock;
address public privateSaleAddress;
address public teamSupplyAddress;
address public advisorsSupplyAddress;
address public airdropSupplyAddress;
uint256 public lockFromBlock;
uint256 public lockToBlock;
mapping(address => uint256) private _locks;
mapping(address => uint256) private _lastUnlockBlock;
event Lock(address indexed to, uint256 value);
constructor(
uint256 _lockFromBlock,
uint256 _lockToBlock,
address _privateSaleAddress,
address _teamSupplyAddress,
address _advisorsSupplyAddress,
address _airdropSupplyAddress
)
public {
lockFromBlock = _lockFromBlock;
lockToBlock = _lockToBlock;
privateSaleAddress = _privateSaleAddress;
teamSupplyAddress = _teamSupplyAddress;
advisorsSupplyAddress = _advisorsSupplyAddress;
airdropSupplyAddress = _airdropSupplyAddress;
}
function cap() public view returns (uint256) {
return _cap;
}
function teamSupply() public view returns (uint256) {
}
function crowdSaleSupply() public view returns (uint256) {
}
function privateSaleSupply() public view returns (uint256) {
}
function advisorsSupply() public view returns (uint256) {
}
function liquidityMiningSupply() public view returns (uint256) {
}
function proposalsSupply() public view returns (uint256) {
}
function airdropSupply() public view returns (uint256) {
}
function circulatingSupply() public view returns (uint256) {
return totalSupply().sub(_totalLock);
}
function totalLock() public view returns (uint256) {
return _totalLock;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded");
}
}
| 8,555,086 | [
1,
42,
270,
1345,
598,
611,
1643,
82,
1359,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
| [
1,
16351,
478,
270,
1345,
353,
4232,
39,
3462,
2932,
42,
789,
3155,
3113,
315,
42,
789,
6,
3631,
14223,
6914,
288,
203,
203,
565,
2254,
5034,
3238,
389,
4963,
2531,
31,
203,
203,
565,
1758,
1071,
3238,
30746,
1887,
31,
203,
565,
1758,
1071,
5927,
3088,
1283,
1887,
31,
203,
565,
1758,
1071,
1261,
3516,
1383,
3088,
1283,
1887,
31,
203,
565,
1758,
1071,
279,
6909,
1764,
3088,
1283,
1887,
31,
203,
203,
565,
2254,
5034,
1071,
2176,
1265,
1768,
31,
203,
565,
2254,
5034,
1071,
2176,
774,
1768,
31,
203,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
23581,
31,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
3238,
389,
2722,
7087,
1768,
31,
203,
203,
565,
871,
3488,
12,
2867,
8808,
358,
16,
2254,
5034,
460,
1769,
203,
203,
565,
3885,
12,
203,
3639,
2254,
5034,
389,
739,
1265,
1768,
16,
203,
3639,
2254,
5034,
389,
739,
774,
1768,
16,
203,
3639,
1758,
389,
1152,
30746,
1887,
16,
203,
3639,
1758,
389,
10035,
3088,
1283,
1887,
16,
203,
3639,
1758,
389,
361,
3516,
1383,
3088,
1283,
1887,
16,
203,
3639,
1758,
389,
1826,
7285,
3088,
1283,
1887,
203,
565,
262,
203,
203,
203,
565,
1071,
288,
203,
3639,
2176,
1265,
1768,
273,
389,
739,
1265,
1768,
31,
203,
3639,
2176,
774,
1768,
273,
389,
739,
774,
1768,
31,
203,
3639,
3238,
30746,
1887,
273,
225,
389,
1152,
30746,
1887,
31,
203,
3639,
5927,
3088,
1283,
1887,
273,
225,
389,
10035,
3088,
1283,
1887,
31,
203,
3639,
1261,
3516,
2
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.