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 |
---|---|---|---|---|---|---|
pragma solidity 0.5.11;
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;
}
}
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));
}
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 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");
}
}
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract Governable {
// Storage position of the owner and pendingOwner of the contract
bytes32
private constant governorPosition = 0x7bea13895fa79d2831e0a9e28edede30099005a50d652d8957cf8a607ee6ca4a;
//keccak256("OUSD.governor");
bytes32
private constant pendingGovernorPosition = 0x44c4d30b2eaad5130ad70c3ba6972730566f3e6359ab83e800d905c61b1c51db;
//keccak256("OUSD.pending.governor");
event PendingGovernorshipTransfer(
address indexed previousGovernor,
address indexed newGovernor
);
event GovernorshipTransferred(
address indexed previousGovernor,
address indexed newGovernor
);
/**
* @dev Initializes the contract setting the deployer as the initial Governor.
*/
constructor() internal {
_setGovernor(msg.sender);
emit GovernorshipTransferred(address(0), _governor());
}
/**
* @dev Returns the address of the current Governor.
*/
function governor() public view returns (address) {
return _governor();
}
function _governor() internal view returns (address governorOut) {
bytes32 position = governorPosition;
assembly {
governorOut := sload(position)
}
}
function _pendingGovernor()
internal
view
returns (address pendingGovernor)
{
bytes32 position = pendingGovernorPosition;
assembly {
pendingGovernor := sload(position)
}
}
/**
* @dev Throws if called by any account other than the Governor.
*/
modifier onlyGovernor() {
require(isGovernor(), "Caller is not the Governor");
_;
}
/**
* @dev Returns true if the caller is the current Governor.
*/
function isGovernor() public view returns (bool) {
return msg.sender == _governor();
}
function _setGovernor(address newGovernor) internal {
bytes32 position = governorPosition;
assembly {
sstore(position, newGovernor)
}
}
function _setPendingGovernor(address newGovernor) internal {
bytes32 position = pendingGovernorPosition;
assembly {
sstore(position, newGovernor)
}
}
/**
* @dev Transfers Governance of the contract to a new account (`newGovernor`).
* Can only be called by the current Governor. Must be claimed for this to complete
* @param _newGovernor Address of the new Governor
*/
function transferGovernance(address _newGovernor) external onlyGovernor {
_setPendingGovernor(_newGovernor);
emit PendingGovernorshipTransfer(_governor(), _newGovernor);
}
/**
* @dev Claim Governance of the contract to a new account (`newGovernor`).
* Can only be called by the new Governor.
*/
function claimGovernance() external {
require(
msg.sender == _pendingGovernor(),
"Only the pending Governor can complete the claim"
);
_changeGovernor(msg.sender);
}
/**
* @dev Change Governance of the contract to a new account (`newGovernor`).
* @param _newGovernor Address of the new Governor
*/
function _changeGovernor(address _newGovernor) internal {
require(_newGovernor != address(0), "New Governor is address(0)");
emit GovernorshipTransferred(_governor(), _newGovernor);
_setGovernor(_newGovernor);
}
}
contract InitializableGovernable is Governable, Initializable {
function _initialize(address _governor) internal {
_changeGovernor(_governor);
}
}
interface IStrategy {
/**
* @dev Deposit the given asset to Lending platform.
* @param _asset asset address
* @param _amount Amount to deposit
*/
function deposit(address _asset, uint256 _amount)
external
returns (uint256 amountDeposited);
/**
* @dev Withdraw given asset from Lending platform
*/
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external returns (uint256 amountWithdrawn);
/**
* @dev Returns the current balance of the given asset.
*/
function checkBalance(address _asset)
external
view
returns (uint256 balance);
/**
* @dev Returns bool indicating whether strategy supports asset.
*/
function supportsAsset(address _asset) external view returns (bool);
/**
* @dev Liquidate all assets in strategy and return them to Vault.
*/
function liquidate() external;
/**
* @dev Get the APR for the Strategy.
*/
function getAPR() external view returns (uint256);
/**
* @dev Collect reward tokens from the Strategy.
*/
function collectRewardToken() external;
}
interface ICERC20 {
/**
* @notice The mint function transfers an asset into the protocol, which begins accumulating
* interest based on the current Supply Rate for the asset. The user receives a quantity of
* cTokens equal to the underlying tokens supplied, divided by the current Exchange Rate.
* @param mintAmount The amount of the asset to be supplied, in units of the underlying asset.
* @return 0 on success, otherwise an Error codes
*/
function mint(uint256 mintAmount) external returns (uint256);
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise an error code.
*/
function redeem(uint256 redeemTokens) external returns (uint256);
/**
* @notice The redeem underlying function converts cTokens into a specified quantity of the underlying
* asset, and returns them to the user. The amount of cTokens redeemed is equal to the quantity of
* underlying tokens received, divided by the current Exchange Rate. The amount redeemed must be less
* than the user's Account Liquidity and the market's available liquidity.
* @param redeemAmount The amount of underlying to be redeemed.
* @return 0 on success, otherwise an error code.
*/
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
/**
* @notice The user's underlying balance, representing their assets in the protocol, is equal to
* the user's cToken balance multiplied by the Exchange Rate.
* @param owner The account to get the underlying balance of.
* @return The amount of underlying currently owned by the account.
*/
function balanceOfUnderlying(address owner) external returns (uint256);
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() external view returns (uint256);
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @notice Get the supply rate per block for supplying the token to Compound.
*/
function supplyRatePerBlock() external view returns (uint256);
}
contract InitializableAbstractStrategy is IStrategy, Initializable, Governable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
event PTokenAdded(address indexed _asset, address _pToken);
event Deposit(address indexed _asset, address _pToken, uint256 _amount);
event Withdrawal(address indexed _asset, address _pToken, uint256 _amount);
// Core address for the given platform
address public platformAddress;
address public vaultAddress;
// asset => pToken (Platform Specific Token Address)
mapping(address => address) public assetToPToken;
// Full list of all assets supported here
address[] internal assetsMapped;
// Reward token address
address public rewardTokenAddress;
/**
* @dev Internal initialize function, to set up initial internal state
* @param _platformAddress jGeneric platform address
* @param _vaultAddress Address of the Vault
* @param _rewardTokenAddress Address of reward token for platform
* @param _assets Addresses of initial supported assets
* @param _pTokens Platform Token corresponding addresses
*/
function initialize(
address _platformAddress,
address _vaultAddress,
address _rewardTokenAddress,
address[] calldata _assets,
address[] calldata _pTokens
) external onlyGovernor initializer {
InitializableAbstractStrategy._initialize(
_platformAddress,
_vaultAddress,
_rewardTokenAddress,
_assets,
_pTokens
);
}
function _initialize(
address _platformAddress,
address _vaultAddress,
address _rewardTokenAddress,
address[] memory _assets,
address[] memory _pTokens
) internal {
platformAddress = _platformAddress;
vaultAddress = _vaultAddress;
rewardTokenAddress = _rewardTokenAddress;
uint256 assetCount = _assets.length;
require(assetCount == _pTokens.length, "Invalid input arrays");
for (uint256 i = 0; i < assetCount; i++) {
_setPTokenAddress(_assets[i], _pTokens[i]);
}
}
/**
* @dev Verifies that the caller is the Vault.
*/
modifier onlyVault() {
require(msg.sender == vaultAddress, "Caller is not the Vault");
_;
}
/**
* @dev Verifies that the caller is the Vault or Governor.
*/
modifier onlyVaultOrGovernor() {
require(
msg.sender == vaultAddress || msg.sender == governor(),
"Caller is not the Vault or Governor"
);
_;
}
/**
* @dev Set the reward token address.
* @param _rewardTokenAddress Address of the reward token
*/
function setRewardTokenAddress(address _rewardTokenAddress)
external
onlyGovernor
{
rewardTokenAddress = _rewardTokenAddress;
}
/**
* @dev Provide support for asset by passing its pToken address.
* This method can only be called by the system Governor
* @param _asset Address for the asset
* @param _pToken Address for the corresponding platform token
*/
function setPTokenAddress(address _asset, address _pToken)
external
onlyGovernor
{
_setPTokenAddress(_asset, _pToken);
}
/**
* @dev Provide support for asset by passing its pToken address.
* Add to internal mappings and execute the platform specific,
* abstract method `_abstractSetPToken`
* @param _asset Address for the asset
* @param _pToken Address for the corresponding platform token
*/
function _setPTokenAddress(address _asset, address _pToken) internal {
require(assetToPToken[_asset] == address(0), "pToken already set");
require(
_asset != address(0) && _pToken != address(0),
"Invalid addresses"
);
assetToPToken[_asset] = _pToken;
assetsMapped.push(_asset);
emit PTokenAdded(_asset, _pToken);
_abstractSetPToken(_asset, _pToken);
}
/**
* @dev Transfer token to governor. Intended for recovering tokens stuck in
* strategy contracts, i.e. mistaken sends.
* @param _asset Address for the asset
* @param _amount Amount of the asset to transfer
*/
function transferToken(address _asset, uint256 _amount)
public
onlyGovernor
{
IERC20(_asset).transfer(governor(), _amount);
}
/***************************************
Abstract
****************************************/
function _abstractSetPToken(address _asset, address _pToken) internal;
function safeApproveAllTokens() external;
/**
* @dev Deposit a amount of asset into the platform
* @param _asset Address for the asset
* @param _amount Units of asset to deposit
* @return amountDeposited Quantity of asset that was deposited
*/
function deposit(address _asset, uint256 _amount)
external
returns (uint256 amountDeposited);
/**
* @dev Withdraw an amount of asset from the platform.
* @param _recipient Address to which the asset should be sent
* @param _asset Address of the asset
* @param _amount Units of asset to withdraw
* @return amountWithdrawn Quantity of asset that was withdrawn
*/
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external returns (uint256 amountWithdrawn);
/**
* @dev Liquidate entire contents of strategy sending assets to Vault.
*/
function liquidate() external;
/**
* @dev Get the total asset value held in the platform.
* This includes any interest that was generated since depositing.
* @param _asset Address of the asset
* @return balance Total value of the asset in the platform
*/
function checkBalance(address _asset)
external
view
returns (uint256 balance);
/**
* @dev Check if an asset is supported.
* @param _asset Address of the asset
* @return bool Whether asset is supported
*/
function supportsAsset(address _asset) external view returns (bool);
/**
* @dev Get the weighted APR for all assets.
* @return uint256 APR for Strategy
*/
function getAPR() external view returns (uint256);
/**
* @dev Get the APR for a single asset.
* @param _asset Address of the asset
* @return uint256 APR for single asset in Strategy
*/
function getAssetAPR(address _asset) external view returns (uint256);
}
contract CompoundStrategy is InitializableAbstractStrategy {
event RewardTokenCollected(address recipient, uint256 amount);
event SkippedWithdrawal(address asset, uint256 amount);
/**
* @dev Collect accumulated reward token (COMP) and send to Vault.
*/
function collectRewardToken() external onlyVault {
IERC20 compToken = IERC20(rewardTokenAddress);
uint256 balance = compToken.balanceOf(address(this));
require(
compToken.transfer(vaultAddress, balance),
"Reward token transfer failed"
);
emit RewardTokenCollected(vaultAddress, balance);
}
/**
* @dev Deposit asset into Compound
* @param _asset Address of asset to deposit
* @param _amount Amount of asset to deposit
* @return amountDeposited Amount of asset that was deposited
*/
function deposit(address _asset, uint256 _amount)
external
onlyVault
returns (uint256 amountDeposited)
{
require(_amount > 0, "Must deposit something");
ICERC20 cToken = _getCTokenFor(_asset);
require(cToken.mint(_amount) == 0, "cToken mint failed");
amountDeposited = _amount;
emit Deposit(_asset, address(cToken), amountDeposited);
}
/**
* @dev Withdraw asset from Compound
* @param _recipient Address to receive withdrawn asset
* @param _asset Address of asset to withdraw
* @param _amount Amount of asset to withdraw
* @return amountWithdrawn Amount of asset that was withdrawn
*/
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external onlyVault returns (uint256 amountWithdrawn) {
require(_amount > 0, "Must withdraw something");
require(_recipient != address(0), "Must specify recipient");
ICERC20 cToken = _getCTokenFor(_asset);
// If redeeming 0 cTokens, just skip, else COMP will revert
uint256 cTokensToRedeem = _convertUnderlyingToCToken(cToken, _amount);
if (cTokensToRedeem == 0) {
emit SkippedWithdrawal(_asset, _amount);
return 0;
}
amountWithdrawn = _amount;
require(cToken.redeemUnderlying(_amount) == 0, "Redeem failed");
IERC20(_asset).safeTransfer(_recipient, amountWithdrawn);
emit Withdrawal(_asset, address(cToken), amountWithdrawn);
}
/**
* @dev Remove all assets from platform and send them to Vault contract.
*/
function liquidate() external onlyVaultOrGovernor {
for (uint256 i = 0; i < assetsMapped.length; i++) {
// Redeem entire balance of cToken
ICERC20 cToken = _getCTokenFor(assetsMapped[i]);
if (cToken.balanceOf(address(this)) > 0) {
cToken.redeem(cToken.balanceOf(address(this)));
// Transfer entire balance to Vault
IERC20 asset = IERC20(assetsMapped[i]);
asset.safeTransfer(
vaultAddress,
asset.balanceOf(address(this))
);
}
}
}
/**
* @dev Get the total asset value held in the platform
* This includes any interest that was generated since depositing
* Compound exchange rate between the cToken and asset gradually increases,
* causing the cToken to be worth more corresponding asset.
* @param _asset Address of the asset
* @return balance Total value of the asset in the platform
*/
function checkBalance(address _asset)
external
view
returns (uint256 balance)
{
// Balance is always with token cToken decimals
ICERC20 cToken = _getCTokenFor(_asset);
balance = _checkBalance(cToken);
}
/**
* @dev Get the total asset value held in the platform
* underlying = (cTokenAmt * exchangeRate) / 1e18
* @param _cToken cToken for which to check balance
* @return balance Total value of the asset in the platform
*/
function _checkBalance(ICERC20 _cToken)
internal
view
returns (uint256 balance)
{
uint256 cTokenBalance = _cToken.balanceOf(address(this));
uint256 exchangeRate = _cToken.exchangeRateStored();
// e.g. 50e8*205316390724364402565641705 / 1e18 = 1.0265..e18
balance = cTokenBalance.mul(exchangeRate).div(1e18);
}
/**
* @dev Retuns bool indicating whether asset is supported by strategy
* @param _asset Address of the asset
*/
function supportsAsset(address _asset) external view returns (bool) {
return assetToPToken[_asset] != address(0);
}
/**
* @dev Approve the spending of all assets by their corresponding cToken,
* if for some reason is it necessary. Only callable through Governance.
*/
function safeApproveAllTokens() external {
uint256 assetCount = assetsMapped.length;
for (uint256 i = 0; i < assetCount; i++) {
address asset = assetsMapped[i];
address cToken = assetToPToken[asset];
// Safe approval
IERC20(asset).safeApprove(cToken, 0);
IERC20(asset).safeApprove(cToken, uint256(-1));
}
}
/**
* @dev Get the weighted APR for all assets in strategy.
* @return APR in 1e18
*/
function getAPR() external view returns (uint256) {
uint256 totalValue = 0;
for (uint256 i = 0; i < assetsMapped.length; i++) {
ICERC20 cToken = _getCTokenFor(assetsMapped[i]);
totalValue += _checkBalance(cToken);
}
if (totalValue == 0) return 0;
uint256 totalAPR = 0;
for (uint256 i = 0; i < assetsMapped.length; i++) {
ICERC20 cToken = _getCTokenFor(assetsMapped[i]);
totalAPR += _checkBalance(cToken)
.mul(_getAssetAPR(assetsMapped[i]))
.div(totalValue);
}
return totalAPR;
}
/**
* @dev Get the APR for a single asset.
* @param _asset Address of the asset
* @return APR in 1e18
*/
function getAssetAPR(address _asset) external view returns (uint256) {
return _getAssetAPR(_asset);
}
/**
* @dev Internal method to get the APR for a single asset.
* @param _asset Address of the asset
* @return APR in 1e18
*/
function _getAssetAPR(address _asset) internal view returns (uint256) {
ICERC20 cToken = _getCTokenFor(_asset);
// Extrapolate to a year assuming 6,500 blocks per day times 365.
return cToken.supplyRatePerBlock().mul(2372500);
}
/**
* @dev Internal method to respond to the addition of new asset / cTokens
* We need to approve the cToken and give it permission to spend the asset
* @param _asset Address of the asset to approve
* @param _cToken This cToken has the approval approval
*/
function _abstractSetPToken(address _asset, address _cToken) internal {
// Safe approval
IERC20(_asset).safeApprove(_cToken, 0);
IERC20(_asset).safeApprove(_cToken, uint256(-1));
}
/**
* @dev Get the cToken wrapped in the ICERC20 interface for this asset.
* Fails if the pToken doesn't exist in our mappings.
* @param _asset Address of the asset
* @return Corresponding cToken to this asset
*/
function _getCTokenFor(address _asset) internal view returns (ICERC20) {
address cToken = assetToPToken[_asset];
require(cToken != address(0), "cToken does not exist");
return ICERC20(cToken);
}
/**
* @dev Converts an underlying amount into cToken amount
* cTokenAmt = (underlying * 1e18) / exchangeRate
* @param _cToken cToken for which to change
* @param _underlying Amount of underlying to convert
* @return amount Equivalent amount of cTokens
*/
function _convertUnderlyingToCToken(ICERC20 _cToken, uint256 _underlying)
internal
view
returns (uint256 amount)
{
uint256 exchangeRate = _cToken.exchangeRateStored();
// e.g. 1e18*1e18 / 205316390724364402565641705 = 50e8
// e.g. 1e8*1e18 / 205316390724364402565641705 = 0.45 or 0
amount = _underlying.mul(1e18).div(exchangeRate);
}
}
|
* @dev Deposit a amount of asset into the platform @param _asset Address for the asset @param _amount Units of asset to deposit @return amountDeposited Quantity of asset that was deposited/* @dev Withdraw an amount of asset from the platform. @param _recipient Address to which the asset should be sent @param _asset Address of the asset @param _amount Units of asset to withdraw @return amountWithdrawn Quantity of asset that was withdrawn/* @dev Liquidate entire contents of strategy sending assets to Vault./* @dev Get the total asset value held in the platform. This includes any interest that was generated since depositing. @param _asset Address of the asset @return balance Total value of the asset in the platform/* @dev Check if an asset is supported. @param _asset Address of the asset @return bool Whether asset is supported/* @dev Get the weighted APR for all assets. @return uint256 APR for Strategy/* @dev Get the APR for a single asset. @param _asset Address of the asset @return uint256 APR for single asset in Strategy/
|
contract CompoundStrategy is InitializableAbstractStrategy {
event RewardTokenCollected(address recipient, uint256 amount);
event SkippedWithdrawal(address asset, uint256 amount);
function _abstractSetPToken(address _asset, address _pToken) internal;
function safeApproveAllTokens() external;
function deposit(address _asset, uint256 _amount)
external
returns (uint256 amountDeposited);
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external returns (uint256 amountWithdrawn);
function liquidate() external;
function checkBalance(address _asset)
external
view
returns (uint256 balance);
function supportsAsset(address _asset) external view returns (bool);
function getAPR() external view returns (uint256);
function getAssetAPR(address _asset) external view returns (uint256);
}
function collectRewardToken() external onlyVault {
IERC20 compToken = IERC20(rewardTokenAddress);
uint256 balance = compToken.balanceOf(address(this));
require(
compToken.transfer(vaultAddress, balance),
"Reward token transfer failed"
);
emit RewardTokenCollected(vaultAddress, balance);
}
function deposit(address _asset, uint256 _amount)
external
onlyVault
returns (uint256 amountDeposited)
{
require(_amount > 0, "Must deposit something");
ICERC20 cToken = _getCTokenFor(_asset);
require(cToken.mint(_amount) == 0, "cToken mint failed");
amountDeposited = _amount;
emit Deposit(_asset, address(cToken), amountDeposited);
}
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external onlyVault returns (uint256 amountWithdrawn) {
require(_amount > 0, "Must withdraw something");
require(_recipient != address(0), "Must specify recipient");
ICERC20 cToken = _getCTokenFor(_asset);
uint256 cTokensToRedeem = _convertUnderlyingToCToken(cToken, _amount);
if (cTokensToRedeem == 0) {
emit SkippedWithdrawal(_asset, _amount);
return 0;
}
amountWithdrawn = _amount;
require(cToken.redeemUnderlying(_amount) == 0, "Redeem failed");
IERC20(_asset).safeTransfer(_recipient, amountWithdrawn);
emit Withdrawal(_asset, address(cToken), amountWithdrawn);
}
function withdraw(
address _recipient,
address _asset,
uint256 _amount
) external onlyVault returns (uint256 amountWithdrawn) {
require(_amount > 0, "Must withdraw something");
require(_recipient != address(0), "Must specify recipient");
ICERC20 cToken = _getCTokenFor(_asset);
uint256 cTokensToRedeem = _convertUnderlyingToCToken(cToken, _amount);
if (cTokensToRedeem == 0) {
emit SkippedWithdrawal(_asset, _amount);
return 0;
}
amountWithdrawn = _amount;
require(cToken.redeemUnderlying(_amount) == 0, "Redeem failed");
IERC20(_asset).safeTransfer(_recipient, amountWithdrawn);
emit Withdrawal(_asset, address(cToken), amountWithdrawn);
}
function liquidate() external onlyVaultOrGovernor {
for (uint256 i = 0; i < assetsMapped.length; i++) {
ICERC20 cToken = _getCTokenFor(assetsMapped[i]);
if (cToken.balanceOf(address(this)) > 0) {
cToken.redeem(cToken.balanceOf(address(this)));
IERC20 asset = IERC20(assetsMapped[i]);
asset.safeTransfer(
vaultAddress,
asset.balanceOf(address(this))
);
}
}
}
function liquidate() external onlyVaultOrGovernor {
for (uint256 i = 0; i < assetsMapped.length; i++) {
ICERC20 cToken = _getCTokenFor(assetsMapped[i]);
if (cToken.balanceOf(address(this)) > 0) {
cToken.redeem(cToken.balanceOf(address(this)));
IERC20 asset = IERC20(assetsMapped[i]);
asset.safeTransfer(
vaultAddress,
asset.balanceOf(address(this))
);
}
}
}
function liquidate() external onlyVaultOrGovernor {
for (uint256 i = 0; i < assetsMapped.length; i++) {
ICERC20 cToken = _getCTokenFor(assetsMapped[i]);
if (cToken.balanceOf(address(this)) > 0) {
cToken.redeem(cToken.balanceOf(address(this)));
IERC20 asset = IERC20(assetsMapped[i]);
asset.safeTransfer(
vaultAddress,
asset.balanceOf(address(this))
);
}
}
}
function checkBalance(address _asset)
external
view
returns (uint256 balance)
{
ICERC20 cToken = _getCTokenFor(_asset);
balance = _checkBalance(cToken);
}
function _checkBalance(ICERC20 _cToken)
internal
view
returns (uint256 balance)
{
uint256 cTokenBalance = _cToken.balanceOf(address(this));
uint256 exchangeRate = _cToken.exchangeRateStored();
balance = cTokenBalance.mul(exchangeRate).div(1e18);
}
function supportsAsset(address _asset) external view returns (bool) {
return assetToPToken[_asset] != address(0);
}
function safeApproveAllTokens() external {
uint256 assetCount = assetsMapped.length;
for (uint256 i = 0; i < assetCount; i++) {
address asset = assetsMapped[i];
address cToken = assetToPToken[asset];
IERC20(asset).safeApprove(cToken, 0);
IERC20(asset).safeApprove(cToken, uint256(-1));
}
}
function safeApproveAllTokens() external {
uint256 assetCount = assetsMapped.length;
for (uint256 i = 0; i < assetCount; i++) {
address asset = assetsMapped[i];
address cToken = assetToPToken[asset];
IERC20(asset).safeApprove(cToken, 0);
IERC20(asset).safeApprove(cToken, uint256(-1));
}
}
function getAPR() external view returns (uint256) {
uint256 totalValue = 0;
for (uint256 i = 0; i < assetsMapped.length; i++) {
ICERC20 cToken = _getCTokenFor(assetsMapped[i]);
totalValue += _checkBalance(cToken);
}
if (totalValue == 0) return 0;
uint256 totalAPR = 0;
for (uint256 i = 0; i < assetsMapped.length; i++) {
ICERC20 cToken = _getCTokenFor(assetsMapped[i]);
totalAPR += _checkBalance(cToken)
.mul(_getAssetAPR(assetsMapped[i]))
.div(totalValue);
}
return totalAPR;
}
function getAPR() external view returns (uint256) {
uint256 totalValue = 0;
for (uint256 i = 0; i < assetsMapped.length; i++) {
ICERC20 cToken = _getCTokenFor(assetsMapped[i]);
totalValue += _checkBalance(cToken);
}
if (totalValue == 0) return 0;
uint256 totalAPR = 0;
for (uint256 i = 0; i < assetsMapped.length; i++) {
ICERC20 cToken = _getCTokenFor(assetsMapped[i]);
totalAPR += _checkBalance(cToken)
.mul(_getAssetAPR(assetsMapped[i]))
.div(totalValue);
}
return totalAPR;
}
function getAPR() external view returns (uint256) {
uint256 totalValue = 0;
for (uint256 i = 0; i < assetsMapped.length; i++) {
ICERC20 cToken = _getCTokenFor(assetsMapped[i]);
totalValue += _checkBalance(cToken);
}
if (totalValue == 0) return 0;
uint256 totalAPR = 0;
for (uint256 i = 0; i < assetsMapped.length; i++) {
ICERC20 cToken = _getCTokenFor(assetsMapped[i]);
totalAPR += _checkBalance(cToken)
.mul(_getAssetAPR(assetsMapped[i]))
.div(totalValue);
}
return totalAPR;
}
function getAssetAPR(address _asset) external view returns (uint256) {
return _getAssetAPR(_asset);
}
function _getAssetAPR(address _asset) internal view returns (uint256) {
ICERC20 cToken = _getCTokenFor(_asset);
return cToken.supplyRatePerBlock().mul(2372500);
}
function _abstractSetPToken(address _asset, address _cToken) internal {
IERC20(_asset).safeApprove(_cToken, 0);
IERC20(_asset).safeApprove(_cToken, uint256(-1));
}
function _getCTokenFor(address _asset) internal view returns (ICERC20) {
address cToken = assetToPToken[_asset];
require(cToken != address(0), "cToken does not exist");
return ICERC20(cToken);
}
function _convertUnderlyingToCToken(ICERC20 _cToken, uint256 _underlying)
internal
view
returns (uint256 amount)
{
uint256 exchangeRate = _cToken.exchangeRateStored();
amount = _underlying.mul(1e18).div(exchangeRate);
}
}
| 2,121,727 |
[
1,
758,
1724,
279,
3844,
434,
3310,
1368,
326,
4072,
225,
389,
9406,
9079,
5267,
364,
326,
3310,
225,
389,
8949,
2868,
27845,
434,
3310,
358,
443,
1724,
327,
3844,
758,
1724,
329,
377,
18189,
434,
3310,
716,
1703,
443,
1724,
329,
19,
225,
3423,
9446,
392,
3844,
434,
3310,
628,
326,
4072,
18,
225,
389,
20367,
540,
5267,
358,
1492,
326,
3310,
1410,
506,
3271,
225,
389,
9406,
2398,
5267,
434,
326,
3310,
225,
389,
8949,
5411,
27845,
434,
3310,
358,
598,
9446,
327,
3844,
1190,
9446,
82,
282,
18189,
434,
3310,
716,
1703,
598,
9446,
82,
19,
225,
511,
18988,
350,
340,
7278,
2939,
434,
6252,
5431,
7176,
358,
17329,
18,
19,
225,
968,
326,
2078,
3310,
460,
15770,
316,
326,
4072,
18,
1377,
1220,
6104,
1281,
16513,
716,
1703,
4374,
3241,
443,
1724,
310,
18,
225,
389,
9406,
1377,
5267,
434,
326,
3310,
327,
11013,
565,
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,
16351,
21327,
4525,
353,
10188,
6934,
7469,
4525,
288,
203,
565,
871,
534,
359,
1060,
1345,
10808,
329,
12,
2867,
8027,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
6611,
1845,
1190,
9446,
287,
12,
2867,
3310,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
445,
389,
17801,
694,
52,
1345,
12,
2867,
389,
9406,
16,
1758,
389,
84,
1345,
13,
2713,
31,
203,
203,
565,
445,
4183,
12053,
537,
1595,
5157,
1435,
3903,
31,
203,
203,
565,
445,
443,
1724,
12,
2867,
389,
9406,
16,
2254,
5034,
389,
8949,
13,
203,
3639,
3903,
203,
3639,
1135,
261,
11890,
5034,
3844,
758,
1724,
329,
1769,
203,
203,
565,
445,
598,
9446,
12,
203,
3639,
1758,
389,
20367,
16,
203,
3639,
1758,
389,
9406,
16,
203,
3639,
2254,
5034,
389,
8949,
203,
565,
262,
3903,
1135,
261,
11890,
5034,
3844,
1190,
9446,
82,
1769,
203,
203,
565,
445,
4501,
26595,
340,
1435,
3903,
31,
203,
203,
565,
445,
866,
13937,
12,
2867,
389,
9406,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
11890,
5034,
11013,
1769,
203,
203,
565,
445,
6146,
6672,
12,
2867,
389,
9406,
13,
3903,
1476,
1135,
261,
6430,
1769,
203,
203,
565,
445,
336,
2203,
54,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
203,
565,
445,
24689,
2203,
54,
12,
2867,
389,
9406,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
97,
203,
203,
565,
445,
3274,
17631,
1060,
1345,
1435,
3903,
1338,
12003,
288,
203,
3639,
467,
654,
39,
3462,
1161,
1345,
273,
467,
2
] |
./partial_match/3/0x16a3F868483aF281b8a91D018c28F8156ef77258/sources/Token.sol
|
---------------------------------------------------------------------------- ERC20 Token, with the addition of symbol, name and decimals and assisted token transfers ----------------------------------------------------------------------------
|
contract Token is IERC20, Owned {
using SafeMath for uint256;
string public symbol = "EMAX";
string public name = "ETHmax";
uint256 public decimals = 18;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
mapping (address => bool) minters;
modifier onlyMinter{
require(minters[msg.sender], "UnAuthorized");
_;
}
event MinterAdded(address _minterAdded);
event MinterRemoved(address _minterRemoved);
event TokensMinted(address _to, uint256 _tokens);
constructor() public {
owner = 0xcdf99D4d5ca2E5C523ED1D3a68c563dBfB323Ed7;
_mint(owner, _totalSupply);
}
function AddMinter(address _minter) external onlyOwner {
require(_minter != address(0),"invalid address");
minters[_minter] = true;
emit MinterAdded(_minter);
}
function RemoveMinter(address _minter) external onlyOwner{
require(_minter != address(0),"invalid address");
minters[_minter] = false;
emit MinterRemoved(_minter);
}
function Mint(address to, uint256 tokens) external onlyMinter {
_mint(to, tokens);
_totalSupply = _totalSupply.add(tokens);
emit TokensMinted(to, tokens);
}
function _mint(address _to, uint256 _tokens) internal {
balances[address(_to)] = balances[address(_to)].add(_tokens);
emit Transfer(address(0), address(_to), _tokens);
}
function totalSupply() external override view returns (uint256){
return _totalSupply;
}
function balanceOf(address tokenOwner) external override view returns (uint256 balance) {
return balances[tokenOwner];
}
function approve(address spender, uint256 tokens) external override returns (bool success){
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender,spender,tokens);
return true;
}
function allowance(address tokenOwner, address spender) external override view returns (uint256 remaining) {
return allowed[tokenOwner][spender];
}
function transfer(address to, uint256 tokens) public override returns (bool success) {
require(address(to) != address(0));
require(balances[msg.sender] >= tokens );
require(balances[to] + tokens >= balances[to]);
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
function transferFrom(address from, address to, uint256 tokens) external override returns (bool success){
require(balances[from] >= tokens, "Insufficient balance");
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(from, to, tokens);
return true;
}
}
| 5,339,550 |
[
1,
5802,
7620,
4232,
39,
3462,
3155,
16,
598,
326,
2719,
434,
3273,
16,
508,
471,
15105,
471,
1551,
25444,
1147,
29375,
8879,
13849,
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,
16351,
3155,
353,
467,
654,
39,
3462,
16,
14223,
11748,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
27699,
565,
533,
1071,
3273,
273,
315,
3375,
2501,
14432,
203,
565,
533,
1071,
225,
508,
273,
315,
1584,
44,
1896,
14432,
203,
565,
2254,
5034,
1071,
15105,
273,
6549,
31,
203,
377,
203,
565,
2874,
12,
2867,
516,
2254,
5034,
13,
324,
26488,
31,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
2935,
31,
203,
27699,
565,
2874,
261,
2867,
516,
1426,
13,
1131,
5432,
31,
203,
203,
203,
565,
9606,
1338,
49,
2761,
95,
203,
3639,
2583,
12,
1154,
5432,
63,
3576,
18,
15330,
6487,
315,
984,
15341,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
565,
871,
490,
2761,
8602,
12,
2867,
389,
1154,
387,
8602,
1769,
203,
565,
871,
490,
2761,
10026,
12,
2867,
389,
1154,
387,
10026,
1769,
203,
565,
871,
13899,
49,
474,
329,
12,
2867,
389,
869,
16,
2254,
5034,
389,
7860,
1769,
203,
377,
203,
377,
203,
565,
3885,
1435,
1071,
288,
203,
3639,
3410,
273,
374,
6511,
2180,
2733,
40,
24,
72,
25,
5353,
22,
41,
25,
39,
25,
4366,
2056,
21,
40,
23,
69,
9470,
71,
4313,
23,
72,
38,
74,
38,
1578,
23,
2671,
27,
31,
203,
3639,
389,
81,
474,
12,
8443,
16,
389,
4963,
3088,
1283,
1769,
203,
540,
203,
565,
289,
203,
565,
445,
1436,
49,
2761,
12,
2867,
389,
1154,
387,
13,
3903,
1338,
5541,
288,
203,
3639,
2583,
24899,
2
] |
./full_match/1/0x59D55D53a715b3B4581c52098BCb4075C2941DBa/sources/contracts/protocol/modules/v1/AuctionRebalanceModuleV1.sol
|
* @notice Calculates the quantity of quote asset involved in the bid. @param isSellAuction Is the auction a sell type. @param _componentQuantity The amount of component in the bid. @param _componentPrice The price of the component. @return The quantity of quote asset in the bid./
|
function _calculateQuoteAssetQuantity(bool isSellAuction, uint256 _componentQuantity, uint256 _componentPrice) private pure returns (uint256) {
return isSellAuction ? _componentQuantity.preciseMulCeil(_componentPrice) : _componentQuantity.preciseMul(_componentPrice);
}
| 3,851,273 |
[
1,
10587,
326,
10457,
434,
3862,
3310,
24589,
316,
326,
9949,
18,
225,
11604,
1165,
37,
4062,
3639,
2585,
326,
279,
4062,
279,
357,
80,
618,
18,
225,
389,
4652,
12035,
282,
1021,
3844,
434,
1794,
316,
326,
9949,
18,
225,
389,
4652,
5147,
1377,
1021,
6205,
434,
326,
1794,
18,
327,
5397,
1021,
10457,
434,
3862,
3310,
316,
326,
9949,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
389,
11162,
10257,
6672,
12035,
12,
6430,
11604,
1165,
37,
4062,
16,
2254,
5034,
389,
4652,
12035,
16,
2254,
5034,
389,
4652,
5147,
13,
3238,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
11604,
1165,
37,
4062,
692,
389,
4652,
12035,
18,
4036,
784,
27860,
39,
73,
330,
24899,
4652,
5147,
13,
294,
389,
4652,
12035,
18,
4036,
784,
27860,
24899,
4652,
5147,
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
] |
./full_match/1/0xC441425E3e8F8b94EafA76f6bF90d97597ccEE2E/sources/contracts/sbBTCPool.sol
|
ackFunds checks the difference between the last known balance of `token` and the current one if it goes up, the multiplier is re-calculated if it goes down, it only updates the known balance
|
function ackFunds() public {
uint256 balanceNow = rewardToken.balanceOf(address(this));
if (balanceNow == 0 || balanceNow <= balanceBefore) {
balanceBefore = balanceNow;
return;
}
if (totalNodeStaked == 0) {
return;
}
uint256 diff = balanceNow.sub(balanceBefore);
uint256 multiplier = currentMultiplier.add(
diff.mul(divisor).div(totalNodeStaked)
);
balanceBefore = balanceNow;
currentMultiplier = multiplier;
}
| 3,198,356 |
[
1,
484,
42,
19156,
4271,
326,
7114,
3086,
326,
1142,
4846,
11013,
434,
1375,
2316,
68,
471,
326,
783,
1245,
309,
518,
13998,
731,
16,
326,
15027,
353,
283,
17,
22113,
309,
518,
13998,
2588,
16,
518,
1338,
4533,
326,
4846,
11013,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
8479,
42,
19156,
1435,
1071,
288,
203,
3639,
2254,
5034,
11013,
8674,
273,
19890,
1345,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
309,
261,
12296,
8674,
422,
374,
747,
11013,
8674,
1648,
11013,
4649,
13,
288,
203,
5411,
11013,
4649,
273,
11013,
8674,
31,
203,
5411,
327,
31,
203,
3639,
289,
203,
3639,
309,
261,
4963,
907,
510,
9477,
422,
374,
13,
288,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
3122,
273,
11013,
8674,
18,
1717,
12,
12296,
4649,
1769,
203,
3639,
2254,
5034,
15027,
273,
783,
23365,
18,
1289,
12,
203,
5411,
3122,
18,
16411,
12,
2892,
12385,
2934,
2892,
12,
4963,
907,
510,
9477,
13,
203,
3639,
11272,
203,
203,
3639,
11013,
4649,
273,
11013,
8674,
31,
203,
3639,
783,
23365,
273,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./DG4610Simple.sol";
import "../interfaces/ITokenAuxiliary.sol";
contract RuneGolem is DG4610Simple {
ITokenAuxiliary private immutable _tokenProvider;
uint256 public runesRequirement = 10;
uint256 public maxCountId = 500;
mapping(address => uint256) public userMinted;
constructor(address tokenProvider_) DG4610Simple("Godland Rune Golem", "GDLRG") {
_tokenProvider = ITokenAuxiliary(tokenProvider_);
tokenIdCounter = 1;
}
/**
* @dev Set the minimal rune to make a golem
* @param runesRequirement_ the minimal rune amount
*/
function setRunesRequirement(uint256 runesRequirement_) external onlyOwner {
runesRequirement = runesRequirement_;
}
/**
* @dev Set maxiume counts of golem should make
* @param maxCounterId_ the maximun count
*/
function setMaxCountId(uint256 maxCounterId_) external onlyOwner {
maxCountId = maxCounterId_;
}
/**
* @dev Make a golem for one address
* the required runes will not be consumed
*/
function makeGolem() external {
require(userMinted[msg.sender] == 0, "already minted");
require(tokenIdCounter < maxCountId, "cannot mint anymore");
uint256 runeSum;
uint256[] memory runes = _tokenProvider.userRunes(msg.sender);
for (uint256 index = 9; index > 0; ) {
runeSum += runes[--index];
if (runeSum >= runesRequirement) {
userMinted[msg.sender] = tokenIdCounter;
_mint(msg.sender);
return;
}
}
revert("not enought runes");
}
}
|
* @dev Set maxiume counts of golem should make @param maxCounterId_ the maximun count/
|
function setMaxCountId(uint256 maxCounterId_) external onlyOwner {
maxCountId = maxCounterId_;
}
| 954,898 |
[
1,
694,
943,
77,
2066,
6880,
434,
314,
790,
81,
1410,
1221,
225,
943,
4789,
548,
67,
326,
30547,
318,
1056,
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
] |
[
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,
10851,
1380,
548,
12,
11890,
5034,
943,
4789,
548,
67,
13,
3903,
1338,
5541,
288,
203,
3639,
943,
1380,
548,
273,
943,
4789,
548,
67,
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
] |
/**
*Submitted for verification at Etherscan.io on 2022-04-21
*/
/**
DOGETTE - Lady Doge Meme Currency
Dogette's idol's are Doge Coin and Shiba Inu, we inspire to follow their foot steps and become a worldwide brand.
Telegram: https://t.me/Dogette_ETH
Website: https://dogettetoken.com
Twitter: https://twitter.com/DogetteToken
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.0;
interface IERC20 {
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 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;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return payable(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;
}
}
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _activate() external virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function startTrading() external virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
/**
* @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);
}
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view 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;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
//Locks the contract for owner for the amount of time provided
function lock(uint256 time) public virtual onlyOwner {
_previousOwner = _owner;
_owner = address(0);
_lockTime = block.timestamp + time;
emit OwnershipTransferred(_owner, address(0));
}
//Unlocks the contract for owner when _lockTime is exceeds
function unlock() public virtual {
require(_previousOwner == msg.sender, "You don't have permission to unlock");
require(block.timestamp > _lockTime , "Contract is locked until 7 days");
emit OwnershipTransferred(_owner, _previousOwner);
_owner = _previousOwner;
}
}
// pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract DOGETTE is Context, IERC20, Ownable, Pausable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _whiteList;
address public deadAddress = 0x000000000000000000000000000000000000dEaD;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 100000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "DOGETTE";
string private _symbol = "DOGETTE";
uint8 private _decimals = 9;
//Buy Fees
uint256 public _buyTaxFee = 0;
uint256 public _buyLiquidityFee = 0;
uint256 public _buyMarketingFee = 0;
uint256 public _buyBurnFee = 0;
//Sell Fees
uint256 public _sellTaxFee = 0;
uint256 public _sellMarketingFee = 0;
uint256 public _sellLiquidityFee = 0;
uint256 public _sellBurnFee = 0;
// Fees (Current)
uint256 private _taxFee;
uint256 private _marketingFee;
uint256 private _liquidityFee;
uint256 private _burnFee;
address payable public marketingWallet = payable(0x08C1217E045B0200cB16e8F5Cb70BE0c991f19E5);
mapping(address => bool) public _isBlacklisted;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public numTokensSellToAddToLiquidity = 100000000 * 10**9; //0.1%
uint256 public _maxTxAmount = 1000000000 * 10**9;
uint256 public maxBuyTransactionAmount = 250000000 * 10**9; //0.25%
uint256 public maxWalletToken = 750000000 * 10**9; //.75%
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
//exclude owner and this contract from fee
_whiteList[owner()] = true;
_whiteList[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function blacklistAddress(address account, bool value) external onlyOwner{
_isBlacklisted[account] = value;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
} else {
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**2
);
}
function removeAllFee() private {
if(_taxFee == 0 && _liquidityFee == 0 && _marketingFee==0 && _burnFee==0) return;
_taxFee = 0;
_liquidityFee = 0;
_marketingFee = 0;
_burnFee = 0;
}
function isWhiteListed(address account) public view returns(bool) {
return _whiteList[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) whenNotPaused() private {
require(from != address(0), "ERC20: transfer from the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address');
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
to != uniswapV2Pair
) {
uint256 contractBalanceRecepient = balanceOf(to);
require(
contractBalanceRecepient + amount <= maxWalletToken,
"Exceeds maximum wallet token amount."
);
}
if(from == uniswapV2Pair && !isWhiteListed(to)){
require(amount <= maxBuyTransactionAmount, "Buy transfer amount exceeds the maxBuyTransactionAmount.");
}
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
//add liquidity
swapAndLiquify(contractTokenBalance);
}
// Indicates if fee should be deducted from transfer
bool takeFee = true;
// If any account belongs to _isExcludedFromFee account then remove the fee
if(isWhiteListed(from) || isWhiteListed(to)){
takeFee = false;
}
// Set buy fees
if(from == uniswapV2Pair || from.isContract()) {
_taxFee = _buyTaxFee;
_marketingFee = _buyMarketingFee;
_liquidityFee = _buyLiquidityFee;
_burnFee = _buyBurnFee;
}
// Set sell fees
if(to == uniswapV2Pair || to.isContract()) {
_taxFee = _sellTaxFee;
_marketingFee = _sellMarketingFee;
_liquidityFee = _sellLiquidityFee;
_burnFee = _sellBurnFee;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from,to,amount);
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
uint256 combineFees = _liquidityFee.add(_marketingFee); // marketing + liquidity fees
uint256 tokensForLiquidity = contractTokenBalance.mul(_liquidityFee).div(combineFees);
uint256 tokensForMarketing = contractTokenBalance.sub(tokensForLiquidity);
// split the Liquidity tokens balance into halves
uint256 half = tokensForLiquidity.div(2);
uint256 otherHalf = tokensForLiquidity.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
uint256 contractBalance = address(this).balance;
swapTokensForEth(tokensForMarketing);
uint256 transferredBalance = address(this).balance.sub(contractBalance);
//Send to Marketing address
transferToAddressETH(marketingWallet, transferredBalance);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(address sender, address recipient, uint256 amount) private
{
if(_whiteList[sender] || _whiteList[recipient])
{
removeAllFee();
}
else
{
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
}
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
}
function _transferStandard(address sender, address recipient, uint256 tAmount) private
{
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
(tTransferAmount, rTransferAmount) = takeBurn(sender, tTransferAmount, rTransferAmount, tAmount);
(tTransferAmount, rTransferAmount) = takeMarketing(sender, tTransferAmount, rTransferAmount, tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function takeBurn(address sender, uint256 tTransferAmount, uint256 rTransferAmount, uint256 tAmount) private
returns (uint256, uint256)
{
if(_burnFee==0) { return(tTransferAmount, rTransferAmount); }
uint256 tBurn = tAmount.div(100).mul(_burnFee);
uint256 rBurn = tBurn.mul(_getRate());
rTransferAmount = rTransferAmount.sub(rBurn);
tTransferAmount = tTransferAmount.sub(tBurn);
_rOwned[deadAddress] = _rOwned[deadAddress].add(rBurn);
emit Transfer(sender, deadAddress, tBurn);
return(tTransferAmount, rTransferAmount);
}
function takeMarketing(address sender, uint256 tTransferAmount, uint256 rTransferAmount, uint256 tAmount) private
returns (uint256, uint256)
{
if(_marketingFee==0) { return(tTransferAmount, rTransferAmount); }
uint256 tMarketing = tAmount.div(100).mul(_marketingFee);
uint256 rMarketing = tMarketing.mul(_getRate());
rTransferAmount = rTransferAmount.sub(rMarketing);
tTransferAmount = tTransferAmount.sub(tMarketing);
_rOwned[address(this)] = _rOwned[address(this)].add(rMarketing);
emit Transfer(sender, address(this), tMarketing);
return(tTransferAmount, rTransferAmount);
}
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_whiteList[account] = true;
}
function includeInFee(address account) public onlyOwner {
_whiteList[account] = false;
}
function setMarketingWallet(address payable newWallet) external onlyOwner() {
marketingWallet = newWallet;
}
function setBuyFeePercent(uint256 taxFee, uint256 MarketingFee, uint256 liquidityFee, uint256 burnFee) external onlyOwner() {
_buyTaxFee = taxFee;
_buyMarketingFee = MarketingFee;
_buyLiquidityFee = liquidityFee;
_buyBurnFee = burnFee;
}
function setSellFeePercent(uint256 taxFee, uint256 MarketingFee, uint256 liquidityFee, uint256 burnFee) external onlyOwner() {
_sellTaxFee = taxFee;
_sellMarketingFee = MarketingFee;
_sellLiquidityFee = liquidityFee;
_sellBurnFee = burnFee;
}
function setNumTokensSellToAddToLiquidity(uint256 newAmt) external onlyOwner() {
numTokensSellToAddToLiquidity = newAmt*10**_decimals;
}
function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
require(maxTxAmount > 0, "Cannot set transaction amount as zero");
_maxTxAmount = maxTxAmount * 10**_decimals;
}
function setMaxBuytx(uint256 _newAmount) public onlyOwner {
maxBuyTransactionAmount = _newAmount * 10**_decimals;
}
function setMaxWalletToken(uint256 _maxToken) external onlyOwner {
maxWalletToken = _maxToken * 10**_decimals;
}
//New router address?
//No problem, just change it here!
function setRouterAddress(address newRouter) public onlyOwner() {
IUniswapV2Router02 _newPancakeRouter = IUniswapV2Router02(newRouter);
uniswapV2Pair = IUniswapV2Factory(_newPancakeRouter.factory()).createPair(address(this), _newPancakeRouter.WETH());
uniswapV2Router = _newPancakeRouter;
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
function transferToAddressETH(address payable recipient, uint256 amount) private {
recipient.transfer(amount);
}
}
|
Buy FeesSell Fees Fees (Current)
|
contract DOGETTE is Context, IERC20, Ownable, Pausable {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _rOwned;
mapping (address => uint256) private _tOwned;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _whiteList;
address public deadAddress = 0x000000000000000000000000000000000000dEaD;
mapping (address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 100000000000 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "DOGETTE";
string private _symbol = "DOGETTE";
uint8 private _decimals = 9;
uint256 public _buyTaxFee = 0;
uint256 public _buyLiquidityFee = 0;
uint256 public _buyMarketingFee = 0;
uint256 public _buyBurnFee = 0;
uint256 public _sellTaxFee = 0;
uint256 public _sellMarketingFee = 0;
uint256 public _sellLiquidityFee = 0;
uint256 public _sellBurnFee = 0;
uint256 private _taxFee;
uint256 private _marketingFee;
uint256 private _liquidityFee;
uint256 private _burnFee;
address payable public marketingWallet = payable(0x08C1217E045B0200cB16e8F5Cb70BE0c991f19E5);
mapping(address => bool) public _isBlacklisted;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public _maxTxAmount = 1000000000 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor() {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_whiteList[owner()] = true;
_whiteList[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
function blacklistAddress(address account, bool value) external onlyOwner{
_isBlacklisted[account] = value;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(!_isExcluded[sender], "Excluded addresses cannot call this function");
(uint256 rAmount,,,,,) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee) public view returns(uint256) {
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount,,,,,) = _getValues(tAmount);
return rAmount;
(,uint256 rTransferAmount,,,,) = _getValues(tAmount);
return rTransferAmount;
}
}
} else {
function tokenFromReflection(uint256 rAmount) public view returns(uint256) {
require(rAmount <= _rTotal, "Amount must be less than total reflections");
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function excludeFromReward(address account) public onlyOwner() {
require(!_isExcluded[account], "Account is already excluded");
if(_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _transferBothExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount) private view returns (uint256, uint256, uint256, uint256, uint256, uint256) {
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) = _getRValues(tAmount, tFee, tLiquidity, _getRate());
return (rAmount, rTransferAmount, rFee, tTransferAmount, tFee, tLiquidity);
}
function _getTValues(uint256 tAmount) private view returns (uint256, uint256, uint256) {
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(uint256 tAmount, uint256 tFee, uint256 tLiquidity, uint256 currentRate) private pure returns (uint256, uint256, uint256) {
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns(uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _getCurrentSupply() private view returns(uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (_rOwned[_excluded[i]] > rSupply || _tOwned[_excluded[i]] > tSupply) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if(_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(
10**2
);
}
function calculateLiquidityFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_liquidityFee).div(
10**2
);
}
function removeAllFee() private {
if(_taxFee == 0 && _liquidityFee == 0 && _marketingFee==0 && _burnFee==0) return;
_taxFee = 0;
_liquidityFee = 0;
_marketingFee = 0;
_burnFee = 0;
}
function isWhiteListed(address account) public view returns(bool) {
return _whiteList[account];
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) whenNotPaused() private {
require(from != address(0), "ERC20: transfer from the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address');
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
to != uniswapV2Pair
) {
uint256 contractBalanceRecepient = balanceOf(to);
require(
contractBalanceRecepient + amount <= maxWalletToken,
"Exceeds maximum wallet token amount."
);
}
if(from == uniswapV2Pair && !isWhiteListed(to)){
require(amount <= maxBuyTransactionAmount, "Buy transfer amount exceeds the maxBuyTransactionAmount.");
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
swapAndLiquify(contractTokenBalance);
}
if(isWhiteListed(from) || isWhiteListed(to)){
takeFee = false;
}
if(from == uniswapV2Pair || from.isContract()) {
_taxFee = _buyTaxFee;
_marketingFee = _buyMarketingFee;
_liquidityFee = _buyLiquidityFee;
_burnFee = _buyBurnFee;
}
if(to == uniswapV2Pair || to.isContract()) {
_taxFee = _sellTaxFee;
_marketingFee = _sellMarketingFee;
_liquidityFee = _sellLiquidityFee;
_burnFee = _sellBurnFee;
}
}
function _transfer(
address from,
address to,
uint256 amount
) whenNotPaused() private {
require(from != address(0), "ERC20: transfer from the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address');
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
to != uniswapV2Pair
) {
uint256 contractBalanceRecepient = balanceOf(to);
require(
contractBalanceRecepient + amount <= maxWalletToken,
"Exceeds maximum wallet token amount."
);
}
if(from == uniswapV2Pair && !isWhiteListed(to)){
require(amount <= maxBuyTransactionAmount, "Buy transfer amount exceeds the maxBuyTransactionAmount.");
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
swapAndLiquify(contractTokenBalance);
}
if(isWhiteListed(from) || isWhiteListed(to)){
takeFee = false;
}
if(from == uniswapV2Pair || from.isContract()) {
_taxFee = _buyTaxFee;
_marketingFee = _buyMarketingFee;
_liquidityFee = _buyLiquidityFee;
_burnFee = _buyBurnFee;
}
if(to == uniswapV2Pair || to.isContract()) {
_taxFee = _sellTaxFee;
_marketingFee = _sellMarketingFee;
_liquidityFee = _sellLiquidityFee;
_burnFee = _sellBurnFee;
}
}
function _transfer(
address from,
address to,
uint256 amount
) whenNotPaused() private {
require(from != address(0), "ERC20: transfer from the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address');
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
to != uniswapV2Pair
) {
uint256 contractBalanceRecepient = balanceOf(to);
require(
contractBalanceRecepient + amount <= maxWalletToken,
"Exceeds maximum wallet token amount."
);
}
if(from == uniswapV2Pair && !isWhiteListed(to)){
require(amount <= maxBuyTransactionAmount, "Buy transfer amount exceeds the maxBuyTransactionAmount.");
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
swapAndLiquify(contractTokenBalance);
}
if(isWhiteListed(from) || isWhiteListed(to)){
takeFee = false;
}
if(from == uniswapV2Pair || from.isContract()) {
_taxFee = _buyTaxFee;
_marketingFee = _buyMarketingFee;
_liquidityFee = _buyLiquidityFee;
_burnFee = _buyBurnFee;
}
if(to == uniswapV2Pair || to.isContract()) {
_taxFee = _sellTaxFee;
_marketingFee = _sellMarketingFee;
_liquidityFee = _sellLiquidityFee;
_burnFee = _sellBurnFee;
}
}
uint256 contractTokenBalance = balanceOf(address(this));
function _transfer(
address from,
address to,
uint256 amount
) whenNotPaused() private {
require(from != address(0), "ERC20: transfer from the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address');
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
to != uniswapV2Pair
) {
uint256 contractBalanceRecepient = balanceOf(to);
require(
contractBalanceRecepient + amount <= maxWalletToken,
"Exceeds maximum wallet token amount."
);
}
if(from == uniswapV2Pair && !isWhiteListed(to)){
require(amount <= maxBuyTransactionAmount, "Buy transfer amount exceeds the maxBuyTransactionAmount.");
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
swapAndLiquify(contractTokenBalance);
}
if(isWhiteListed(from) || isWhiteListed(to)){
takeFee = false;
}
if(from == uniswapV2Pair || from.isContract()) {
_taxFee = _buyTaxFee;
_marketingFee = _buyMarketingFee;
_liquidityFee = _buyLiquidityFee;
_burnFee = _buyBurnFee;
}
if(to == uniswapV2Pair || to.isContract()) {
_taxFee = _sellTaxFee;
_marketingFee = _sellMarketingFee;
_liquidityFee = _sellLiquidityFee;
_burnFee = _sellBurnFee;
}
}
bool takeFee = true;
function _transfer(
address from,
address to,
uint256 amount
) whenNotPaused() private {
require(from != address(0), "ERC20: transfer from the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address');
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
to != uniswapV2Pair
) {
uint256 contractBalanceRecepient = balanceOf(to);
require(
contractBalanceRecepient + amount <= maxWalletToken,
"Exceeds maximum wallet token amount."
);
}
if(from == uniswapV2Pair && !isWhiteListed(to)){
require(amount <= maxBuyTransactionAmount, "Buy transfer amount exceeds the maxBuyTransactionAmount.");
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
swapAndLiquify(contractTokenBalance);
}
if(isWhiteListed(from) || isWhiteListed(to)){
takeFee = false;
}
if(from == uniswapV2Pair || from.isContract()) {
_taxFee = _buyTaxFee;
_marketingFee = _buyMarketingFee;
_liquidityFee = _buyLiquidityFee;
_burnFee = _buyBurnFee;
}
if(to == uniswapV2Pair || to.isContract()) {
_taxFee = _sellTaxFee;
_marketingFee = _sellMarketingFee;
_liquidityFee = _sellLiquidityFee;
_burnFee = _sellBurnFee;
}
}
function _transfer(
address from,
address to,
uint256 amount
) whenNotPaused() private {
require(from != address(0), "ERC20: transfer from the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address');
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
to != uniswapV2Pair
) {
uint256 contractBalanceRecepient = balanceOf(to);
require(
contractBalanceRecepient + amount <= maxWalletToken,
"Exceeds maximum wallet token amount."
);
}
if(from == uniswapV2Pair && !isWhiteListed(to)){
require(amount <= maxBuyTransactionAmount, "Buy transfer amount exceeds the maxBuyTransactionAmount.");
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
swapAndLiquify(contractTokenBalance);
}
if(isWhiteListed(from) || isWhiteListed(to)){
takeFee = false;
}
if(from == uniswapV2Pair || from.isContract()) {
_taxFee = _buyTaxFee;
_marketingFee = _buyMarketingFee;
_liquidityFee = _buyLiquidityFee;
_burnFee = _buyBurnFee;
}
if(to == uniswapV2Pair || to.isContract()) {
_taxFee = _sellTaxFee;
_marketingFee = _sellMarketingFee;
_liquidityFee = _sellLiquidityFee;
_burnFee = _sellBurnFee;
}
}
function _transfer(
address from,
address to,
uint256 amount
) whenNotPaused() private {
require(from != address(0), "ERC20: transfer from the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
require(!_isBlacklisted[from] && !_isBlacklisted[to], 'Blacklisted address');
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
to != uniswapV2Pair
) {
uint256 contractBalanceRecepient = balanceOf(to);
require(
contractBalanceRecepient + amount <= maxWalletToken,
"Exceeds maximum wallet token amount."
);
}
if(from == uniswapV2Pair && !isWhiteListed(to)){
require(amount <= maxBuyTransactionAmount, "Buy transfer amount exceeds the maxBuyTransactionAmount.");
}
bool overMinTokenBalance = contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
swapAndLiquify(contractTokenBalance);
}
if(isWhiteListed(from) || isWhiteListed(to)){
takeFee = false;
}
if(from == uniswapV2Pair || from.isContract()) {
_taxFee = _buyTaxFee;
_marketingFee = _buyMarketingFee;
_liquidityFee = _buyLiquidityFee;
_burnFee = _buyBurnFee;
}
if(to == uniswapV2Pair || to.isContract()) {
_taxFee = _sellTaxFee;
_marketingFee = _sellMarketingFee;
_liquidityFee = _sellLiquidityFee;
_burnFee = _sellBurnFee;
}
}
_tokenTransfer(from,to,amount);
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
uint256 tokensForLiquidity = contractTokenBalance.mul(_liquidityFee).div(combineFees);
uint256 tokensForMarketing = contractTokenBalance.sub(tokensForLiquidity);
uint256 half = tokensForLiquidity.div(2);
uint256 otherHalf = tokensForLiquidity.sub(half);
uint256 initialBalance = address(this).balance;
uint256 newBalance = address(this).balance.sub(initialBalance);
addLiquidity(otherHalf, newBalance);
emit SwapAndLiquify(half, newBalance, otherHalf);
uint256 contractBalance = address(this).balance;
swapTokensForEth(tokensForMarketing);
uint256 transferredBalance = address(this).balance.sub(contractBalance);
transferToAddressETH(marketingWallet, transferredBalance);
}
function swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
owner(),
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
function _tokenTransfer(address sender, address recipient, uint256 amount) private
{
if(_whiteList[sender] || _whiteList[recipient])
{
removeAllFee();
}
else
{
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
}
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
}
function _tokenTransfer(address sender, address recipient, uint256 amount) private
{
if(_whiteList[sender] || _whiteList[recipient])
{
removeAllFee();
}
else
{
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
}
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
}
function _tokenTransfer(address sender, address recipient, uint256 amount) private
{
if(_whiteList[sender] || _whiteList[recipient])
{
removeAllFee();
}
else
{
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
}
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
}
function _tokenTransfer(address sender, address recipient, uint256 amount) private
{
if(_whiteList[sender] || _whiteList[recipient])
{
removeAllFee();
}
else
{
require(amount <= _maxTxAmount, "Transfer amount exceeds the maxTxAmount.");
}
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
}
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
} else {
function _transferStandard(address sender, address recipient, uint256 tAmount) private
{
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
(tTransferAmount, rTransferAmount) = takeBurn(sender, tTransferAmount, rTransferAmount, tAmount);
(tTransferAmount, rTransferAmount) = takeMarketing(sender, tTransferAmount, rTransferAmount, tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function takeBurn(address sender, uint256 tTransferAmount, uint256 rTransferAmount, uint256 tAmount) private
returns (uint256, uint256)
{
uint256 tBurn = tAmount.div(100).mul(_burnFee);
uint256 rBurn = tBurn.mul(_getRate());
rTransferAmount = rTransferAmount.sub(rBurn);
tTransferAmount = tTransferAmount.sub(tBurn);
_rOwned[deadAddress] = _rOwned[deadAddress].add(rBurn);
emit Transfer(sender, deadAddress, tBurn);
return(tTransferAmount, rTransferAmount);
}
if(_burnFee==0) { return(tTransferAmount, rTransferAmount); }
function takeMarketing(address sender, uint256 tTransferAmount, uint256 rTransferAmount, uint256 tAmount) private
returns (uint256, uint256)
{
uint256 tMarketing = tAmount.div(100).mul(_marketingFee);
uint256 rMarketing = tMarketing.mul(_getRate());
rTransferAmount = rTransferAmount.sub(rMarketing);
tTransferAmount = tTransferAmount.sub(tMarketing);
_rOwned[address(this)] = _rOwned[address(this)].add(rMarketing);
emit Transfer(sender, address(this), tMarketing);
return(tTransferAmount, rTransferAmount);
}
if(_marketingFee==0) { return(tTransferAmount, rTransferAmount); }
function _transferToExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(address sender, address recipient, uint256 tAmount) private {
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee, uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_whiteList[account] = true;
}
function includeInFee(address account) public onlyOwner {
_whiteList[account] = false;
}
function setMarketingWallet(address payable newWallet) external onlyOwner() {
marketingWallet = newWallet;
}
function setBuyFeePercent(uint256 taxFee, uint256 MarketingFee, uint256 liquidityFee, uint256 burnFee) external onlyOwner() {
_buyTaxFee = taxFee;
_buyMarketingFee = MarketingFee;
_buyLiquidityFee = liquidityFee;
_buyBurnFee = burnFee;
}
function setSellFeePercent(uint256 taxFee, uint256 MarketingFee, uint256 liquidityFee, uint256 burnFee) external onlyOwner() {
_sellTaxFee = taxFee;
_sellMarketingFee = MarketingFee;
_sellLiquidityFee = liquidityFee;
_sellBurnFee = burnFee;
}
function setNumTokensSellToAddToLiquidity(uint256 newAmt) external onlyOwner() {
numTokensSellToAddToLiquidity = newAmt*10**_decimals;
}
function setMaxTxAmount(uint256 maxTxAmount) external onlyOwner() {
require(maxTxAmount > 0, "Cannot set transaction amount as zero");
_maxTxAmount = maxTxAmount * 10**_decimals;
}
function setMaxBuytx(uint256 _newAmount) public onlyOwner {
maxBuyTransactionAmount = _newAmount * 10**_decimals;
}
function setMaxWalletToken(uint256 _maxToken) external onlyOwner {
maxWalletToken = _maxToken * 10**_decimals;
}
function setRouterAddress(address newRouter) public onlyOwner() {
IUniswapV2Router02 _newPancakeRouter = IUniswapV2Router02(newRouter);
uniswapV2Pair = IUniswapV2Factory(_newPancakeRouter.factory()).createPair(address(this), _newPancakeRouter.WETH());
uniswapV2Router = _newPancakeRouter;
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
function transferToAddressETH(address payable recipient, uint256 amount) private {
recipient.transfer(amount);
}
}
| 15,338,000 |
[
1,
38,
9835,
5782,
281,
55,
1165,
5782,
281,
5782,
281,
261,
3935,
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,
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,
16351,
5467,
3264,
1448,
353,
1772,
16,
467,
654,
39,
3462,
16,
14223,
6914,
16,
21800,
16665,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
5267,
364,
1758,
31,
203,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
86,
5460,
329,
31,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
13,
3238,
389,
88,
5460,
329,
31,
203,
565,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
3238,
389,
5965,
6872,
31,
203,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
14739,
682,
31,
203,
203,
565,
1758,
1071,
8363,
1887,
273,
374,
92,
12648,
12648,
12648,
12648,
2787,
72,
41,
69,
40,
31,
203,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
16461,
31,
203,
565,
1758,
8526,
3238,
389,
24602,
31,
203,
27699,
565,
2254,
5034,
3238,
5381,
4552,
273,
4871,
11890,
5034,
12,
20,
1769,
203,
565,
2254,
5034,
3238,
389,
88,
5269,
273,
15088,
11706,
380,
1728,
636,
29,
31,
203,
565,
2254,
5034,
3238,
389,
86,
5269,
273,
261,
6694,
300,
261,
6694,
738,
389,
88,
5269,
10019,
203,
565,
2254,
5034,
3238,
389,
88,
14667,
5269,
31,
203,
203,
565,
533,
3238,
389,
529,
273,
315,
3191,
3264,
1448,
14432,
203,
565,
533,
3238,
389,
7175,
273,
315,
3191,
3264,
1448,
14432,
203,
565,
2254,
28,
3238,
389,
31734,
273,
2468,
31,
203,
377,
203,
565,
2254,
5034,
1071,
389,
70,
9835,
7731,
14667,
273,
374,
31,
203,
565,
2254,
5034,
1071,
2
] |
./full_match/4/0x14Ac3D94c295B8778a70485bD6d1Ca5294C5a4Be/sources/AltexV2.sol
|
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x10ED43C718714eb63d5aA57B78B54704E256024E ); Create a uniswap pair for this new token set the rest of the contract variablesexclude owner and this contract from fee
|
constructor () public {
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D );
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
emit Transfer(address(0), _msgSender(), _tTotal);
}
| 675,436 |
[
1,
45,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
20,
92,
2163,
2056,
8942,
39,
27,
2643,
27,
3461,
24008,
4449,
72,
25,
69,
37,
10321,
38,
8285,
38,
6564,
27,
3028,
41,
5034,
3103,
24,
41,
11272,
1788,
279,
640,
291,
91,
438,
3082,
364,
333,
394,
1147,
444,
326,
3127,
434,
326,
6835,
3152,
10157,
3410,
471,
333,
6835,
628,
14036,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
3885,
1832,
1071,
288,
203,
3639,
389,
86,
5460,
329,
63,
67,
3576,
12021,
1435,
65,
273,
389,
86,
5269,
31,
203,
540,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
20,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
11272,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
540,
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,
540,
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
] |
./full_match/1/0xdca0641e507709FFE7e1e532533aC84e2c27c4bF/sources/localhost/staking/rewards/MixinPopRewards.sol
|
@dev Get stats on a staking pool in this epoch. @param poolId Pool Id to query. @return PoolStats struct for pool id.
|
function getStakingPoolStatsThisEpoch(bytes32 poolId)
external
view
override
returns (IStructs.PoolStats memory)
{
return poolStatsByEpoch[poolId][currentEpoch];
}
| 3,221,499 |
[
1,
967,
3177,
603,
279,
384,
6159,
2845,
316,
333,
7632,
18,
225,
2845,
548,
8828,
3124,
358,
843,
18,
327,
8828,
4195,
1958,
364,
2845,
612,
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
] |
[
1,
1,
1,
1,
1,
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,
21491,
6159,
2864,
4195,
2503,
14638,
12,
3890,
1578,
2845,
548,
13,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
3849,
203,
3639,
1135,
261,
45,
3823,
87,
18,
2864,
4195,
3778,
13,
203,
565,
288,
203,
3639,
327,
2845,
4195,
858,
14638,
63,
6011,
548,
6362,
2972,
14638,
15533,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
// import "@openzeppelin/contracts/utils/Counters.sol";
// import { Base64 } from "base64-sol/base64.sol";
import { RxStructs } from "./libraries/RxStructs.sol";
import { TokenURIDescriptor } from "./libraries/TokenURIDescriptor.sol";
/// @title A NFT Prescription creator
/// @author Matias Parij (@7i7o)
/// @notice You can use this contract only as a MVP for minting Prescriptions
/// @dev Features such as workplaces for doctors or pharmacists are for future iterations
contract Rx is ERC721, ERC721URIStorage, ERC721Burnable, AccessControl {
/// @notice Role definition for Minter
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
/// @notice Role definition for Minter
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
/// @notice Role definition for Burner
bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE");
/** Begin of State Variables & Events */
// uint8 internal constant MAX_KEY_LENGTH = 20;
// uint8 internal constant MAX_VALUE_LENGTH = 62;
uint8 internal constant RX_LINES = 12; // Has to be same value as in RxStructs !!!
bool private selfGrantAdmin = false;
/// @notice TokenId enumeration (start at '1').
uint256 private _tokenIdCounter;
/// @notice this mapping holds all the subjects registered in the contract
mapping ( address => RxStructs.Subject ) private subjects;
/// @notice this mapping holds all the doctors registered in the contract
mapping ( address => RxStructs.Doctor ) private doctors;
/// @notice this mapping holds all the pharmacists registered in the contract
mapping ( address => RxStructs.Pharmacist ) private pharmacists;
/// @notice this mapping holds all the prescriptions minted in the contract
mapping ( uint256 => RxStructs.RxData ) private rxs;
/// @notice Event to signal when a new Rx has been minted
/// @param sender address of the Doctor that minted the Rx
/// @param receiver address of the Subject that received the Rx minted
/// @param tokenId Id of the Token (Rx) that has been minted
event minted(address indexed sender, address indexed receiver, uint256 indexed tokenId);
/// @notice Event to signal when adding/replacing a Subject allowed to receive/hold NFT Prescriptions
/// @param sender is the address of the admin that set the Subject's data
/// @param _subjectId is the registered address of the subject (approved for holding NFT Prescriptions)
/// @param _birthDate is the subjects' date of birth, in seconds, from UNIX Epoch (1970-01-01)
/// @param _nameA is the subject's full name (uses 2 bytes32)
/// @param _nameB is the subject's full name (uses 2 bytes32)
/// @param _homeAddressA is the subject's legal home address (uses 2 bytes32)
/// @param _homeAddressB is the subject's legal home address (uses 2 bytes32)
event subjectDataSet(address indexed sender, address indexed _subjectId, uint256 _birthDate, bytes32 _nameA, bytes32 _nameB, bytes32 _homeAddressA, bytes32 _homeAddressB);
/// @notice Event to signal when adding/replacing a Doctor allowed to mint NFT Prescriptions
/// @param sender is the address of the admin that set the Doctor's data
/// @param _subjectId is the ethereum address for the doctor (same Id as the subject that holds this doctor's personal details)
/// @param _degree contains a string with the degree of the doctor
/// @param _license contains a string with the legal license of the doctor
event doctorDataSet(address indexed sender, address indexed _subjectId, bytes32 _degree, bytes32 _license);
/// @notice Event to signal when adding/replacing a Pharmacist allowed to burn NFT Prescriptions
/// @param sender is the address of the admin that set the Pharmacist's data
/// @param _subjectId is the ethereum address for the pahrmacist (same Id as the subject that holds this pharmacist's personal details)
/// @param _degree contains a string with the degree of the pharmacist
/// @param _license contains a string with the legal license of the pharmacist
event pharmacistDataSet(address indexed sender, address indexed _subjectId, bytes32 _degree, bytes32 _license);
/// @notice Event to signal a removed Subject
/// @param sender is the address of the admin that removed the Subject
/// @param _subjectId is the registered address of the subject removed
event subjectRemoved(address indexed sender, address indexed _subjectId);
/// @notice Event to signal a removed Doctor
/// @param sender is the address of the admin that removed the Doctor
/// @param _subjectId is the registered address of the doctor removed
event doctorRemoved(address indexed sender, address indexed _subjectId);
/// @notice Event to signal a removed Pharmacist
/// @param sender is the address of the admin that removed the Pharmacist
/// @param _subjectId is the registered address of the pharmacist removed
event pharmacistRemoved(address indexed sender, address indexed _subjectId);
/** End of State Variables & Events */
/// @notice constructor for NFT Prescriptions contract
/// @dev Using ERC721 default constructor with "Prescription" and "Rx" as Name and Symbol for the tokens
/// @dev We set up the contract creator (msg.sender) with the ADMIN_ROLE to manage all the other Roles
/// @dev We increment the counter in the constructor to start Ids in 1, keeping Id 0 (default for uints
/// in solidity) to signal that someone doesn't have any NFTs
constructor() ERC721("Rx", "Rx") {
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
grantRole(ADMIN_ROLE, msg.sender);
_setRoleAdmin(MINTER_ROLE, ADMIN_ROLE);
_setRoleAdmin(BURNER_ROLE, ADMIN_ROLE);
_tokenIdCounter = 1;
}
/// @dev function override required by solidity
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, AccessControl)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
/** Begin of implementation of functions for final project */
/// @dev Transfers ownership of the contract to a new account (`newOwner`). Can only be called by the current owner.
function transferOwnership(address newOwner)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
grantRole(DEFAULT_ADMIN_ROLE, newOwner);
renounceRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/// @dev Checks if _addr is a Subject
function isSubject(address _addr) private view returns (bool) {
return (
_addr != address(0)
&& subjects[_addr].subjectId == _addr
);
}
/// @dev Checks if _addr is a registered doctor
function isDoctor(address _addr) private view returns (bool) {
return (
_addr != address(0)
&& doctors[_addr].subjectId == _addr
);
}
/// @dev Checks if _addr is a registered pharmacist
function isPharmacist(address _addr) private view returns (bool) {
return (
_addr != address(0)
&& pharmacists[_addr].subjectId == _addr
);
}
/// @notice function override to prohibit token transfers
function _transfer(address, address, uint256)
internal
view
override(ERC721)
{
require(msg.sender == address(0), "RX: Rxs are untransferables");
}
/// @notice Funtion to mint a Prescription. Should be called only by a Doctor (has MINTER_ROLE)
/// @param to The id of the subject (patient) recipient of the prescription
/// @param _keys Text lines with the 'title' of each content of the prescription (max 19 characters each)
/// @param _values Text lines with the 'content' of the prescription (max 61 characters each)
/// @dev Does NOT store a tokenURI. It stores Prescription data on contract (tokenURI is generated upon request)
function mint(address to, bytes32[RX_LINES] memory _keys, bytes32[2*RX_LINES] memory _values)
public
onlyRole(MINTER_ROLE)
{
require( isSubject(to), 'RX: Not a Subject');
require( (msg.sender != to) , 'RX: Cannot self-prescribe');
uint256 tokenId = _tokenIdCounter++;
super._safeMint(to, tokenId);
// Store prescription data in contract, leaving tokenURI empty, for it is generated on request (Uniswap V3 style!)
rxs[tokenId].date = block.timestamp;
rxs[tokenId].patient = getSubject(to); // Patient Info
rxs[tokenId].doctorSubject = getSubject(msg.sender); // Doctor (Subject) Info
rxs[tokenId].doctor = getDoctor(msg.sender); // Doctor Info
rxs[tokenId].keys = _keys; // Rx Keys
rxs[tokenId].values = _values; // Rx values
emit minted(msg.sender, to, tokenId);
}
/// @dev function override required by solidity
/// @notice function override to store burner data in the rx before burning
function _burn(uint256 tokenId)
internal
override(ERC721, ERC721URIStorage)
onlyRole(BURNER_ROLE)
{
// delete rxs[tokenId]; // Keep Rx Data to be able to view past (dispensed) Prescriptions
require(
getApproved(tokenId) == msg.sender ||
isApprovedForAll(ownerOf(tokenId), msg.sender),
"pharm not approved");
// We save the burner (pharmacist) data to the Rx
rxs[tokenId].pharmacistSubject = getSubject(msg.sender);
rxs[tokenId].pharmacist = getPharmacist(msg.sender);
super._burn(tokenId);
//TODO: Change prescription life cycle in 'Status' to keep prescription data without burning
}
/// @dev TokenURI generated on the fly from stored data (function override required by solidity)
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
// require(_exists(tokenId), "nonexistent token");
require(tokenId < _tokenIdCounter, "nonminted token"); // Also show TokenURI for 'dispensed' prescriptions
return TokenURIDescriptor.constructTokenURI(tokenId, name(), symbol(), rxs[tokenId]);
// TODO: Only show TokenURI to authorized people (patient, doctor, pharmacist)
// TODO: Modify SVG when a prescription is 'dispensed'
}
/// @notice Function to get data for a specific tokenId. Only for Doctor, Patient or Pharmacist of the tokenId.
/// @param tokenId uint256 representing an existing tokenId
/// @return a RxData struct containing all the Rx Data
function getRx(uint256 tokenId)
public
view
returns (RxStructs.RxData memory)
{
return rxs[tokenId];
// TODO: Only show TokenURI to authorized people (patient, doctor, pharmacist)
}
/// @notice Function to set selfGrantAdmin (only deployer of contract is allowed)
/// @param _selfAdmin bool to set state variable
function setSelfGrantAdmin(bool _selfAdmin)
public
onlyRole(DEFAULT_ADMIN_ROLE)
{
selfGrantAdmin = _selfAdmin;
}
/// @notice Function to set selfGrantAdmin (only deployer of contract is allowed)
/// @return bool with state variable
function getSelfGrantAdmin()
public
view
returns (bool)
{
return selfGrantAdmin;
}
/// @notice Function to add an admin account
/// @param to Address of the account to grant admin role
function addAdmin(address to)
public
{
if (!selfGrantAdmin) {
grantRole(ADMIN_ROLE, to);
} else {
// We skip role manager checks for the final project presentation
_grantRole(ADMIN_ROLE, to);
}
}
/// @notice Function to remove an admin account
/// @param to Address of the account to remove admin role
function removeAdmin(address to)
public
onlyRole(ADMIN_ROLE)
{
revokeRole(ADMIN_ROLE, to);
}
/// @notice Function to check if someone has admin role
/// @param to address to check for admin role privilege
/// @return true if @param to is an admin or false otherwise
function isAdmin(address to)
public
view
returns (bool)
{
return hasRole(ADMIN_ROLE, to);
}
/// @notice Function to retrieve a Subject
/// @param _subjectId the registered address of the subject to retrieve
/// @return an object with the Subject
function getSubject(address _subjectId)
public
view
returns (RxStructs.Subject memory)
{
return subjects[_subjectId];
}
/// @notice Function to retrieve a Doctor
/// @param _subjectId the registered address of the doctor to retrieve
/// @return an object with the Doctor
function getDoctor(address _subjectId)
public
view
returns (RxStructs.Doctor memory)
{
return doctors[_subjectId];
}
/// @notice Function to retrieve a Pharmacist
/// @param _subjectId the registered address of the pharmacist to retrieve
/// @return an object with the Pharmacist
function getPharmacist(address _subjectId)
public
view
returns (RxStructs.Pharmacist memory)
{
return pharmacists[_subjectId];
}
/// @notice Function to add/replace a Subject allowed to receive/hold NFT Prescriptions
/// @param _subjectId is the registered address of the subject (approved for holding NFT Prescriptions)
/// @param _birthDate is the subjects' date of birth, in seconds, from UNIX Epoch (1970-01-01)
/// @param _nameA is the subject's full name (uses 2 bytes32)
/// @param _nameB is the subject's full name (uses 2 bytes32)
/// @param _homeAddressA is the subject's legal home address (uses 2 bytes32)
/// @param _homeAddressB is the subject's legal home address (uses 2 bytes32)
/// @dev Only ADMIN_ROLE users are allowed to modify subjects
function setSubjectData(address _subjectId, uint256 _birthDate, bytes32 _nameA, bytes32 _nameB, bytes32 _homeAddressA, bytes32 _homeAddressB)
public
onlyRole(ADMIN_ROLE)
{
require ( _subjectId != address(0), 'RX: Cannot register 0x0 address');
// subjects[_subjectId] = RxStructs.Subject(_subjectId, _birthDate, _nameA, _nameB, _homeAddressA, _homeAddressB);
subjects[_subjectId].subjectId = _subjectId;
subjects[_subjectId].birthDate = _birthDate;
subjects[_subjectId].nameA = _nameA;
subjects[_subjectId].nameB = _nameB;
subjects[_subjectId].homeAddressA = _homeAddressA;
subjects[_subjectId].homeAddressB = _homeAddressB;
emit subjectDataSet(msg.sender, _subjectId, _birthDate, _nameA, _nameB, _homeAddressA, _homeAddressB);
}
/// @notice Function to add/replace a Doctor allowed to mint NFT Prescriptions
/// @param _subjectId should be a valid ethereum address (same Id as the subject that holds this doctor's personal details)
/// @param _degree should contain the degree of the doctor
/// @param _license should contain the legal license of the doctor
/// @dev @param _workplaces is a feature for future implementations
function setDoctorData(address _subjectId, bytes32 _degree, bytes32 _license) //, address[] calldata _workplaces)
public
onlyRole(ADMIN_ROLE)
{
require( isSubject(_subjectId), 'RX: Not a Subject'); // Also checks address!=0x0
grantRole(MINTER_ROLE, _subjectId);
// doctors[_subjectId] = RxStructs.Doctor(_subjectId, _degree, _license);
doctors[_subjectId].subjectId = _subjectId;
doctors[_subjectId].degree = _degree;
doctors[_subjectId].license = _license;
emit doctorDataSet(msg.sender, _subjectId, _degree, _license);
}
/// @notice Function to add/replace a Pharmacist allowed to burn NFT Prescriptions
/// @param _subjectId should be a valid ethereum address (same Id as the subject that holds this pharmacist's personal details)
/// @param _degree should contain the degree of the pharmacist
/// @param _license should contain the legal license of the pharmacist
/// @dev @param _workplaces is a feature for future implementations
function setPharmacistData(address _subjectId, bytes32 _degree, bytes32 _license) //, address[] calldata _workplaces)
public
onlyRole(ADMIN_ROLE)
{
require( isSubject(_subjectId), 'RX: Not a Subject'); // Also checks address!=0x0
grantRole(BURNER_ROLE, _subjectId);
// pharmacists[_subjectId] = RxStructs.Pharmacist(_subjectId, _degree, _license);
pharmacists[_subjectId].subjectId = _subjectId;
pharmacists[_subjectId].degree = _degree;
pharmacists[_subjectId].license = _license;
emit pharmacistDataSet(msg.sender, _subjectId, _degree, _license);
}
/// @notice Function to remove a registered Subject
/// @param _subjectId is the registered address of the subject to remove
/// @dev Only ADMIN_ROLE users are allowed to remove subjects
function removeSubject(address _subjectId)
public
onlyRole(ADMIN_ROLE)
{
require( isSubject(_subjectId), 'RX: Not a Subject'); // Also checks address!=0x0
require( !isDoctor(_subjectId), 'RX: Still a Doctor');
require( !isPharmacist(_subjectId), 'RX: Still a Pharmacist');
delete subjects[_subjectId];
emit subjectRemoved(msg.sender, _subjectId);
}
/// @notice Function to remove a registered Doctor
/// @param _subjectId is the registered address of the doctor to remove
/// @dev Only ADMIN_ROLE users are allowed to remove doctors
function removeDoctor(address _subjectId)
public
onlyRole(ADMIN_ROLE)
{
require( isDoctor(_subjectId), 'RX: Not a Doctor'); // Also checks address!=0x0
revokeRole(MINTER_ROLE, _subjectId);
delete doctors[_subjectId];
emit doctorRemoved(msg.sender, _subjectId);
}
/// @notice Function to remove a registered Pharmacist
/// @param _subjectId is the registered address of the pharmacist to remove
/// @dev Only ADMIN_ROLE users are allowed to remove pharmacists
function removePharmacist(address _subjectId)
public
onlyRole(ADMIN_ROLE)
{
require( isPharmacist(_subjectId), 'RX: Not a Pharmacist'); // Also checks address!=0x0
revokeRole(BURNER_ROLE, _subjectId);
delete pharmacists[_subjectId];
emit pharmacistRemoved(msg.sender, _subjectId);
}
}
|
@notice Function to retrieve a Doctor @param _subjectId the registered address of the doctor to retrieve @return an object with the Doctor
|
function getDoctor(address _subjectId)
public
view
returns (RxStructs.Doctor memory)
{
return doctors[_subjectId];
}
| 13,112,975 |
[
1,
2083,
358,
4614,
279,
2256,
30206,
225,
389,
7857,
548,
326,
4104,
1758,
434,
326,
741,
30206,
358,
4614,
327,
392,
733,
598,
326,
2256,
30206,
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,
11165,
30206,
12,
2867,
389,
7857,
548,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
27741,
3823,
87,
18,
3244,
30206,
3778,
13,
7010,
3639,
288,
203,
5411,
327,
31263,
1383,
63,
67,
7857,
548,
15533,
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
] |
./partial_match/43113/0x26639692ec4bFB0767f505BbEbC871b84C3D4bbE/sources/contracts/SingleStakeFactory_flattened.sol
|
* @notice This function is available to FaaS governance in case any "Scam" or nefarious farms are created using the contract. Governance will be able to stop the offending farm and allow users to recover funds. @param _farmAddress The address of the farm to be stopped./
|
function _overrideOwnership(address _farmAddress) private {
address creatorAddress = getCreator[_farmAddress];
require(creatorAddress != msg.sender, "Contract is already overriden");
require(creatorAddress != address(0), "Address is not a known farm");
SingleStakingRewards rewardsContract = SingleStakingRewards(
_farmAddress
);
address stakingToken = address(rewardsContract.stakingToken());
getSingleStake[creatorAddress][stakingToken] = address(0);
getSingleStake[msg.sender][stakingToken] = _farmAddress;
getCreator[_farmAddress] = msg.sender;
}
| 16,909,139 |
[
1,
2503,
445,
353,
2319,
358,
478,
7598,
55,
314,
1643,
82,
1359,
316,
648,
1281,
315,
1541,
301,
6,
578,
1073,
74,
12954,
1481,
10247,
959,
854,
2522,
1450,
326,
6835,
18,
611,
1643,
82,
1359,
903,
506,
7752,
358,
2132,
326,
3397,
2846,
284,
4610,
471,
1699,
3677,
358,
5910,
284,
19156,
18,
225,
389,
74,
4610,
1887,
1021,
1758,
434,
326,
284,
4610,
358,
506,
9627,
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,
389,
10601,
5460,
12565,
12,
2867,
389,
74,
4610,
1887,
13,
3238,
288,
203,
3639,
1758,
11784,
1887,
273,
15759,
639,
63,
67,
74,
4610,
1887,
15533,
203,
203,
3639,
2583,
12,
20394,
1887,
480,
1234,
18,
15330,
16,
315,
8924,
353,
1818,
31736,
8863,
203,
3639,
2583,
12,
20394,
1887,
480,
1758,
12,
20,
3631,
315,
1887,
353,
486,
279,
4846,
284,
4610,
8863,
203,
203,
3639,
10326,
510,
6159,
17631,
14727,
283,
6397,
8924,
273,
10326,
510,
6159,
17631,
14727,
12,
203,
5411,
389,
74,
4610,
1887,
203,
3639,
11272,
203,
3639,
1758,
384,
6159,
1345,
273,
1758,
12,
266,
6397,
8924,
18,
334,
6159,
1345,
10663,
203,
203,
3639,
19108,
510,
911,
63,
20394,
1887,
6362,
334,
6159,
1345,
65,
273,
1758,
12,
20,
1769,
203,
3639,
19108,
510,
911,
63,
3576,
18,
15330,
6362,
334,
6159,
1345,
65,
273,
389,
74,
4610,
1887,
31,
203,
3639,
15759,
639,
63,
67,
74,
4610,
1887,
65,
273,
1234,
18,
15330,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./StandardToken.sol";
import "./IBEP677.sol";
import "./IBEP677Receiver.sol";
/**
* @title Smart Token
* @dev Enhanced Standard Token, with "transfer and call" possibility.
*/
contract SmartToken is StandardToken, IBEP677 {
/**
* @dev Current token cannot be transferred to the token contract based on follwing override modification.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(validRecipient(to), "LQR: recipient cannot be Laqira token address");
}
/**
* @dev transfer token to a contract address with additional data if the recipient is a contract.
* @param _to address to transfer to.
* @param _value amount to be transferred.
* @param _data extra data to be passed to the receiving contract.
*/
function transferAndCall(address _to, uint256 _value, bytes memory _data) public override returns (bool success) {
_transfer(_msgSender(), _to, _value);
emit Transfer(_msgSender(), _to, _value, _data);
if (isContract(_to)) {
contractFallback(_to, _value, _data);
}
return true;
}
/**
* @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;
}
function validRecipient(address _recipient) internal view returns (bool) {
return _recipient != address(this);
}
function contractFallback(address _to, uint _value, bytes memory _data) private {
IBEP677Receiver receiver = IBEP677Receiver(_to);
receiver.onTokenTransfer(_msgSender(), _value, _data);
}
}
|
* @dev Current token cannot be transferred to the token contract based on follwing override modification./
|
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(validRecipient(to), "LQR: recipient cannot be Laqira token address");
}
| 12,983,857 |
[
1,
3935,
1147,
2780,
506,
906,
4193,
358,
326,
1147,
6835,
2511,
603,
284,
22382,
91,
310,
3849,
11544,
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,
565,
262,
2713,
5024,
3849,
288,
203,
3639,
2240,
6315,
5771,
1345,
5912,
12,
2080,
16,
358,
16,
3844,
1769,
203,
3639,
2583,
12,
877,
18241,
12,
869,
3631,
315,
48,
29853,
30,
8027,
2780,
506,
21072,
85,
11547,
1147,
1758,
8863,
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
] |
// File: contracts/src/common/lifecycle/Killable.sol
pragma solidity ^0.5.0;
/**
* A module that allows contracts to self-destruct.
*/
contract Killable {
address payable public _owner;
/**
* Initialized with the deployer as the owner.
*/
constructor() internal {
_owner = msg.sender;
}
/**
* Self-destruct the contract.
* This function can only be executed by the owner.
*/
function kill() public {
require(msg.sender == _owner, "only owner method");
selfdestruct(_owner);
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor() internal {}
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/src/common/interface/IGroup.sol
pragma solidity ^0.5.0;
contract IGroup {
function isGroup(address _addr) public view returns (bool);
function addGroup(address _addr) external;
function getGroupKey(address _addr) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("_group", _addr));
}
}
// File: contracts/src/common/validate/AddressValidator.sol
pragma solidity ^0.5.0;
/**
* A module that provides common validations patterns.
*/
contract AddressValidator {
string constant errorMessage = "this is illegal address";
/**
* Validates passed address is not a zero address.
*/
function validateIllegalAddress(address _addr) external pure {
require(_addr != address(0), errorMessage);
}
/**
* Validates passed address is included in an address set.
*/
function validateGroup(address _addr, address _groupAddr) external view {
require(IGroup(_groupAddr).isGroup(_addr), errorMessage);
}
/**
* Validates passed address is included in two address sets.
*/
function validateGroups(
address _addr,
address _groupAddr1,
address _groupAddr2
) external view {
if (IGroup(_groupAddr1).isGroup(_addr)) {
return;
}
require(IGroup(_groupAddr2).isGroup(_addr), errorMessage);
}
/**
* Validates that the address of the first argument is equal to the address of the second argument.
*/
function validateAddress(address _addr, address _target) external pure {
require(_addr == _target, errorMessage);
}
/**
* Validates passed address equals to the two addresses.
*/
function validateAddresses(
address _addr,
address _target1,
address _target2
) external pure {
if (_addr == _target1) {
return;
}
require(_addr == _target2, errorMessage);
}
/**
* Validates passed address equals to the three addresses.
*/
function validate3Addresses(
address _addr,
address _target1,
address _target2,
address _target3
) external pure {
if (_addr == _target1) {
return;
}
if (_addr == _target2) {
return;
}
require(_addr == _target3, errorMessage);
}
}
// File: contracts/src/common/validate/UsingValidator.sol
pragma solidity ^0.5.0;
// prettier-ignore
/**
* Module for contrast handling AddressValidator.
*/
contract UsingValidator {
AddressValidator private _validator;
/**
* Create a new AddressValidator contract when initialize.
*/
constructor() public {
_validator = new AddressValidator();
}
/**
* Returns the set AddressValidator address.
*/
function addressValidator() internal view returns (AddressValidator) {
return _validator;
}
}
// File: contracts/src/common/config/AddressConfig.sol
pragma solidity ^0.5.0;
/**
* A registry contract to hold the latest contract addresses.
* Dev Protocol will be upgradeable by this contract.
*/
contract AddressConfig is Ownable, UsingValidator, Killable {
address public token = 0x98626E2C9231f03504273d55f397409deFD4a093;
address public allocator;
address public allocatorStorage;
address public withdraw;
address public withdrawStorage;
address public marketFactory;
address public marketGroup;
address public propertyFactory;
address public propertyGroup;
address public metricsGroup;
address public metricsFactory;
address public policy;
address public policyFactory;
address public policySet;
address public policyGroup;
address public lockup;
address public lockupStorage;
address public voteTimes;
address public voteTimesStorage;
address public voteCounter;
address public voteCounterStorage;
/**
* Set the latest Allocator contract address.
* Only the owner can execute this function.
*/
function setAllocator(address _addr) external onlyOwner {
allocator = _addr;
}
/**
* Set the latest AllocatorStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the AllocatorStorage contract is not used.
*/
function setAllocatorStorage(address _addr) external onlyOwner {
allocatorStorage = _addr;
}
/**
* Set the latest Withdraw contract address.
* Only the owner can execute this function.
*/
function setWithdraw(address _addr) external onlyOwner {
withdraw = _addr;
}
/**
* Set the latest WithdrawStorage contract address.
* Only the owner can execute this function.
*/
function setWithdrawStorage(address _addr) external onlyOwner {
withdrawStorage = _addr;
}
/**
* Set the latest MarketFactory contract address.
* Only the owner can execute this function.
*/
function setMarketFactory(address _addr) external onlyOwner {
marketFactory = _addr;
}
/**
* Set the latest MarketGroup contract address.
* Only the owner can execute this function.
*/
function setMarketGroup(address _addr) external onlyOwner {
marketGroup = _addr;
}
/**
* Set the latest PropertyFactory contract address.
* Only the owner can execute this function.
*/
function setPropertyFactory(address _addr) external onlyOwner {
propertyFactory = _addr;
}
/**
* Set the latest PropertyGroup contract address.
* Only the owner can execute this function.
*/
function setPropertyGroup(address _addr) external onlyOwner {
propertyGroup = _addr;
}
/**
* Set the latest MetricsFactory contract address.
* Only the owner can execute this function.
*/
function setMetricsFactory(address _addr) external onlyOwner {
metricsFactory = _addr;
}
/**
* Set the latest MetricsGroup contract address.
* Only the owner can execute this function.
*/
function setMetricsGroup(address _addr) external onlyOwner {
metricsGroup = _addr;
}
/**
* Set the latest PolicyFactory contract address.
* Only the owner can execute this function.
*/
function setPolicyFactory(address _addr) external onlyOwner {
policyFactory = _addr;
}
/**
* Set the latest PolicyGroup contract address.
* Only the owner can execute this function.
*/
function setPolicyGroup(address _addr) external onlyOwner {
policyGroup = _addr;
}
/**
* Set the latest PolicySet contract address.
* Only the owner can execute this function.
*/
function setPolicySet(address _addr) external onlyOwner {
policySet = _addr;
}
/**
* Set the latest Policy contract address.
* Only the latest PolicyFactory contract can execute this function.
*/
function setPolicy(address _addr) external {
addressValidator().validateAddress(msg.sender, policyFactory);
policy = _addr;
}
/**
* Set the latest Dev contract address.
* Only the owner can execute this function.
*/
function setToken(address _addr) external onlyOwner {
token = _addr;
}
/**
* Set the latest Lockup contract address.
* Only the owner can execute this function.
*/
function setLockup(address _addr) external onlyOwner {
lockup = _addr;
}
/**
* Set the latest LockupStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the LockupStorage contract is not used as a stand-alone because it is inherited from the Lockup contract.
*/
function setLockupStorage(address _addr) external onlyOwner {
lockupStorage = _addr;
}
/**
* Set the latest VoteTimes contract address.
* Only the owner can execute this function.
* NOTE: But currently, the VoteTimes contract is not used.
*/
function setVoteTimes(address _addr) external onlyOwner {
voteTimes = _addr;
}
/**
* Set the latest VoteTimesStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the VoteTimesStorage contract is not used.
*/
function setVoteTimesStorage(address _addr) external onlyOwner {
voteTimesStorage = _addr;
}
/**
* Set the latest VoteCounter contract address.
* Only the owner can execute this function.
*/
function setVoteCounter(address _addr) external onlyOwner {
voteCounter = _addr;
}
/**
* Set the latest VoteCounterStorage contract address.
* Only the owner can execute this function.
* NOTE: But currently, the VoteCounterStorage contract is not used as a stand-alone because it is inherited from the VoteCounter contract.
*/
function setVoteCounterStorage(address _addr) external onlyOwner {
voteCounterStorage = _addr;
}
}
// File: contracts/src/common/config/UsingConfig.sol
pragma solidity ^0.5.0;
/**
* Module for using AddressConfig contracts.
*/
contract UsingConfig {
AddressConfig private _config;
/**
* Initialize the argument as AddressConfig address.
*/
constructor(address _addressConfig) public {
_config = AddressConfig(_addressConfig);
}
/**
* Returns the latest AddressConfig instance.
*/
function config() internal view returns (AddressConfig) {
return _config;
}
/**
* Returns the latest AddressConfig address.
*/
function configAddress() external view returns (address) {
return address(_config);
}
}
// File: contracts/src/market/IMarketFactory.sol
pragma solidity ^0.5.0;
contract IMarketFactory {
function create(address _addr) external returns (address);
}
// 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: contracts/src/property/IProperty.sol
pragma solidity ^0.5.0;
contract IProperty {
function author() external view returns (address);
function withdraw(address _sender, uint256 _value) external;
}
// File: contracts/src/market/IMarket.sol
pragma solidity ^0.5.0;
interface IMarket {
function authenticate(
address _prop,
string calldata _args1,
string calldata _args2,
string calldata _args3,
string calldata _args4,
string calldata _args5
)
external
returns (
// solium-disable-next-line indentation
bool
);
function authenticatedCallback(address _property, bytes32 _idHash)
external
returns (address);
function deauthenticate(address _metrics) external;
function schema() external view returns (string memory);
function behavior() external view returns (address);
function enabled() external view returns (bool);
function votingEndBlockNumber() external view returns (uint256);
function toEnable() external;
}
// File: contracts/src/market/IMarketBehavior.sol
pragma solidity ^0.5.0;
interface IMarketBehavior {
function authenticate(
address _prop,
string calldata _args1,
string calldata _args2,
string calldata _args3,
string calldata _args4,
string calldata _args5,
address market,
address account
)
external
returns (
// solium-disable-next-line indentation
bool
);
function schema() external view returns (string memory);
function getId(address _metrics) external view returns (string memory);
function getMetrics(string calldata _id) external view returns (address);
}
// File: contracts/src/policy/IPolicy.sol
pragma solidity ^0.5.0;
contract IPolicy {
function rewards(uint256 _lockups, uint256 _assets)
external
view
returns (uint256);
function holdersShare(uint256 _amount, uint256 _lockups)
external
view
returns (uint256);
function assetValue(uint256 _value, uint256 _lockups)
external
view
returns (uint256);
function authenticationFee(uint256 _assets, uint256 _propertyAssets)
external
view
returns (uint256);
function marketApproval(uint256 _agree, uint256 _opposite)
external
view
returns (bool);
function policyApproval(uint256 _agree, uint256 _opposite)
external
view
returns (bool);
function marketVotingBlocks() external view returns (uint256);
function policyVotingBlocks() external view returns (uint256);
function abstentionPenalty(uint256 _count) external view returns (uint256);
function lockUpBlocks() external view returns (uint256);
}
// File: contracts/src/metrics/IMetrics.sol
pragma solidity ^0.5.0;
contract IMetrics {
address public market;
address public property;
}
// File: contracts/src/metrics/Metrics.sol
pragma solidity ^0.5.0;
/**
* A contract for associating a Property and an asset authenticated by a Market.
*/
contract Metrics is IMetrics {
address public market;
address public property;
constructor(address _market, address _property) public {
//Do not validate because there is no AddressConfig
market = _market;
property = _property;
}
}
// File: contracts/src/metrics/IMetricsFactory.sol
pragma solidity ^0.5.0;
contract IMetricsFactory {
function create(address _property) external returns (address);
function destroy(address _metrics) external;
}
// File: contracts/src/metrics/IMetricsGroup.sol
pragma solidity ^0.5.0;
contract IMetricsGroup is IGroup {
function removeGroup(address _addr) external;
function totalIssuedMetrics() external view returns (uint256);
function getMetricsCountPerProperty(address _property)
public
view
returns (uint256);
function hasAssets(address _property) public view returns (bool);
}
// File: contracts/src/lockup/ILockup.sol
pragma solidity ^0.5.0;
contract ILockup {
function lockup(
address _from,
address _property,
uint256 _value
// solium-disable-next-line indentation
) external;
function update() public;
function cancel(address _property) external;
function withdraw(address _property) external;
function difference(address _property, uint256 _lastReward)
public
view
returns (
uint256 _reward,
uint256 _holdersAmount,
uint256 _holdersPrice,
uint256 _interestAmount,
uint256 _interestPrice
);
function getPropertyValue(address _property)
external
view
returns (uint256);
function getAllValue() external view returns (uint256);
function getValue(address _property, address _sender)
external
view
returns (uint256);
function calculateWithdrawableInterestAmount(
address _property,
address _user
)
public
view
returns (
// solium-disable-next-line indentation
uint256
);
function withdrawInterest(address _property) external;
}
// 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/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: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* 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;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender)
public
view
returns (uint256)
{
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue)
public
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
public
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(
amount,
"ERC20: transfer amount exceeds balance"
);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(
amount,
"ERC20: burn amount exceeds balance"
);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(
account,
_msgSender(),
_allowances[account][_msgSender()].sub(
amount,
"ERC20: burn amount exceeds allowance"
)
);
}
}
// File: @openzeppelin/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping(address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: @openzeppelin/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole is Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor() internal {
_addMinter(_msgSender());
}
modifier onlyMinter() {
require(
isMinter(_msgSender()),
"MinterRole: caller does not have the Minter role"
);
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Mintable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount)
public
onlyMinter
returns (bool)
{
_mint(account, amount);
return true;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.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).
*/
contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev See {ERC20-_burnFrom}.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
}
// File: contracts/src/common/libs/Decimals.sol
pragma solidity ^0.5.0;
/**
* Library for emulating calculations involving decimals.
*/
library Decimals {
using SafeMath for uint256;
uint120 private constant basisValue = 1000000000000000000;
/**
* Returns the ratio of the first argument to the second argument.
*/
function outOf(uint256 _a, uint256 _b)
internal
pure
returns (uint256 result)
{
if (_a == 0) {
return 0;
}
uint256 a = _a.mul(basisValue);
if (a < _b) {
return 0;
}
return (a.div(_b));
}
/**
* Returns multiplied the number by 10^18.
* This is used when there is a very large difference between the two numbers passed to the `outOf` function.
*/
function mulBasis(uint256 _a) internal pure returns (uint256) {
return _a.mul(basisValue);
}
/**
* Returns by changing the numerical value being emulated to the original number of digits.
*/
function divBasis(uint256 _a) internal pure returns (uint256) {
return _a.div(basisValue);
}
}
// File: contracts/src/common/storage/EternalStorage.sol
pragma solidity ^0.5.0;
/**
* Module for persisting states.
* Stores a map for `uint256`, `string`, `address`, `bytes32`, `bool`, and `int256` type with `bytes32` type as a key.
*/
contract EternalStorage {
address private currentOwner = msg.sender;
mapping(bytes32 => uint256) private uIntStorage;
mapping(bytes32 => string) private stringStorage;
mapping(bytes32 => address) private addressStorage;
mapping(bytes32 => bytes32) private bytesStorage;
mapping(bytes32 => bool) private boolStorage;
mapping(bytes32 => int256) private intStorage;
/**
* Modifiers to validate that only the owner can execute.
*/
modifier onlyCurrentOwner() {
require(msg.sender == currentOwner, "not current owner");
_;
}
/**
* Transfer the owner.
* Only the owner can execute this function.
*/
function changeOwner(address _newOwner) external {
require(msg.sender == currentOwner, "not current owner");
currentOwner = _newOwner;
}
// *** Getter Methods ***
/**
* Returns the value of the `uint256` type that mapped to the given key.
*/
function getUint(bytes32 _key) external view returns (uint256) {
return uIntStorage[_key];
}
/**
* Returns the value of the `string` type that mapped to the given key.
*/
function getString(bytes32 _key) external view returns (string memory) {
return stringStorage[_key];
}
/**
* Returns the value of the `address` type that mapped to the given key.
*/
function getAddress(bytes32 _key) external view returns (address) {
return addressStorage[_key];
}
/**
* Returns the value of the `bytes32` type that mapped to the given key.
*/
function getBytes(bytes32 _key) external view returns (bytes32) {
return bytesStorage[_key];
}
/**
* Returns the value of the `bool` type that mapped to the given key.
*/
function getBool(bytes32 _key) external view returns (bool) {
return boolStorage[_key];
}
/**
* Returns the value of the `int256` type that mapped to the given key.
*/
function getInt(bytes32 _key) external view returns (int256) {
return intStorage[_key];
}
// *** Setter Methods ***
/**
* Maps a value of `uint256` type to a given key.
* Only the owner can execute this function.
*/
function setUint(bytes32 _key, uint256 _value) external onlyCurrentOwner {
uIntStorage[_key] = _value;
}
/**
* Maps a value of `string` type to a given key.
* Only the owner can execute this function.
*/
function setString(bytes32 _key, string calldata _value)
external
onlyCurrentOwner
{
stringStorage[_key] = _value;
}
/**
* Maps a value of `address` type to a given key.
* Only the owner can execute this function.
*/
function setAddress(bytes32 _key, address _value)
external
onlyCurrentOwner
{
addressStorage[_key] = _value;
}
/**
* Maps a value of `bytes32` type to a given key.
* Only the owner can execute this function.
*/
function setBytes(bytes32 _key, bytes32 _value) external onlyCurrentOwner {
bytesStorage[_key] = _value;
}
/**
* Maps a value of `bool` type to a given key.
* Only the owner can execute this function.
*/
function setBool(bytes32 _key, bool _value) external onlyCurrentOwner {
boolStorage[_key] = _value;
}
/**
* Maps a value of `int256` type to a given key.
* Only the owner can execute this function.
*/
function setInt(bytes32 _key, int256 _value) external onlyCurrentOwner {
intStorage[_key] = _value;
}
// *** Delete Methods ***
/**
* Deletes the value of the `uint256` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteUint(bytes32 _key) external onlyCurrentOwner {
delete uIntStorage[_key];
}
/**
* Deletes the value of the `string` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteString(bytes32 _key) external onlyCurrentOwner {
delete stringStorage[_key];
}
/**
* Deletes the value of the `address` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteAddress(bytes32 _key) external onlyCurrentOwner {
delete addressStorage[_key];
}
/**
* Deletes the value of the `bytes32` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteBytes(bytes32 _key) external onlyCurrentOwner {
delete bytesStorage[_key];
}
/**
* Deletes the value of the `bool` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteBool(bytes32 _key) external onlyCurrentOwner {
delete boolStorage[_key];
}
/**
* Deletes the value of the `int256` type that mapped to the given key.
* Only the owner can execute this function.
*/
function deleteInt(bytes32 _key) external onlyCurrentOwner {
delete intStorage[_key];
}
}
// File: contracts/src/common/storage/UsingStorage.sol
pragma solidity ^0.5.0;
/**
* Module for contrast handling EternalStorage.
*/
contract UsingStorage is Ownable {
address private _storage;
/**
* Modifier to verify that EternalStorage is set.
*/
modifier hasStorage() {
require(_storage != address(0), "storage is not set");
_;
}
/**
* Returns the set EternalStorage instance.
*/
function eternalStorage()
internal
view
hasStorage
returns (EternalStorage)
{
return EternalStorage(_storage);
}
/**
* Returns the set EternalStorage address.
*/
function getStorageAddress() external view hasStorage returns (address) {
return _storage;
}
/**
* Create a new EternalStorage contract.
* This function call will fail if the EternalStorage contract is already set.
* Also, only the owner can execute it.
*/
function createStorage() external onlyOwner {
require(_storage == address(0), "storage is set");
EternalStorage tmp = new EternalStorage();
_storage = address(tmp);
}
/**
* Assigns the EternalStorage contract that has already been created.
* Only the owner can execute this function.
*/
function setStorage(address _storageAddress) external onlyOwner {
_storage = _storageAddress;
}
/**
* Delegates the owner of the current EternalStorage contract.
* Only the owner can execute this function.
*/
function changeOwner(address newOwner) external onlyOwner {
EternalStorage(_storage).changeOwner(newOwner);
}
}
// File: contracts/src/lockup/LockupStorage.sol
pragma solidity ^0.5.0;
contract LockupStorage is UsingStorage {
using SafeMath for uint256;
uint256 public constant basis = 100000000000000000000000000000000;
//AllValue
function setStorageAllValue(uint256 _value) internal {
bytes32 key = getStorageAllValueKey();
eternalStorage().setUint(key, _value);
}
function getStorageAllValue() public view returns (uint256) {
bytes32 key = getStorageAllValueKey();
return eternalStorage().getUint(key);
}
function getStorageAllValueKey() private pure returns (bytes32) {
return keccak256(abi.encodePacked("_allValue"));
}
//Value
function setStorageValue(
address _property,
address _sender,
uint256 _value
) internal {
bytes32 key = getStorageValueKey(_property, _sender);
eternalStorage().setUint(key, _value);
}
function getStorageValue(address _property, address _sender)
public
view
returns (uint256)
{
bytes32 key = getStorageValueKey(_property, _sender);
return eternalStorage().getUint(key);
}
function getStorageValueKey(address _property, address _sender)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_value", _property, _sender));
}
//PropertyValue
function setStoragePropertyValue(address _property, uint256 _value)
internal
{
bytes32 key = getStoragePropertyValueKey(_property);
eternalStorage().setUint(key, _value);
}
function getStoragePropertyValue(address _property)
public
view
returns (uint256)
{
bytes32 key = getStoragePropertyValueKey(_property);
return eternalStorage().getUint(key);
}
function getStoragePropertyValueKey(address _property)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_propertyValue", _property));
}
//WithdrawalStatus
function setStorageWithdrawalStatus(
address _property,
address _from,
uint256 _value
) internal {
bytes32 key = getStorageWithdrawalStatusKey(_property, _from);
eternalStorage().setUint(key, _value);
}
function getStorageWithdrawalStatus(address _property, address _from)
public
view
returns (uint256)
{
bytes32 key = getStorageWithdrawalStatusKey(_property, _from);
return eternalStorage().getUint(key);
}
function getStorageWithdrawalStatusKey(address _property, address _sender)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_withdrawalStatus", _property, _sender)
);
}
//InterestPrice
function setStorageInterestPrice(address _property, uint256 _value)
internal
{
// The previously used function
// This function is only used in testing
eternalStorage().setUint(getStorageInterestPriceKey(_property), _value);
}
function getStorageInterestPrice(address _property)
public
view
returns (uint256)
{
return eternalStorage().getUint(getStorageInterestPriceKey(_property));
}
function getStorageInterestPriceKey(address _property)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_interestTotals", _property));
}
//LastInterestPrice
function setStorageLastInterestPrice(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageLastInterestPriceKey(_property, _user),
_value
);
}
function getStorageLastInterestPrice(address _property, address _user)
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageLastInterestPriceKey(_property, _user)
);
}
function getStorageLastInterestPriceKey(address _property, address _user)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_lastLastInterestPrice", _property, _user)
);
}
//LastSameRewardsAmountAndBlock
function setStorageLastSameRewardsAmountAndBlock(
uint256 _amount,
uint256 _block
) internal {
uint256 record = _amount.mul(basis).add(_block);
eternalStorage().setUint(
getStorageLastSameRewardsAmountAndBlockKey(),
record
);
}
function getStorageLastSameRewardsAmountAndBlock()
public
view
returns (uint256 _amount, uint256 _block)
{
uint256 record = eternalStorage().getUint(
getStorageLastSameRewardsAmountAndBlockKey()
);
uint256 amount = record.div(basis);
uint256 blockNumber = record.sub(amount.mul(basis));
return (amount, blockNumber);
}
function getStorageLastSameRewardsAmountAndBlockKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_LastSameRewardsAmountAndBlock"));
}
//CumulativeGlobalRewards
function setStorageCumulativeGlobalRewards(uint256 _value) internal {
eternalStorage().setUint(
getStorageCumulativeGlobalRewardsKey(),
_value
);
}
function getStorageCumulativeGlobalRewards() public view returns (uint256) {
return eternalStorage().getUint(getStorageCumulativeGlobalRewardsKey());
}
function getStorageCumulativeGlobalRewardsKey()
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_cumulativeGlobalRewards"));
}
//LastCumulativeGlobalReward
function setStorageLastCumulativeGlobalReward(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageLastCumulativeGlobalRewardKey(_property, _user),
_value
);
}
function getStorageLastCumulativeGlobalReward(
address _property,
address _user
) public view returns (uint256) {
return
eternalStorage().getUint(
getStorageLastCumulativeGlobalRewardKey(_property, _user)
);
}
function getStorageLastCumulativeGlobalRewardKey(
address _property,
address _user
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"_LastCumulativeGlobalReward",
_property,
_user
)
);
}
//LastCumulativePropertyInterest
function setStorageLastCumulativePropertyInterest(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStorageLastCumulativePropertyInterestKey(_property, _user),
_value
);
}
function getStorageLastCumulativePropertyInterest(
address _property,
address _user
) public view returns (uint256) {
return
eternalStorage().getUint(
getStorageLastCumulativePropertyInterestKey(_property, _user)
);
}
function getStorageLastCumulativePropertyInterestKey(
address _property,
address _user
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"_lastCumulativePropertyInterest",
_property,
_user
)
);
}
//CumulativeLockedUpUnitAndBlock
function setStorageCumulativeLockedUpUnitAndBlock(
address _addr,
uint256 _unit,
uint256 _block
) internal {
uint256 record = _unit.mul(basis).add(_block);
eternalStorage().setUint(
getStorageCumulativeLockedUpUnitAndBlockKey(_addr),
record
);
}
function getStorageCumulativeLockedUpUnitAndBlock(address _addr)
public
view
returns (uint256 _unit, uint256 _block)
{
uint256 record = eternalStorage().getUint(
getStorageCumulativeLockedUpUnitAndBlockKey(_addr)
);
uint256 unit = record.div(basis);
uint256 blockNumber = record.sub(unit.mul(basis));
return (unit, blockNumber);
}
function getStorageCumulativeLockedUpUnitAndBlockKey(address _addr)
private
pure
returns (bytes32)
{
return
keccak256(
abi.encodePacked("_cumulativeLockedUpUnitAndBlock", _addr)
);
}
//CumulativeLockedUpValue
function setStorageCumulativeLockedUpValue(address _addr, uint256 _value)
internal
{
eternalStorage().setUint(
getStorageCumulativeLockedUpValueKey(_addr),
_value
);
}
function getStorageCumulativeLockedUpValue(address _addr)
public
view
returns (uint256)
{
return
eternalStorage().getUint(
getStorageCumulativeLockedUpValueKey(_addr)
);
}
function getStorageCumulativeLockedUpValueKey(address _addr)
private
pure
returns (bytes32)
{
return keccak256(abi.encodePacked("_cumulativeLockedUpValue", _addr));
}
//PendingWithdrawal
function setStoragePendingInterestWithdrawal(
address _property,
address _user,
uint256 _value
) internal {
eternalStorage().setUint(
getStoragePendingInterestWithdrawalKey(_property, _user),
_value
);
}
function getStoragePendingInterestWithdrawal(
address _property,
address _user
) public view returns (uint256) {
return
eternalStorage().getUint(
getStoragePendingInterestWithdrawalKey(_property, _user)
);
}
function getStoragePendingInterestWithdrawalKey(
address _property,
address _user
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked("_pendingInterestWithdrawal", _property, _user)
);
}
//DIP4GenesisBlock
function setStorageDIP4GenesisBlock(uint256 _block) internal {
eternalStorage().setUint(getStorageDIP4GenesisBlockKey(), _block);
}
function getStorageDIP4GenesisBlock() public view returns (uint256) {
return eternalStorage().getUint(getStorageDIP4GenesisBlockKey());
}
function getStorageDIP4GenesisBlockKey() private pure returns (bytes32) {
return keccak256(abi.encodePacked("_dip4GenesisBlock"));
}
//LastCumulativeLockedUpAndBlock
function setStorageLastCumulativeLockedUpAndBlock(
address _property,
address _user,
uint256 _cLocked,
uint256 _block
) internal {
uint256 record = _cLocked.mul(basis).add(_block);
eternalStorage().setUint(
getStorageLastCumulativeLockedUpAndBlockKey(_property, _user),
record
);
}
function getStorageLastCumulativeLockedUpAndBlock(
address _property,
address _user
) public view returns (uint256 _cLocked, uint256 _block) {
uint256 record = eternalStorage().getUint(
getStorageLastCumulativeLockedUpAndBlockKey(_property, _user)
);
uint256 cLocked = record.div(basis);
uint256 blockNumber = record.sub(cLocked.mul(basis));
return (cLocked, blockNumber);
}
function getStorageLastCumulativeLockedUpAndBlockKey(
address _property,
address _user
) private pure returns (bytes32) {
return
keccak256(
abi.encodePacked(
"_lastCumulativeLockedUpAndBlock",
_property,
_user
)
);
}
}
// File: contracts/src/allocator/IAllocator.sol
pragma solidity ^0.5.0;
contract IAllocator {
function calculateMaxRewardsPerBlock() public view returns (uint256);
function beforeBalanceChange(
address _property,
address _from,
address _to
// solium-disable-next-line indentation
) external;
}
// File: contracts/src/lockup/Lockup.sol
pragma solidity ^0.5.0;
// prettier-ignore
/**
* A contract that manages the staking of DEV tokens and calculates rewards.
* Staking and the following mechanism determines that reward calculation.
*
* Variables:
* -`M`: Maximum mint amount per block determined by Allocator contract
* -`B`: Number of blocks during staking
* -`P`: Total number of staking locked up in a Property contract
* -`S`: Total number of staking locked up in all Property contracts
* -`U`: Number of staking per account locked up in a Property contract
*
* Formula:
* Staking Rewards = M * B * (P / S) * (U / P)
*
* Note:
* -`M`, `P` and `S` vary from block to block, and the variation cannot be predicted.
* -`B` is added every time the Ethereum block is created.
* - Only `U` and `B` are predictable variables.
* - As `M`, `P` and `S` cannot be observed from a staker, the "cumulative sum" is often used to calculate ratio variation with history.
* - Reward withdrawal always withdraws the total withdrawable amount.
*
* Scenario:
* - Assume `M` is fixed at 500
* - Alice stakes 100 DEV on Property-A (Alice's staking state on Property-A: `M`=500, `B`=0, `P`=100, `S`=100, `U`=100)
* - After 10 blocks, Bob stakes 60 DEV on Property-B (Alice's staking state on Property-A: `M`=500, `B`=10, `P`=100, `S`=160, `U`=100)
* - After 10 blocks, Carol stakes 40 DEV on Property-A (Alice's staking state on Property-A: `M`=500, `B`=20, `P`=140, `S`=200, `U`=100)
* - After 10 blocks, Alice withdraws Property-A staking reward. The reward at this time is 5000 DEV (10 blocks * 500 DEV) + 3125 DEV (10 blocks * 62.5% * 500 DEV) + 2500 DEV (10 blocks * 50% * 500 DEV).
*/
contract Lockup is ILockup, UsingConfig, UsingValidator, LockupStorage {
using SafeMath for uint256;
using Decimals for uint256;
event Lockedup(address _from, address _property, uint256 _value);
/**
* Initialize the passed address as AddressConfig address.
*/
// solium-disable-next-line no-empty-blocks
constructor(address _config) public UsingConfig(_config) {}
/**
* Adds staking.
* Only the Dev contract can execute this function.
*/
function lockup(
address _from,
address _property,
uint256 _value
) external {
/**
* Validates the sender is Dev contract.
*/
addressValidator().validateAddress(msg.sender, config().token());
/**
* Validates the target of staking is included Property set.
*/
addressValidator().validateGroup(_property, config().propertyGroup());
require(_value != 0, "illegal lockup value");
/**
* Validates the passed Property has greater than 1 asset.
*/
require(
IMetricsGroup(config().metricsGroup()).hasAssets(_property),
"unable to stake to unauthenticated property"
);
/**
* Refuses new staking when after cancel staking and until release it.
*/
bool isWaiting = getStorageWithdrawalStatus(_property, _from) != 0;
require(isWaiting == false, "lockup is already canceled");
/**
* Since the reward per block that can be withdrawn will change with the addition of staking,
* saves the undrawn withdrawable reward before addition it.
*/
updatePendingInterestWithdrawal(_property, _from);
/**
* Saves the variables at the time of staking to prepare for reward calculation.
*/
(, , , uint256 interest, ) = difference(_property, 0);
updateStatesAtLockup(_property, _from, interest);
/**
* Saves variables that should change due to the addition of staking.
*/
updateValues(true, _from, _property, _value);
emit Lockedup(_from, _property, _value);
}
/**
* Cancel staking.
* The staking amount can be withdrawn after the blocks specified by `Policy.lockUpBlocks` have passed.
*/
function cancel(address _property) external {
/**
* Validates the target of staked is included Property set.
*/
addressValidator().validateGroup(_property, config().propertyGroup());
/**
* Validates the sender is staking to the target Property.
*/
require(hasValue(_property, msg.sender), "dev token is not locked");
/**
* Validates not already been canceled.
*/
bool isWaiting = getStorageWithdrawalStatus(_property, msg.sender) != 0;
require(isWaiting == false, "lockup is already canceled");
/**
* Get `Policy.lockUpBlocks`, add it to the current block number, and saves that block number in `WithdrawalStatus`.
* Staking is cannot release until the block number saved in `WithdrawalStatus` is reached.
*/
uint256 blockNumber = IPolicy(config().policy()).lockUpBlocks();
blockNumber = blockNumber.add(block.number);
setStorageWithdrawalStatus(_property, msg.sender, blockNumber);
}
/**
* Withdraw staking.
* Releases canceled staking and transfer the staked amount to the sender.
*/
function withdraw(address _property) external {
/**
* Validates the target of staked is included Property set.
*/
addressValidator().validateGroup(_property, config().propertyGroup());
/**
* Validates the block number reaches the block number where staking can be released.
*/
require(possible(_property, msg.sender), "waiting for release");
/**
* Validates the sender is staking to the target Property.
*/
uint256 lockedUpValue = getStorageValue(_property, msg.sender);
require(lockedUpValue != 0, "dev token is not locked");
/**
* Since the increase of rewards will stop with the release of the staking,
* saves the undrawn withdrawable reward before releasing it.
*/
updatePendingInterestWithdrawal(_property, msg.sender);
/**
* Transfer the staked amount to the sender.
*/
IProperty(_property).withdraw(msg.sender, lockedUpValue);
/**
* Saves variables that should change due to the canceling staking..
*/
updateValues(false, msg.sender, _property, lockedUpValue);
/**
* Sets the staked amount to 0.
*/
setStorageValue(_property, msg.sender, 0);
/**
* Sets the cancellation status to not have.
*/
setStorageWithdrawalStatus(_property, msg.sender, 0);
}
/**
* Returns the current staking amount, and the block number in which the recorded last.
* These values are used to calculate the cumulative sum of the staking.
*/
function getCumulativeLockedUpUnitAndBlock(address _property)
private
view
returns (uint256 _unit, uint256 _block)
{
/**
* Get the current staking amount and the last recorded block number from the `CumulativeLockedUpUnitAndBlock` storage.
* If the last recorded block number is not 0, it is returns as it is.
*/
(
uint256 unit,
uint256 lastBlock
) = getStorageCumulativeLockedUpUnitAndBlock(_property);
if (lastBlock > 0) {
return (unit, lastBlock);
}
/**
* If the last recorded block number is 0, this function falls back as already staked before the current specs (before DIP4).
* More detail for DIP4: https://github.com/dev-protocol/DIPs/issues/4
*
* When the passed address is 0, the caller wants to know the total staking amount on the protocol,
* so gets the total staking amount from `AllValue` storage.
* When the address is other than 0, the caller wants to know the staking amount of a Property,
* so gets the staking amount from the `PropertyValue` storage.
*/
unit = _property == address(0)
? getStorageAllValue()
: getStoragePropertyValue(_property);
/**
* Staking pre-DIP4 will be treated as staked simultaneously with the DIP4 release.
* Therefore, the last recorded block number is the same as the DIP4 release block.
*/
lastBlock = getStorageDIP4GenesisBlock();
return (unit, lastBlock);
}
/**
* Returns the cumulative sum of the staking on passed address, the current staking amount,
* and the block number in which the recorded last.
* The latest cumulative sum can be calculated using the following formula:
* (current staking amount) * (current block number - last recorded block number) + (last cumulative sum)
*/
function getCumulativeLockedUp(address _property)
public
view
returns (
uint256 _value,
uint256 _unit,
uint256 _block
)
{
/**
* Gets the current staking amount and the last recorded block number from the `getCumulativeLockedUpUnitAndBlock` function.
*/
(uint256 unit, uint256 lastBlock) = getCumulativeLockedUpUnitAndBlock(
_property
);
/**
* Gets the last cumulative sum of the staking from `CumulativeLockedUpValue` storage.
*/
uint256 lastValue = getStorageCumulativeLockedUpValue(_property);
/**
* Returns the latest cumulative sum, current staking amount as a unit, and last recorded block number.
*/
return (
lastValue.add(unit.mul(block.number.sub(lastBlock))),
unit,
lastBlock
);
}
/**
* Returns the cumulative sum of the staking on the protocol totally, the current staking amount,
* and the block number in which the recorded last.
*/
function getCumulativeLockedUpAll()
public
view
returns (
uint256 _value,
uint256 _unit,
uint256 _block
)
{
/**
* If the 0 address is passed as a key, it indicates the entire protocol.
*/
return getCumulativeLockedUp(address(0));
}
/**
* Updates the `CumulativeLockedUpValue` and `CumulativeLockedUpUnitAndBlock` storage.
* This function expected to executes when the amount of staking as a unit changes.
*/
function updateCumulativeLockedUp(
bool _addition,
address _property,
uint256 _unit
) private {
address zero = address(0);
/**
* Gets the cumulative sum of the staking amount, staking amount, and last recorded block number for the passed Property address.
*/
(uint256 lastValue, uint256 lastUnit, ) = getCumulativeLockedUp(
_property
);
/**
* Gets the cumulative sum of the staking amount, staking amount, and last recorded block number for the protocol total.
*/
(uint256 lastValueAll, uint256 lastUnitAll, ) = getCumulativeLockedUp(
zero
);
/**
* Adds or subtracts the staking amount as a new unit to the cumulative sum of the staking for the passed Property address.
*/
setStorageCumulativeLockedUpValue(
_property,
_addition ? lastValue.add(_unit) : lastValue.sub(_unit)
);
/**
* Adds or subtracts the staking amount as a new unit to the cumulative sum of the staking for the protocol total.
*/
setStorageCumulativeLockedUpValue(
zero,
_addition ? lastValueAll.add(_unit) : lastValueAll.sub(_unit)
);
/**
* Adds or subtracts the staking amount to the staking unit for the passed Property address.
* Also, record the latest block number.
*/
setStorageCumulativeLockedUpUnitAndBlock(
_property,
_addition ? lastUnit.add(_unit) : lastUnit.sub(_unit),
block.number
);
/**
* Adds or subtracts the staking amount to the staking unit for the protocol total.
* Also, record the latest block number.
*/
setStorageCumulativeLockedUpUnitAndBlock(
zero,
_addition ? lastUnitAll.add(_unit) : lastUnitAll.sub(_unit),
block.number
);
}
/**
* Updates cumulative sum of the maximum mint amount calculated by Allocator contract, the latest maximum mint amount per block,
* and the last recorded block number.
* The cumulative sum of the maximum mint amount is always added.
* By recording that value when the staker last stakes, the difference from the when the staker stakes can be calculated.
*/
function update() public {
/**
* Gets the cumulative sum of the maximum mint amount and the maximum mint number per block.
*/
(uint256 _nextRewards, uint256 _amount) = dry();
/**
* Records each value and the latest block number.
*/
setStorageCumulativeGlobalRewards(_nextRewards);
setStorageLastSameRewardsAmountAndBlock(_amount, block.number);
}
/**
* Updates the cumulative sum of the maximum mint amount when staking, the cumulative sum of staker reward as an interest of the target Property
* and the cumulative staking amount, and the latest block number.
*/
function updateStatesAtLockup(
address _property,
address _user,
uint256 _interest
) private {
/**
* Gets the cumulative sum of the maximum mint amount.
*/
(uint256 _reward, ) = dry();
/**
* Records each value and the latest block number.
*/
if (isSingle(_property, _user)) {
setStorageLastCumulativeGlobalReward(_property, _user, _reward);
}
setStorageLastCumulativePropertyInterest(_property, _user, _interest);
(uint256 cLocked, , ) = getCumulativeLockedUp(_property);
setStorageLastCumulativeLockedUpAndBlock(
_property,
_user,
cLocked,
block.number
);
}
/**
* Returns the last cumulative staking amount of the passed Property address and the last recorded block number.
*/
function getLastCumulativeLockedUpAndBlock(address _property, address _user)
private
view
returns (uint256 _cLocked, uint256 _block)
{
/**
* Gets the values from `LastCumulativeLockedUpAndBlock` storage.
*/
(
uint256 cLocked,
uint256 blockNumber
) = getStorageLastCumulativeLockedUpAndBlock(_property, _user);
/**
* When the last recorded block number is 0, the block number at the time of the DIP4 release is returned as being staked at the same time as the DIP4 release.
* More detail for DIP4: https://github.com/dev-protocol/DIPs/issues/4
*/
if (blockNumber == 0) {
blockNumber = getStorageDIP4GenesisBlock();
}
return (cLocked, blockNumber);
}
/**
* Referring to the values recorded in each storage to returns the latest cumulative sum of the maximum mint amount and the latest maximum mint amount per block.
*/
function dry()
private
view
returns (uint256 _nextRewards, uint256 _amount)
{
/**
* Gets the latest mint amount per block from Allocator contract.
*/
uint256 rewardsAmount = IAllocator(config().allocator())
.calculateMaxRewardsPerBlock();
/**
* Gets the maximum mint amount per block, and the last recorded block number from `LastSameRewardsAmountAndBlock` storage.
*/
(
uint256 lastAmount,
uint256 lastBlock
) = getStorageLastSameRewardsAmountAndBlock();
/**
* If the recorded maximum mint amount per block and the result of the Allocator contract are different,
* the result of the Allocator contract takes precedence as a maximum mint amount per block.
*/
uint256 lastMaxRewards = lastAmount == rewardsAmount
? rewardsAmount
: lastAmount;
/**
* Calculates the difference between the latest block number and the last recorded block number.
*/
uint256 blocks = lastBlock > 0 ? block.number.sub(lastBlock) : 0;
/**
* Adds the calculated new cumulative maximum mint amount to the recorded cumulative maximum mint amount.
*/
uint256 additionalRewards = lastMaxRewards.mul(blocks);
uint256 nextRewards = getStorageCumulativeGlobalRewards().add(
additionalRewards
);
/**
* Returns the latest theoretical cumulative sum of maximum mint amount and maximum mint amount per block.
*/
return (nextRewards, rewardsAmount);
}
/**
* Returns the latest theoretical cumulative sum of maximum mint amount, the holder's reward of the passed Property address and its unit price,
* and the staker's reward as interest and its unit price.
* The latest theoretical cumulative sum of maximum mint amount is got from `dry` function.
* The Holder's reward is a staking(delegation) reward received by the holder of the Property contract(token) according to the share.
* The unit price of the holder's reward is the reward obtained per 1 piece of Property contract(token).
* The staker rewards are rewards for staking users.
* The unit price of the staker reward is the reward per DEV token 1 piece that is staking.
*/
function difference(address _property, uint256 _lastReward)
public
view
returns (
uint256 _reward,
uint256 _holdersAmount,
uint256 _holdersPrice,
uint256 _interestAmount,
uint256 _interestPrice
)
{
/**
* Gets the cumulative sum of the maximum mint amount.
*/
(uint256 rewards, ) = dry();
/**
* Gets the cumulative sum of the staking amount of the passed Property address and
* the cumulative sum of the staking amount of the protocol total.
*/
(uint256 valuePerProperty, , ) = getCumulativeLockedUp(_property);
(uint256 valueAll, , ) = getCumulativeLockedUpAll();
/**
* Calculates the amount of reward that can be received by the Property from the ratio of the cumulative sum of the staking amount of the Property address
* and the cumulative sum of the staking amount of the protocol total.
* If the past cumulative sum of the maximum mint amount passed as the second argument is 1 or more,
* this result is the difference from that cumulative sum.
*/
uint256 propertyRewards = rewards.sub(_lastReward).mul(
valuePerProperty.mulBasis().outOf(valueAll)
);
/**
* Gets the staking amount and total supply of the Property and calls `Policy.holdersShare` function to calculates
* the holder's reward amount out of the total reward amount.
*/
uint256 lockedUpPerProperty = getStoragePropertyValue(_property);
uint256 totalSupply = ERC20Mintable(_property).totalSupply();
uint256 holders = IPolicy(config().policy()).holdersShare(
propertyRewards,
lockedUpPerProperty
);
/**
* The total rewards amount minus the holder reward amount is the staker rewards as an interest.
*/
uint256 interest = propertyRewards.sub(holders);
/**
* Returns each value and a unit price of each reward.
*/
return (
rewards,
holders,
holders.div(totalSupply),
interest,
lockedUpPerProperty > 0 ? interest.div(lockedUpPerProperty) : 0
);
}
/**
* Returns the staker reward as interest.
*/
function _calculateInterestAmount(address _property, address _user)
private
view
returns (uint256)
{
/**
* Gets the cumulative sum of the staking amount, current staking amount, and last recorded block number of the Property.
*/
(
uint256 cLockProperty,
uint256 unit,
uint256 lastBlock
) = getCumulativeLockedUp(_property);
/**
* Gets the cumulative sum of staking amount and block number of Property when the user staked.
*/
(
uint256 lastCLocked,
uint256 lastBlockUser
) = getLastCumulativeLockedUpAndBlock(_property, _user);
/**
* Get the amount the user is staking for the Property.
*/
uint256 lockedUpPerAccount = getStorageValue(_property, _user);
/**
* Gets the cumulative sum of the Property's staker reward when the user staked.
*/
uint256 lastInterest = getStorageLastCumulativePropertyInterest(
_property,
_user
);
/**
* Calculates the cumulative sum of the staking amount from the time the user staked to the present.
* It can be calculated by multiplying the staking amount by the number of elapsed blocks.
*/
uint256 cLockUser = lockedUpPerAccount.mul(
block.number.sub(lastBlockUser)
);
/**
* Determines if the user is the only staker to the Property.
*/
bool isOnly = unit == lockedUpPerAccount && lastBlock <= lastBlockUser;
/**
* If the user is the Property's only staker and the first staker, and the only staker on the protocol:
*/
if (isSingle(_property, _user)) {
/**
* Passing the cumulative sum of the maximum mint amount when staked, to the `difference` function,
* gets the staker reward amount that the user can receive from the time of staking to the present.
* In the case of the staking is single, the ratio of the Property and the user account for 100% of the cumulative sum of the maximum mint amount,
* so the difference cannot be calculated with the value of `LastCumulativePropertyInterest`.
* Therefore, it is necessary to calculate the difference using the cumulative sum of the maximum mint amounts at the time of staked.
*/
(, , , , uint256 interestPrice) = difference(
_property,
getStorageLastCumulativeGlobalReward(_property, _user)
);
/**
* Returns the result after adjusted decimals to 10^18.
*/
uint256 result = interestPrice
.mul(lockedUpPerAccount)
.divBasis()
.divBasis();
return result;
/**
* If not the single but the only staker:
*/
} else if (isOnly) {
/**
* Pass 0 to the `difference` function to gets the Property's cumulative sum of the staker reward.
*/
(, , , uint256 interest, ) = difference(_property, 0);
/**
* Calculates the difference in rewards that can be received by subtracting the Property's cumulative sum of staker rewards at the time of staking.
*/
uint256 result = interest >= lastInterest
? interest.sub(lastInterest).divBasis().divBasis()
: 0;
return result;
}
/**
* If the user is the Property's not the first staker and not the only staker:
*/
/**
* Pass 0 to the `difference` function to gets the Property's cumulative sum of the staker reward.
*/
(, , , uint256 interest, ) = difference(_property, 0);
/**
* Calculates the share of rewards that can be received by the user among Property's staker rewards.
* "Cumulative sum of the staking amount of the Property at the time of staking" is subtracted from "cumulative sum of the staking amount of the Property",
* and calculates the cumulative sum of staking amounts from the time of staking to the present.
* The ratio of the "cumulative sum of staking amount from the time the user staked to the present" to that value is the share.
*/
uint256 share = cLockUser.outOf(cLockProperty.sub(lastCLocked));
/**
* If the Property's staker reward is greater than the value of the `CumulativePropertyInterest` storage,
* calculates the difference and multiply by the share.
* Otherwise, it returns 0.
*/
uint256 result = interest >= lastInterest
? interest
.sub(lastInterest)
.mul(share)
.divBasis()
.divBasis()
.divBasis()
: 0;
return result;
}
/**
* Returns the total rewards currently available for withdrawal. (For calling from inside the contract)
*/
function _calculateWithdrawableInterestAmount(
address _property,
address _user
) private view returns (uint256) {
/**
* If the passed Property has not authenticated, returns always 0.
*/
if (
IMetricsGroup(config().metricsGroup()).hasAssets(_property) == false
) {
return 0;
}
/**
* Gets the reward amount in saved without withdrawal.
*/
uint256 pending = getStoragePendingInterestWithdrawal(_property, _user);
/**
* Gets the reward amount of before DIP4.
*/
uint256 legacy = __legacyWithdrawableInterestAmount(_property, _user);
/**
* Gets the latest withdrawal reward amount.
*/
uint256 amount = _calculateInterestAmount(_property, _user);
/**
* Returns the sum of all values.
*/
uint256 withdrawableAmount = amount
.add(pending) // solium-disable-next-line indentation
.add(legacy);
return withdrawableAmount;
}
/**
* Returns the total rewards currently available for withdrawal. (For calling from external of the contract)
*/
function calculateWithdrawableInterestAmount(
address _property,
address _user
) public view returns (uint256) {
uint256 amount = _calculateWithdrawableInterestAmount(_property, _user);
return amount;
}
/**
* Withdraws staking reward as an interest.
*/
function withdrawInterest(address _property) external {
/**
* Validates the target of staking is included Property set.
*/
addressValidator().validateGroup(_property, config().propertyGroup());
/**
* Gets the withdrawable amount.
*/
uint256 value = _calculateWithdrawableInterestAmount(
_property,
msg.sender
);
/**
* Gets the cumulative sum of staker rewards of the passed Property address.
*/
(, , , uint256 interest, ) = difference(_property, 0);
/**
* Validates rewards amount there are 1 or more.
*/
require(value > 0, "your interest amount is 0");
/**
* Sets the unwithdrawn reward amount to 0.
*/
setStoragePendingInterestWithdrawal(_property, msg.sender, 0);
/**
* Creates a Dev token instance.
*/
ERC20Mintable erc20 = ERC20Mintable(config().token());
/**
* Updates the staking status to avoid double rewards.
*/
updateStatesAtLockup(_property, msg.sender, interest);
__updateLegacyWithdrawableInterestAmount(_property, msg.sender);
/**
* Mints the reward.
*/
require(erc20.mint(msg.sender, value), "dev mint failed");
/**
* Since the total supply of tokens has changed, updates the latest maximum mint amount.
*/
update();
}
/**
* Status updates with the addition or release of staking.
*/
function updateValues(
bool _addition,
address _account,
address _property,
uint256 _value
) private {
/**
* If added staking:
*/
if (_addition) {
/**
* Updates the cumulative sum of the staking amount of the passed Property and the cumulative amount of the staking amount of the protocol total.
*/
updateCumulativeLockedUp(true, _property, _value);
/**
* Updates the current staking amount of the protocol total.
*/
addAllValue(_value);
/**
* Updates the current staking amount of the Property.
*/
addPropertyValue(_property, _value);
/**
* Updates the user's current staking amount in the Property.
*/
addValue(_property, _account, _value);
/**
* If released staking:
*/
} else {
/**
* Updates the cumulative sum of the staking amount of the passed Property and the cumulative amount of the staking amount of the protocol total.
*/
updateCumulativeLockedUp(false, _property, _value);
/**
* Updates the current staking amount of the protocol total.
*/
subAllValue(_value);
/**
* Updates the current staking amount of the Property.
*/
subPropertyValue(_property, _value);
}
/**
* Since each staking amount has changed, updates the latest maximum mint amount.
*/
update();
}
/**
* Returns the staking amount of the protocol total.
*/
function getAllValue() external view returns (uint256) {
return getStorageAllValue();
}
/**
* Adds the staking amount of the protocol total.
*/
function addAllValue(uint256 _value) private {
uint256 value = getStorageAllValue();
value = value.add(_value);
setStorageAllValue(value);
}
/**
* Subtracts the staking amount of the protocol total.
*/
function subAllValue(uint256 _value) private {
uint256 value = getStorageAllValue();
value = value.sub(_value);
setStorageAllValue(value);
}
/**
* Returns the user's staking amount in the Property.
*/
function getValue(address _property, address _sender)
external
view
returns (uint256)
{
return getStorageValue(_property, _sender);
}
/**
* Adds the user's staking amount in the Property.
*/
function addValue(
address _property,
address _sender,
uint256 _value
) private {
uint256 value = getStorageValue(_property, _sender);
value = value.add(_value);
setStorageValue(_property, _sender, value);
}
/**
* Returns whether the user is staking in the Property.
*/
function hasValue(address _property, address _sender)
private
view
returns (bool)
{
uint256 value = getStorageValue(_property, _sender);
return value != 0;
}
/**
* Returns whether a single user has all staking share.
* This value is true when only one Property and one user is historically the only staker.
*/
function isSingle(address _property, address _user)
private
view
returns (bool)
{
uint256 perAccount = getStorageValue(_property, _user);
(uint256 cLockProperty, uint256 unitProperty, ) = getCumulativeLockedUp(
_property
);
(uint256 cLockTotal, , ) = getCumulativeLockedUpAll();
return perAccount == unitProperty && cLockProperty == cLockTotal;
}
/**
* Returns the staking amount of the Property.
*/
function getPropertyValue(address _property)
external
view
returns (uint256)
{
return getStoragePropertyValue(_property);
}
/**
* Adds the staking amount of the Property.
*/
function addPropertyValue(address _property, uint256 _value) private {
uint256 value = getStoragePropertyValue(_property);
value = value.add(_value);
setStoragePropertyValue(_property, value);
}
/**
* Subtracts the staking amount of the Property.
*/
function subPropertyValue(address _property, uint256 _value) private {
uint256 value = getStoragePropertyValue(_property);
uint256 nextValue = value.sub(_value);
setStoragePropertyValue(_property, nextValue);
}
/**
* Saves the latest reward amount as an undrawn amount.
*/
function updatePendingInterestWithdrawal(address _property, address _user)
private
{
/**
* Gets the latest reward amount.
*/
uint256 withdrawableAmount = _calculateWithdrawableInterestAmount(
_property,
_user
);
/**
* Saves the amount to `PendingInterestWithdrawal` storage.
*/
setStoragePendingInterestWithdrawal(
_property,
_user,
withdrawableAmount
);
/**
* Updates the reward amount of before DIP4 to prevent further addition it.
*/
__updateLegacyWithdrawableInterestAmount(_property, _user);
}
/**
* Returns whether the staking can be released.
*/
function possible(address _property, address _from)
private
view
returns (bool)
{
uint256 blockNumber = getStorageWithdrawalStatus(_property, _from);
if (blockNumber == 0) {
return false;
}
if (blockNumber <= block.number) {
return true;
} else {
if (IPolicy(config().policy()).lockUpBlocks() == 1) {
return true;
}
}
return false;
}
/**
* Returns the reward amount of the calculation model before DIP4.
* It can be calculated by subtracting "the last cumulative sum of reward unit price" from
* "the current cumulative sum of reward unit price," and multiplying by the staking amount.
*/
function __legacyWithdrawableInterestAmount(
address _property,
address _user
) private view returns (uint256) {
uint256 _last = getStorageLastInterestPrice(_property, _user);
uint256 price = getStorageInterestPrice(_property);
uint256 priceGap = price.sub(_last);
uint256 lockedUpValue = getStorageValue(_property, _user);
uint256 value = priceGap.mul(lockedUpValue);
return value.divBasis();
}
/**
* Updates and treats the reward of before DIP4 as already received.
*/
function __updateLegacyWithdrawableInterestAmount(
address _property,
address _user
) private {
uint256 interestPrice = getStorageInterestPrice(_property);
if (getStorageLastInterestPrice(_property, _user) != interestPrice) {
setStorageLastInterestPrice(_property, _user, interestPrice);
}
}
/**
* Updates the block number of the time of DIP4 release.
*/
function setDIP4GenesisBlock(uint256 _block) external onlyOwner {
/**
* Validates the value is not set.
*/
require(getStorageDIP4GenesisBlock() == 0, "already set the value");
/**
* Sets the value.
*/
setStorageDIP4GenesisBlock(_block);
}
}
// File: contracts/src/dev/Dev.sol
pragma solidity ^0.5.0;
// prettier-ignore
// prettier-ignore
// prettier-ignore
/**
* The contract used as the DEV token.
* The DEV token is an ERC20 token used as the native token of the Dev Protocol.
* The DEV token is created by migration from its predecessor, the MVP, legacy DEV token. For that reason, the initial supply is 0.
* Also, mint will be performed based on the Allocator contract.
* When authenticated a new asset by the Market contracts, DEV token is burned as fees.
*/
contract Dev is
ERC20Detailed,
ERC20Mintable,
ERC20Burnable,
UsingConfig,
UsingValidator
{
/**
* Initialize the passed address as AddressConfig address.
* The token name is `Dev`, the token symbol is `DEV`, and the decimals is 18.
*/
constructor(address _config)
public
ERC20Detailed("Dev", "DEV", 18)
UsingConfig(_config)
{}
/**
* Staking DEV tokens.
* The transfer destination must always be included in the address set for Property tokens.
* This is because if the transfer destination is not a Property token, it is possible that the staked DEV token cannot be withdrawn.
*/
function deposit(address _to, uint256 _amount) external returns (bool) {
require(transfer(_to, _amount), "dev transfer failed");
lock(msg.sender, _to, _amount);
return true;
}
/**
* Staking DEV tokens by an allowanced address.
* The transfer destination must always be included in the address set for Property tokens.
* This is because if the transfer destination is not a Property token, it is possible that the staked DEV token cannot be withdrawn.
*/
function depositFrom(
address _from,
address _to,
uint256 _amount
) external returns (bool) {
require(transferFrom(_from, _to, _amount), "dev transferFrom failed");
lock(_from, _to, _amount);
return true;
}
/**
* Burn the DEV tokens as an authentication fee.
* Only Market contracts can execute this function.
*/
function fee(address _from, uint256 _amount) external returns (bool) {
addressValidator().validateGroup(msg.sender, config().marketGroup());
_burn(_from, _amount);
return true;
}
/**
* Call `Lockup.lockup` to execute staking.
*/
function lock(
address _from,
address _to,
uint256 _amount
) private {
Lockup(config().lockup()).lockup(_from, _to, _amount);
}
}
// File: contracts/src/market/Market.sol
pragma solidity ^0.5.0;
/**
* A user-proposable contract for authenticating and associating assets with Property.
* A user deploys a contract that inherits IMarketBehavior and creates this Market contract with the MarketFactory contract.
*/
contract Market is UsingConfig, IMarket, UsingValidator {
using SafeMath for uint256;
bool public enabled;
address public behavior;
uint256 public votingEndBlockNumber;
uint256 public issuedMetrics;
mapping(bytes32 => bool) private idMap;
mapping(address => bytes32) private idHashMetricsMap;
/**
* Initialize the passed address as AddressConfig address and user-proposed contract.
*/
constructor(address _config, address _behavior)
public
UsingConfig(_config)
{
/**
* Validates the sender is MarketFactory contract.
*/
addressValidator().validateAddress(
msg.sender,
config().marketFactory()
);
/**
* Stores the contract address proposed by a user as an internal variable.
*/
behavior = _behavior;
/**
* By default this contract is disabled.
*/
enabled = false;
/**
* Sets the period during which voting by voters can be accepted.
* This period is determined by `Policy.marketVotingBlocks`.
*/
uint256 marketVotingBlocks = IPolicy(config().policy())
.marketVotingBlocks();
votingEndBlockNumber = block.number.add(marketVotingBlocks);
}
/**
* Validates the sender is the passed Property's author.
*/
function propertyValidation(address _prop) private view {
addressValidator().validateAddress(
msg.sender,
IProperty(_prop).author()
);
require(enabled, "market is not enabled");
}
/**
* Modifier for validates the sender is the passed Property's author.
*/
modifier onlyPropertyAuthor(address _prop) {
propertyValidation(_prop);
_;
}
/**
* Modifier for validates the sender is the author of the Property associated with the passed Metrics contract.
*/
modifier onlyLinkedPropertyAuthor(address _metrics) {
address _prop = Metrics(_metrics).property();
propertyValidation(_prop);
_;
}
/**
* Activates this Market.
* Called from VoteCounter contract when passed the voting or from MarketFactory contract when the first Market is created.
*/
function toEnable() external {
addressValidator().validateAddresses(
msg.sender,
config().marketFactory(),
config().voteCounter()
);
enabled = true;
}
/**
* Bypass to IMarketBehavior.authenticate.
* Authenticates the new asset and proves that the Property author is the owner of the asset.
*/
function authenticate(
address _prop,
string memory _args1,
string memory _args2,
string memory _args3,
string memory _args4,
string memory _args5
) public onlyPropertyAuthor(_prop) returns (bool) {
uint256 len = bytes(_args1).length;
require(len > 0, "id is required");
return
IMarketBehavior(behavior).authenticate(
_prop,
_args1,
_args2,
_args3,
_args4,
_args5,
address(this),
msg.sender
);
}
/**
* Returns the authentication fee.
* Calculates by gets the staking amount of the Property to be authenticated
* and the total number of authenticated assets on the protocol, and calling `Policy.authenticationFee`.
*/
function getAuthenticationFee(address _property)
private
view
returns (uint256)
{
uint256 tokenValue = ILockup(config().lockup()).getPropertyValue(
_property
);
IPolicy policy = IPolicy(config().policy());
IMetricsGroup metricsGroup = IMetricsGroup(config().metricsGroup());
return
policy.authenticationFee(
metricsGroup.totalIssuedMetrics(),
tokenValue
);
}
/**
* A function that will be called back when the asset is successfully authenticated.
* There are cases where oracle is required for the authentication process, so the function is used callback style.
*/
function authenticatedCallback(address _property, bytes32 _idHash)
external
returns (address)
{
/**
* Validates the sender is the saved IMarketBehavior address.
*/
addressValidator().validateAddress(msg.sender, behavior);
require(enabled, "market is not enabled");
/**
* Validates the assets are not double authenticated.
*/
require(idMap[_idHash] == false, "id is duplicated");
idMap[_idHash] = true;
/**
* Gets the Property author address.
*/
address sender = IProperty(_property).author();
/**
* Publishes a new Metrics contract and associate the Property with the asset.
*/
IMetricsFactory metricsFactory = IMetricsFactory(
config().metricsFactory()
);
address metrics = metricsFactory.create(_property);
idHashMetricsMap[metrics] = _idHash;
/**
* Burn as a authentication fee.
*/
uint256 authenticationFee = getAuthenticationFee(_property);
require(
Dev(config().token()).fee(sender, authenticationFee),
"dev fee failed"
);
/**
* Adds the number of authenticated assets in this Market.
*/
issuedMetrics = issuedMetrics.add(1);
return metrics;
}
/**
* Release the authenticated asset.
*/
function deauthenticate(address _metrics)
external
onlyLinkedPropertyAuthor(_metrics)
{
/**
* Validates the passed Metrics address is authenticated in this Market.
*/
bytes32 idHash = idHashMetricsMap[_metrics];
require(idMap[idHash], "not authenticated");
/**
* Removes the authentication status from local variables.
*/
idMap[idHash] = false;
idHashMetricsMap[_metrics] = bytes32(0);
/**
* Removes the passed Metrics contract from the Metrics address set.
*/
IMetricsFactory metricsFactory = IMetricsFactory(
config().metricsFactory()
);
metricsFactory.destroy(_metrics);
/**
* Subtracts the number of authenticated assets in this Market.
*/
issuedMetrics = issuedMetrics.sub(1);
}
/**
* Bypass to IMarketBehavior.schema.
*/
function schema() external view returns (string memory) {
return IMarketBehavior(behavior).schema();
}
}
// File: contracts/src/market/IMarketGroup.sol
pragma solidity ^0.5.0;
contract IMarketGroup is IGroup {
function getCount() external view returns (uint256);
}
// File: contracts/src/market/MarketFactory.sol
pragma solidity ^0.5.0;
/**
* A factory contract that creates a new Market contract.
*/
contract MarketFactory is IMarketFactory, UsingConfig, UsingValidator {
event Create(address indexed _from, address _market);
/**
* Initialize the passed address as AddressConfig address.
*/
// solium-disable-next-line no-empty-blocks
constructor(address _config) public UsingConfig(_config) {}
/**
* Creates a new Market contract.
*/
function create(address _addr) external returns (address) {
/**
* Validates the passed address is not 0 address.
*/
addressValidator().validateIllegalAddress(_addr);
/**
* Creates a new Market contract with the passed address as the IMarketBehavior.
*/
Market market = new Market(address(config()), _addr);
/**
* Adds the created Market contract to the Market address set.
*/
address marketAddr = address(market);
IMarketGroup marketGroup = IMarketGroup(config().marketGroup());
marketGroup.addGroup(marketAddr);
/**
* For the first Market contract, it will be activated immediately.
* If not, the Market contract will be activated after a vote by the voters.
*/
if (marketGroup.getCount() == 1) {
market.toEnable();
}
emit Create(msg.sender, marketAddr);
return marketAddr;
}
}
|
* Initialize the passed address as AddressConfig address and user-proposed contract./
|
{
addressValidator().validateAddress(
msg.sender,
config().marketFactory()
);
behavior = _behavior;
enabled = false;
uint256 marketVotingBlocks = IPolicy(config().policy())
.marketVotingBlocks();
votingEndBlockNumber = block.number.add(marketVotingBlocks);
| 10,085,551 |
[
1,
7520,
326,
2275,
1758,
487,
5267,
809,
1758,
471,
729,
17,
685,
7423,
6835,
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,
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,
202,
95,
203,
202,
202,
2867,
5126,
7675,
5662,
1887,
12,
203,
1082,
202,
3576,
18,
15330,
16,
203,
1082,
202,
1425,
7675,
27151,
1733,
1435,
203,
202,
202,
1769,
203,
203,
202,
202,
31936,
273,
389,
31936,
31,
203,
203,
202,
202,
5745,
273,
629,
31,
203,
203,
202,
202,
11890,
5034,
13667,
58,
17128,
6450,
273,
467,
2582,
12,
1425,
7675,
5086,
10756,
203,
1082,
202,
18,
27151,
58,
17128,
6450,
5621,
203,
202,
202,
90,
17128,
1638,
1768,
1854,
273,
1203,
18,
2696,
18,
1289,
12,
27151,
58,
17128,
6450,
1769,
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.23;
// File: contracts/NokuPricingPlan.sol
/**
* @dev The NokuPricingPlan contract defines the responsibilities of a Noku pricing plan.
*/
contract NokuPricingPlan {
/**
* @dev Pay the fee for the service identified by the specified name.
* The fee amount shall already be approved by the client.
* @param serviceName The name of the target service.
* @param multiplier The multiplier of the base service fee to apply.
* @param client The client of the target service.
* @return true if fee has been paid.
*/
function payFee(bytes32 serviceName, uint256 multiplier, address client) public returns(bool paid);
/**
* @dev Get the usage fee for the service identified by the specified name.
* The returned fee amount shall be approved before using #payFee method.
* @param serviceName The name of the target service.
* @param multiplier The multiplier of the base service fee to apply.
* @return The amount to approve before really paying such fee.
*/
function usageFee(bytes32 serviceName, uint256 multiplier) public view returns(uint fee);
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: contracts/NokuTokenBurner.sol
contract BurnableERC20 is ERC20 {
function burn(uint256 amount) public returns (bool burned);
}
/**
* @dev The NokuTokenBurner contract has the responsibility to burn the configured fraction of received
* ERC20-compliant tokens and distribute the remainder to the configured wallet.
*/
contract NokuTokenBurner is Pausable {
using SafeMath for uint256;
event LogNokuTokenBurnerCreated(address indexed caller, address indexed wallet);
event LogBurningPercentageChanged(address indexed caller, uint256 indexed burningPercentage);
// The wallet receiving the unburnt tokens.
address public wallet;
// The percentage of tokens to burn after being received (range [0, 100])
uint256 public burningPercentage;
// The cumulative amount of burnt tokens.
uint256 public burnedTokens;
// The cumulative amount of tokens transferred back to the wallet.
uint256 public transferredTokens;
/**
* @dev Create a new NokuTokenBurner with predefined burning fraction.
* @param _wallet The wallet receiving the unburnt tokens.
*/
constructor(address _wallet) public {
require(_wallet != address(0), "_wallet is zero");
wallet = _wallet;
burningPercentage = 100;
emit LogNokuTokenBurnerCreated(msg.sender, _wallet);
}
/**
* @dev Change the percentage of tokens to burn after being received.
* @param _burningPercentage The percentage of tokens to be burnt.
*/
function setBurningPercentage(uint256 _burningPercentage) public onlyOwner {
require(0 <= _burningPercentage && _burningPercentage <= 100, "_burningPercentage not in [0, 100]");
require(_burningPercentage != burningPercentage, "_burningPercentage equal to current one");
burningPercentage = _burningPercentage;
emit LogBurningPercentageChanged(msg.sender, _burningPercentage);
}
/**
* @dev Called after burnable tokens has been transferred for burning.
* @param _token THe extended ERC20 interface supported by the sent tokens.
* @param _amount The amount of burnable tokens just arrived ready for burning.
*/
function tokenReceived(address _token, uint256 _amount) public whenNotPaused {
require(_token != address(0), "_token is zero");
require(_amount > 0, "_amount is zero");
uint256 amountToBurn = _amount.mul(burningPercentage).div(100);
if (amountToBurn > 0) {
assert(BurnableERC20(_token).burn(amountToBurn));
burnedTokens = burnedTokens.add(amountToBurn);
}
uint256 amountToTransfer = _amount.sub(amountToBurn);
if (amountToTransfer > 0) {
assert(BurnableERC20(_token).transfer(wallet, amountToTransfer));
transferredTokens = transferredTokens.add(amountToTransfer);
}
}
}
// File: contracts/NokuFlatPlan.sol
/**
* @dev The NokuFlatPlan contract implements a flat pricing plan, manageable by the contract owner.
*/
contract NokuFlatPlan is NokuPricingPlan, Ownable {
using SafeMath for uint256;
event LogNokuFlatPlanCreated(
address indexed caller,
uint256 indexed paymentInterval,
uint256 indexed flatFee,
address nokuMasterToken,
address tokenBurner
);
event LogPaymentIntervalChanged(address indexed caller, uint256 indexed paymentInterval);
event LogFlatFeeChanged(address indexed caller, uint256 indexed flatFee);
// The validity time interval of the flat subscription.
uint256 public paymentInterval;
// When the next payment is required as timestamp in seconds from Unix epoch
uint256 public nextPaymentTime;
// The fee amount expressed in NOKU tokens.
uint256 public flatFee;
// The NOKU utility token used for paying fee
address public nokuMasterToken;
// The contract responsible for burning the NOKU tokens paid as service fee
address public tokenBurner;
constructor(
uint256 _paymentInterval,
uint256 _flatFee,
address _nokuMasterToken,
address _tokenBurner
)
public
{
require(_paymentInterval != 0, "_paymentInterval is zero");
require(_flatFee != 0, "_flatFee is zero");
require(_nokuMasterToken != 0, "_nokuMasterToken is zero");
require(_tokenBurner != 0, "_tokenBurner is zero");
paymentInterval = _paymentInterval;
flatFee = _flatFee;
nokuMasterToken = _nokuMasterToken;
tokenBurner = _tokenBurner;
nextPaymentTime = block.timestamp;
emit LogNokuFlatPlanCreated(
msg.sender,
_paymentInterval,
_flatFee,
_nokuMasterToken,
_tokenBurner
);
}
function setPaymentInterval(uint256 _paymentInterval) public onlyOwner {
require(_paymentInterval != 0, "_paymentInterval is zero");
require(_paymentInterval != paymentInterval, "_paymentInterval equal to current one");
paymentInterval = _paymentInterval;
emit LogPaymentIntervalChanged(msg.sender, _paymentInterval);
}
function setFlatFee(uint256 _flatFee) public onlyOwner {
require(_flatFee != 0, "_flatFee is zero");
require(_flatFee != flatFee, "_flatFee equal to current one");
flatFee = _flatFee;
emit LogFlatFeeChanged(msg.sender, _flatFee);
}
function isValidService(bytes32 _serviceName) public pure returns(bool isValid) {
return _serviceName != 0;
}
/**
* @dev Defines the operation by checking if flat fee has been paid or not.
*/
function payFee(bytes32 _serviceName, uint256 _multiplier, address _client) public returns(bool paid) {
require(isValidService(_serviceName), "_serviceName in invalid");
require(_multiplier != 0, "_multiplier is zero");
require(_client != 0, "_client is zero");
require(block.timestamp < nextPaymentTime);
return true;
}
function usageFee(bytes32 /*_serviceName*/, uint256 /*_multiplier*/) public view returns(uint fee) {
return 0;
}
function paySubscription(address _client) public returns(bool paid) {
require(_client != 0, "_client is zero");
nextPaymentTime = nextPaymentTime.add(paymentInterval);
assert(ERC20(nokuMasterToken).transferFrom(_client, tokenBurner, flatFee));
NokuTokenBurner(tokenBurner).tokenReceived(nokuMasterToken, flatFee);
return true;
}
}
|
* @dev The NokuPricingPlan contract defines the responsibilities of a Noku pricing plan./
|
contract NokuPricingPlan {
function payFee(bytes32 serviceName, uint256 multiplier, address client) public returns(bool paid);
function usageFee(bytes32 serviceName, uint256 multiplier) public view returns(uint fee);
}
| 1,114,826 |
[
1,
1986,
423,
20924,
52,
1512,
310,
5365,
6835,
11164,
326,
7899,
24074,
434,
279,
423,
20924,
31765,
4995,
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,
16351,
423,
20924,
52,
1512,
310,
5365,
288,
203,
565,
445,
8843,
14667,
12,
3890,
1578,
6773,
16,
2254,
5034,
15027,
16,
1758,
1004,
13,
1071,
1135,
12,
6430,
30591,
1769,
203,
203,
565,
445,
4084,
14667,
12,
3890,
1578,
6773,
16,
2254,
5034,
15027,
13,
1071,
1476,
1135,
12,
11890,
14036,
1769,
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
] |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
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
// OpenZeppelin Contracts v4.4.0 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts 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
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./common/meta-transactions/ContentMixin.sol";
import "./common/meta-transactions/NativeMetaTransaction.sol";
contract OwnableDelegateProxy { }
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @title ERC1155Tradable
* ERC1155Tradable - ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin,
like _exists(), name(), symbol(), and totalSupply()
*/
contract ERC1155Tradable is ContextMixin, ERC1155, NativeMetaTransaction, Ownable {
using Strings for string;
using SafeMath for uint256;
address proxyRegistryAddress;
mapping (uint256 => address) public creators;
mapping (uint256 => uint256) public tokenSupply;
mapping (uint256 => string) customUri;
// Contract name
string public name;
// Contract symbol
string public symbol;
/**
* @dev Require _msgSender() to be the creator of the token id
*/
modifier creatorOnly(uint256 _id) {
require(creators[_id] == _msgSender(), "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED");
_;
}
/**
* @dev Require _msgSender() to own more than 0 of the token id
*/
modifier ownersOnly(uint256 _id) {
require(balanceOf(_msgSender(), _id) > 0, "ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED");
_;
}
constructor(
string memory _name,
string memory _symbol,
string memory _uri,
address _proxyRegistryAddress
) ERC1155(_uri) {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
_initializeEIP712(name);
}
function uri(
uint256 _id
) override public view returns (string memory) {
require(_exists(_id), "ERC1155Tradable#uri: NONEXISTENT_TOKEN");
// We have to convert string to bytes to check for existence
bytes memory customUriBytes = bytes(customUri[_id]);
if (customUriBytes.length > 0) {
return customUri[_id];
} else {
return super.uri(_id);
}
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(
uint256 _id
) public view returns (uint256) {
return tokenSupply[_id];
}
/**
* @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].
* @param _newURI New URI for all tokens
*/
function setURI(
string memory _newURI
) public onlyOwner {
_setURI(_newURI);
}
/**
* @dev Will update the base URI for the token
* @param _tokenId The token to update. _msgSender() must be its creator.
* @param _newURI New URI for the token.
*/
function setCustomURI(
uint256 _tokenId,
string memory _newURI
) public creatorOnly(_tokenId) {
customUri[_tokenId] = _newURI;
emit URI(_newURI, _tokenId);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* NOTE: remove onlyOwner if you want third parties to create new tokens on
* your contract (which may change your IDs)
* NOTE: The token id must be passed. This allows lazy creation of tokens or
* creating NFTs by setting the id's high bits with the method
* described in ERC1155 or to use ids representing values other than
* successive small integers. If you wish to create ids as successive
* small integers you can either subclass this class to count onchain
* or maintain the offchain cache of identifiers recommended in
* ERC1155 and calculate successive ids from that.
* @param _initialOwner address of the first owner of the token
* @param _id The id of the token to create (must not currenty exist).
* @param _initialSupply amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Data to pass if receiver is contract
* @return The newly created token ID
*/
function create(
address _initialOwner,
uint256 _id,
uint256 _initialSupply,
string memory _uri,
bytes memory _data
) public onlyOwner returns (uint256) {
require(!_exists(_id), "token _id already exists");
creators[_id] = _msgSender();
if (bytes(_uri).length > 0) {
customUri[_id] = _uri;
emit URI(_uri, _id);
}
_mint(_initialOwner, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
return _id;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) virtual public /* creatorOnly(_id) */ {
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] = tokenSupply[_id].add(_quantity);
}
/**
* @dev Mint tokens for each id in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _quantities Array of amounts of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _quantities,
bytes memory _data
) public {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 _id = _ids[i];
/* require(creators[_id] == _msgSender(), "ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED"); */
uint256 quantity = _quantities[i];
tokenSupply[_id] = tokenSupply[_id].add(quantity);
}
_mintBatch(_to, _ids, _quantities, _data);
}
/**
* @dev Change the creator address for given tokens
* @param _to Address of the new creator
* @param _ids Array of Token IDs to change creator
*/
function setCreator(
address _to,
uint256[] memory _ids
) public {
require(_to != address(0), "ERC1155Tradable#setCreator: INVALID_ADDRESS.");
for (uint256 i = 0; i < _ids.length; i++) {
uint256 id = _ids[i];
_setCreator(_to, id);
}
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(
address _owner,
address _operator
) override public view returns (bool isOperator) {
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Change the creator address for given token
* @param _to Address of the new creator
* @param _id Token IDs to change creator of
*/
function _setCreator(address _to, uint256 _id) internal creatorOnly(_id)
{
creators[_id] = _to;
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(
uint256 _id
) internal view returns (bool) {
return creators[_id] != address(0);
}
function exists(
uint256 _id
) external view returns (bool) {
return _exists(_id);
}
/**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/
function _msgSender()
internal
override
view
returns (address sender)
{
return ContextMixin.msgSender();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC1155Tradable.sol";
/**
* @title MintPass
* MintPass - a contract for the MintPass
*/
contract MintPass is ERC1155Tradable {
using SafeMath for uint256;
bool public preSaleIsActive = false;
bool public saleIsActive = false;
uint256 public preSalePrice = 0.01420 ether;
uint256 public pubSalePrice = 0.01420 ether;
uint256 public maxPerWallet = 10;
uint256 public maxPerTransaction = 10;
struct Supply {
uint256 supply;
}
mapping(uint256 => Supply) public maxSupply;
constructor(
string memory _name,
string memory _symbol,
string memory _uri,
uint256 _id,
uint256 _initialSupply,
uint256 _maxSupply,
address _proxyRegistryAddress
) ERC1155Tradable(_name, _symbol, _uri, _proxyRegistryAddress) {
create(msg.sender, _id, _initialSupply, _uri, "");
maxSupply[_id].supply = _maxSupply; // setMaxSupply()
}
function setMaxSupply(uint256 _maxSupply, uint256 _id) external onlyOwner {
maxSupply[_id].supply = _maxSupply;
}
function getMaxSupply(uint256 _id) public view returns (uint256) {
return maxSupply[_id].supply;
}
function getCurrentSupply(uint256 _id) public view returns (uint256) {
return totalSupply(_id);
}
function setPubSalePrice(uint256 _price) external onlyOwner {
pubSalePrice = _price;
}
function getPubSalePrice() public view returns (uint256) {
return pubSalePrice;
}
function setPreSalePrice(uint256 _price) external onlyOwner {
preSalePrice = _price;
}
function getPreSalePrice() public view returns (uint256) {
return preSalePrice;
}
function setMaxPerWallet(uint256 _maxToMint) external onlyOwner {
maxPerWallet = _maxToMint;
}
function setMaxPerTransaction(uint256 _maxToMint) external onlyOwner {
maxPerTransaction = _maxToMint;
}
function flipSaleState() public onlyOwner {
saleIsActive = !saleIsActive;
}
function flipPreSaleState() public onlyOwner {
preSaleIsActive = !preSaleIsActive;
}
function airdrop(
address[] memory _addrs,
uint256 _quantity,
uint256 _id
)
public
onlyOwner
{
for (uint256 i = 0; i < _addrs.length; i++) {
mint(_addrs[i], _id, _quantity, "");
}
}
function mint(uint256 _quantity, uint256 _id) public payable {
require(saleIsActive, "Sale is not active.");
require(
totalSupply(_id).add(_quantity) <= getMaxSupply(_id),
"Mint has already ended."
);
require(_quantity > 0, "numberOfTokens cannot be 0.");
require(
pubSalePrice.mul(_quantity) <= msg.value,
"ETH sent is incorrect."
);
require(
balanceOf(msg.sender, _id).add(_quantity) <= maxPerWallet,
"Exceeds limit per wallet."
);
require(
_quantity <= maxPerWallet,
"Exceeds per transaction limit."
);
mint(msg.sender, _id, _quantity, "");
}
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
abstract contract ContextMixin {
function msgSender()
internal
view
returns (address payable sender)
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = payable(msg.sender);
}
return sender;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Initializable} from "./Initializable.sol";
contract EIP712Base is Initializable {
struct EIP712Domain {
string name;
string version;
address verifyingContract;
bytes32 salt;
}
string constant public ERC712_VERSION = "1";
bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256(
bytes(
"EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)"
)
);
bytes32 internal domainSeperator;
// supposed to be called once while initializing.
// one of the contracts that inherits this contract follows proxy pattern
// so it is not possible to do this in a constructor
function _initializeEIP712(
string memory name
)
internal
initializer
{
_setDomainSeperator(name);
}
function _setDomainSeperator(string memory name) internal {
domainSeperator = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(name)),
keccak256(bytes(ERC712_VERSION)),
address(this),
bytes32(getChainId())
)
);
}
function getDomainSeperator() public view returns (bytes32) {
return domainSeperator;
}
function getChainId() public view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* Accept message hash and returns hash message in EIP712 compatible form
* So that it can be used to recover signer from signature signed using EIP712 formatted data
* https://eips.ethereum.org/EIPS/eip-712
* "\\x19" makes the encoding deterministic
* "\\x01" is the version byte to make it compatible to EIP-191
*/
function toTypedMessageHash(bytes32 messageHash)
internal
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Initializable {
bool inited = false;
modifier initializer() {
require(!inited, "already inited");
_;
inited = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {EIP712Base} from "./EIP712Base.sol";
contract NativeMetaTransaction is EIP712Base {
using SafeMath for uint256;
bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256(
bytes(
"MetaTransaction(uint256 nonce,address from,bytes functionSignature)"
)
);
event MetaTransactionExecuted(
address userAddress,
address payable relayerAddress,
bytes functionSignature
);
mapping(address => uint256) nonces;
/*
* Meta transaction structure.
* No point of including value field here as if user is doing value transfer then he has the funds to pay for gas
* He should call the desired function directly in that case.
*/
struct MetaTransaction {
uint256 nonce;
address from;
bytes functionSignature;
}
function executeMetaTransaction(
address userAddress,
bytes memory functionSignature,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) public payable returns (bytes memory) {
MetaTransaction memory metaTx = MetaTransaction({
nonce: nonces[userAddress],
from: userAddress,
functionSignature: functionSignature
});
require(
verify(userAddress, metaTx, sigR, sigS, sigV),
"Signer and signature do not match"
);
// increase nonce for user (to avoid re-use)
nonces[userAddress] = nonces[userAddress].add(1);
emit MetaTransactionExecuted(
userAddress,
payable(msg.sender),
functionSignature
);
// Append userAddress and relayer address at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call(
abi.encodePacked(functionSignature, userAddress)
);
require(success, "Function call not successful");
return returnData;
}
function hashMetaTransaction(MetaTransaction memory metaTx)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
META_TRANSACTION_TYPEHASH,
metaTx.nonce,
metaTx.from,
keccak256(metaTx.functionSignature)
)
);
}
function getNonce(address user) public view returns (uint256 nonce) {
nonce = nonces[user];
}
function verify(
address signer,
MetaTransaction memory metaTx,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) internal view returns (bool) {
require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER");
return
signer ==
ecrecover(
toTypedMessageHash(hashMetaTransaction(metaTx)),
sigV,
sigR,
sigS
);
}
}
|
/ Contract name Contract symbol
|
contract ERC1155Tradable is ContextMixin, ERC1155, NativeMetaTransaction, Ownable {
using Strings for string;
using SafeMath for uint256;
address proxyRegistryAddress;
mapping (uint256 => address) public creators;
mapping (uint256 => uint256) public tokenSupply;
mapping (uint256 => string) customUri;
string public name;
string public symbol;
like _exists(), name(), symbol(), and totalSupply()
modifier creatorOnly(uint256 _id) {
require(creators[_id] == _msgSender(), "ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED");
_;
}
modifier ownersOnly(uint256 _id) {
require(balanceOf(_msgSender(), _id) > 0, "ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED");
_;
}
constructor(
string memory _name,
string memory _symbol,
string memory _uri,
address _proxyRegistryAddress
) ERC1155(_uri) {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
_initializeEIP712(name);
}
function uri(
uint256 _id
) override public view returns (string memory) {
require(_exists(_id), "ERC1155Tradable#uri: NONEXISTENT_TOKEN");
bytes memory customUriBytes = bytes(customUri[_id]);
if (customUriBytes.length > 0) {
return customUri[_id];
return super.uri(_id);
}
}
function uri(
uint256 _id
) override public view returns (string memory) {
require(_exists(_id), "ERC1155Tradable#uri: NONEXISTENT_TOKEN");
bytes memory customUriBytes = bytes(customUri[_id]);
if (customUriBytes.length > 0) {
return customUri[_id];
return super.uri(_id);
}
}
} else {
function totalSupply(
uint256 _id
) public view returns (uint256) {
return tokenSupply[_id];
}
function setURI(
string memory _newURI
) public onlyOwner {
_setURI(_newURI);
}
function setCustomURI(
uint256 _tokenId,
string memory _newURI
) public creatorOnly(_tokenId) {
customUri[_tokenId] = _newURI;
emit URI(_newURI, _tokenId);
}
function create(
address _initialOwner,
uint256 _id,
uint256 _initialSupply,
string memory _uri,
bytes memory _data
) public onlyOwner returns (uint256) {
require(!_exists(_id), "token _id already exists");
creators[_id] = _msgSender();
if (bytes(_uri).length > 0) {
customUri[_id] = _uri;
emit URI(_uri, _id);
}
_mint(_initialOwner, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
return _id;
}
function create(
address _initialOwner,
uint256 _id,
uint256 _initialSupply,
string memory _uri,
bytes memory _data
) public onlyOwner returns (uint256) {
require(!_exists(_id), "token _id already exists");
creators[_id] = _msgSender();
if (bytes(_uri).length > 0) {
customUri[_id] = _uri;
emit URI(_uri, _id);
}
_mint(_initialOwner, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
return _id;
}
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) virtual public /* creatorOnly(_id) */ {
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] = tokenSupply[_id].add(_quantity);
}
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _quantities,
bytes memory _data
) public {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 _id = _ids[i];
uint256 quantity = _quantities[i];
tokenSupply[_id] = tokenSupply[_id].add(quantity);
_mintBatch(_to, _ids, _quantities, _data);
}
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _quantities,
bytes memory _data
) public {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 _id = _ids[i];
uint256 quantity = _quantities[i];
tokenSupply[_id] = tokenSupply[_id].add(quantity);
_mintBatch(_to, _ids, _quantities, _data);
}
}
function setCreator(
address _to,
uint256[] memory _ids
) public {
require(_to != address(0), "ERC1155Tradable#setCreator: INVALID_ADDRESS.");
for (uint256 i = 0; i < _ids.length; i++) {
uint256 id = _ids[i];
_setCreator(_to, id);
}
}
function setCreator(
address _to,
uint256[] memory _ids
) public {
require(_to != address(0), "ERC1155Tradable#setCreator: INVALID_ADDRESS.");
for (uint256 i = 0; i < _ids.length; i++) {
uint256 id = _ids[i];
_setCreator(_to, id);
}
}
function isApprovedForAll(
address _owner,
address _operator
) override public view returns (bool isOperator) {
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
function isApprovedForAll(
address _owner,
address _operator
) override public view returns (bool isOperator) {
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
function _setCreator(address _to, uint256 _id) internal creatorOnly(_id)
{
creators[_id] = _to;
}
function _exists(
uint256 _id
) internal view returns (bool) {
return creators[_id] != address(0);
}
function exists(
uint256 _id
) external view returns (bool) {
return _exists(_id);
}
function _msgSender()
internal
override
view
returns (address sender)
{
return ContextMixin.msgSender();
}
}
| 400,941 |
[
1,
19,
13456,
508,
13456,
3273,
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,
16351,
4232,
39,
2499,
2539,
1609,
17394,
353,
1772,
14439,
16,
4232,
39,
2499,
2539,
16,
16717,
2781,
3342,
16,
14223,
6914,
288,
203,
225,
1450,
8139,
364,
533,
31,
203,
225,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
225,
1758,
2889,
4243,
1887,
31,
203,
225,
2874,
261,
11890,
5034,
516,
1758,
13,
1071,
1519,
3062,
31,
203,
225,
2874,
261,
11890,
5034,
516,
2254,
5034,
13,
1071,
1147,
3088,
1283,
31,
203,
225,
2874,
261,
11890,
5034,
516,
533,
13,
1679,
3006,
31,
203,
225,
533,
1071,
508,
31,
203,
225,
533,
1071,
3273,
31,
203,
203,
225,
3007,
389,
1808,
9334,
508,
9334,
3273,
9334,
471,
2078,
3088,
1283,
1435,
203,
225,
9606,
11784,
3386,
12,
11890,
5034,
389,
350,
13,
288,
203,
565,
2583,
12,
1793,
3062,
63,
67,
350,
65,
422,
389,
3576,
12021,
9334,
315,
654,
39,
2499,
2539,
1609,
17394,
7,
20394,
3386,
30,
20747,
67,
5458,
3575,
67,
16852,
8863,
203,
565,
389,
31,
203,
225,
289,
203,
203,
225,
9606,
25937,
3386,
12,
11890,
5034,
389,
350,
13,
288,
203,
565,
2583,
12,
12296,
951,
24899,
3576,
12021,
9334,
389,
350,
13,
405,
374,
16,
315,
654,
39,
2499,
2539,
1609,
17394,
7,
995,
414,
3386,
30,
20747,
67,
51,
5665,
11367,
67,
16852,
8863,
203,
565,
389,
31,
203,
225,
289,
203,
203,
225,
3885,
12,
203,
565,
533,
3778,
389,
529,
16,
203,
565,
533,
3778,
389,
7175,
16,
203,
565,
533,
3778,
389,
1650,
16,
203,
565,
1758,
389,
5656,
2
] |
./full_match/44787/0xf8Ccc240b7CE51c7E2ED95e5802aacB165046d61/sources/contracts/StarFarm.sol
|
MasterChef is the master of Star. He can make Star and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once STAR is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless. Info of each user.
|
contract MasterChef is Initializable, OwnableUpgradeable {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
struct UserInfo {
uint256 lastDeposit;
uint256 nftAmount;
uint256 nftRewardDebt;
uint256 nftLastDeposit;
}
struct PoolInfo {
uint256 fee;
}
address public lockAddr;
address public teamAddr;
address public rewardAddr;
uint256 public lockRatio;
uint256 public teamRatio;
uint256 public rewardRatio;
mapping (address => uint256[]) public userNFTs;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, bool isNodeUser);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, bool isNodeUser);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, bool isNodeUser);
IERC20Upgradeable public starToken;
IStarNode public starNode;
address public bonusAddr;
IERC721Upgradeable public starNFT;
INFTLogic public nftLogic;
uint256 public starPerBlock;
uint256 public BONUS_MULTIPLIER;
IMigratorChef public migrator;
PoolInfo[] public poolInfo;
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
uint256 public totalAllocPoint;
uint256 public startBlock;
mapping (address => bool) public isNodeUser;
mapping (uint256 => address) public NFTOwner;
function initialize(address _starToken, address _bonus, address _node, uint256 _starPerBlock, uint256 _startBlock) public initializer {
__farm_init(_starToken, _bonus, _node, _starPerBlock, _startBlock);
}
function __farm_init(address _starToken, address _bonus, address _node, uint256 _starPerBlock, uint256 _startBlock) internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__farm_init_unchained(_starToken, _bonus, _node, _starPerBlock, _startBlock);
}
function __farm_init_unchained(address _starToken, address _bonus, address _node, uint256 _starPerBlock, uint256 _startBlock) internal initializer {
starToken = IERC20Upgradeable(_starToken);
bonusAddr = _bonus;
starNode = IStarNode(_node);
starPerBlock = _starPerBlock;
startBlock = _startBlock;
poolInfo.push(PoolInfo({
lpToken: IERC20Upgradeable(_starToken),
allocPoint: 1000,
lastRewardBlock: startBlock,
accStarPerShare: 0,
extraAmount: 0,
fee: 0
}));
totalAllocPoint = 1000;
}
function __farm_init_unchained(address _starToken, address _bonus, address _node, uint256 _starPerBlock, uint256 _startBlock) internal initializer {
starToken = IERC20Upgradeable(_starToken);
bonusAddr = _bonus;
starNode = IStarNode(_node);
starPerBlock = _starPerBlock;
startBlock = _startBlock;
poolInfo.push(PoolInfo({
lpToken: IERC20Upgradeable(_starToken),
allocPoint: 1000,
lastRewardBlock: startBlock,
accStarPerShare: 0,
extraAmount: 0,
fee: 0
}));
totalAllocPoint = 1000;
}
function updateMultiplier(uint256 multiplierNumber) public onlyOwner {
BONUS_MULTIPLIER = multiplierNumber;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function add(uint256 _allocPoint, IERC20Upgradeable _lpToken, uint256 _fee, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accStarPerShare: 0,
extraAmount: 0,
fee: _fee
}));
updateStakingPool();
}
function add(uint256 _allocPoint, IERC20Upgradeable _lpToken, uint256 _fee, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accStarPerShare: 0,
extraAmount: 0,
fee: _fee
}));
updateStakingPool();
}
function add(uint256 _allocPoint, IERC20Upgradeable _lpToken, uint256 _fee, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accStarPerShare: 0,
extraAmount: 0,
fee: _fee
}));
updateStakingPool();
}
function set(uint256 _pid, uint256 _allocPoint, uint256 _fee, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
uint256 prevAllocPoint = poolInfo[_pid].allocPoint;
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].fee = _fee;
if (prevAllocPoint != _allocPoint) {
updateStakingPool();
}
}
function set(uint256 _pid, uint256 _allocPoint, uint256 _fee, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
uint256 prevAllocPoint = poolInfo[_pid].allocPoint;
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].fee = _fee;
if (prevAllocPoint != _allocPoint) {
updateStakingPool();
}
}
function set(uint256 _pid, uint256 _allocPoint, uint256 _fee, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
uint256 prevAllocPoint = poolInfo[_pid].allocPoint;
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].fee = _fee;
if (prevAllocPoint != _allocPoint) {
updateStakingPool();
}
}
function updateStakingPool() internal {
uint256 length = poolInfo.length;
uint256 points = 0;
for (uint256 pid = 1; pid < length; ++pid) {
points = points.add(poolInfo[pid].allocPoint);
}
if (points != 0) {
points = points.div(3);
totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points);
poolInfo[0].allocPoint = points;
}
}
function updateStakingPool() internal {
uint256 length = poolInfo.length;
uint256 points = 0;
for (uint256 pid = 1; pid < length; ++pid) {
points = points.add(poolInfo[pid].allocPoint);
}
if (points != 0) {
points = points.div(3);
totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points);
poolInfo[0].allocPoint = points;
}
}
function updateStakingPool() internal {
uint256 length = poolInfo.length;
uint256 points = 0;
for (uint256 pid = 1; pid < length; ++pid) {
points = points.add(poolInfo[pid].allocPoint);
}
if (points != 0) {
points = points.div(3);
totalAllocPoint = totalAllocPoint.sub(poolInfo[0].allocPoint).add(points);
poolInfo[0].allocPoint = points;
}
}
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20Upgradeable lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20Upgradeable newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
}
function pendingStar(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accStarPerShare = pool.accStarPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this)).add(pool.extraAmount);
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = accStarPerShare.add(starReward.mul(1e12).div(lpSupply));
}
(uint256 _selfGain, ) = starNode.nodeGain();
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12).sub(user.rewardDebt);
uint256 _nftAmountpendingStar = _nftAmountGain.mul(accStarPerShare).div(1e12).sub(user.nftRewardDebt);
return _amountpendingStar.sub(_nftAmountpendingStar);
}
function pendingStar(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accStarPerShare = pool.accStarPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this)).add(pool.extraAmount);
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accStarPerShare = accStarPerShare.add(starReward.mul(1e12).div(lpSupply));
}
(uint256 _selfGain, ) = starNode.nodeGain();
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
uint256 _amountpendingStar = _amountGain.mul(accStarPerShare).div(1e12).sub(user.rewardDebt);
uint256 _nftAmountpendingStar = _nftAmountGain.mul(accStarPerShare).div(1e12).sub(user.nftRewardDebt);
return _amountpendingStar.sub(_nftAmountpendingStar);
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this)).add(pool.extraAmount);
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
starToken.safeTransfer(bonusAddr, starReward.div(10));
pool.accStarPerShare = pool.accStarPerShare.add(starReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this)).add(pool.extraAmount);
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
starToken.safeTransfer(bonusAddr, starReward.div(10));
pool.accStarPerShare = pool.accStarPerShare.add(starReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this)).add(pool.extraAmount);
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 starReward = multiplier.mul(starPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
starToken.safeTransfer(bonusAddr, starReward.div(10));
pool.accStarPerShare = pool.accStarPerShare.add(starReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _useramount = user.amount.sub(user.nftAmount);
uint256 _amountGain = _useramount.add(_useramount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
if (_amountGain > 0) {
uint256 pending = _amountGain.mul(pool.accStarPerShare).div(1e12).add(user.nftRewardDebt).sub(user.rewardDebt);
if(pending > 0) {
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.amount);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(_msgSender(), address(this), _amount);
user.amount = user.amount.add(_amount);
user.lastDeposit = block.timestamp;
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.add(_extraAmount);
}
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
user.rewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(pool.accStarPerShare).div(1e12);
emit Deposit(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _useramount = user.amount.sub(user.nftAmount);
uint256 _amountGain = _useramount.add(_useramount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
if (_amountGain > 0) {
uint256 pending = _amountGain.mul(pool.accStarPerShare).div(1e12).add(user.nftRewardDebt).sub(user.rewardDebt);
if(pending > 0) {
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.amount);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(_msgSender(), address(this), _amount);
user.amount = user.amount.add(_amount);
user.lastDeposit = block.timestamp;
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.add(_extraAmount);
}
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
user.rewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(pool.accStarPerShare).div(1e12);
emit Deposit(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _useramount = user.amount.sub(user.nftAmount);
uint256 _amountGain = _useramount.add(_useramount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
if (_amountGain > 0) {
uint256 pending = _amountGain.mul(pool.accStarPerShare).div(1e12).add(user.nftRewardDebt).sub(user.rewardDebt);
if(pending > 0) {
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.amount);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(_msgSender(), address(this), _amount);
user.amount = user.amount.add(_amount);
user.lastDeposit = block.timestamp;
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.add(_extraAmount);
}
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
user.rewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(pool.accStarPerShare).div(1e12);
emit Deposit(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _useramount = user.amount.sub(user.nftAmount);
uint256 _amountGain = _useramount.add(_useramount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
if (_amountGain > 0) {
uint256 pending = _amountGain.mul(pool.accStarPerShare).div(1e12).add(user.nftRewardDebt).sub(user.rewardDebt);
if(pending > 0) {
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.amount);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(_msgSender(), address(this), _amount);
user.amount = user.amount.add(_amount);
user.lastDeposit = block.timestamp;
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.add(_extraAmount);
}
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
user.rewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(pool.accStarPerShare).div(1e12);
emit Deposit(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
uint256 _useramount = user.amount.sub(user.nftAmount);
require(_useramount >= _amount, "withdraw: amount error");
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = _useramount.add(_useramount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
uint256 pending = _amountGain.mul(pool.accStarPerShare).div(1e12).add(user.nftRewardDebt).sub(user.rewardDebt);
if(pending > 0) {
if (user.lastDeposit > block.timestamp.sub(604800)) {
pending = pending.mul(90).div(100);
starToken.safeTransfer(bonusAddr, pending.mul(10).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), _useramount);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpToken.safeTransfer(_msgSender(), _amount);
}
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
user.rewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(pool.accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
uint256 _useramount = user.amount.sub(user.nftAmount);
require(_useramount >= _amount, "withdraw: amount error");
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = _useramount.add(_useramount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
uint256 pending = _amountGain.mul(pool.accStarPerShare).div(1e12).add(user.nftRewardDebt).sub(user.rewardDebt);
if(pending > 0) {
if (user.lastDeposit > block.timestamp.sub(604800)) {
pending = pending.mul(90).div(100);
starToken.safeTransfer(bonusAddr, pending.mul(10).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), _useramount);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpToken.safeTransfer(_msgSender(), _amount);
}
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
user.rewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(pool.accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
uint256 _useramount = user.amount.sub(user.nftAmount);
require(_useramount >= _amount, "withdraw: amount error");
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = _useramount.add(_useramount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
uint256 pending = _amountGain.mul(pool.accStarPerShare).div(1e12).add(user.nftRewardDebt).sub(user.rewardDebt);
if(pending > 0) {
if (user.lastDeposit > block.timestamp.sub(604800)) {
pending = pending.mul(90).div(100);
starToken.safeTransfer(bonusAddr, pending.mul(10).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), _useramount);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpToken.safeTransfer(_msgSender(), _amount);
}
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
user.rewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(pool.accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
uint256 _useramount = user.amount.sub(user.nftAmount);
require(_useramount >= _amount, "withdraw: amount error");
updatePool(_pid);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = _useramount.add(_useramount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
uint256 pending = _amountGain.mul(pool.accStarPerShare).div(1e12).add(user.nftRewardDebt).sub(user.rewardDebt);
if(pending > 0) {
if (user.lastDeposit > block.timestamp.sub(604800)) {
pending = pending.mul(90).div(100);
starToken.safeTransfer(bonusAddr, pending.mul(10).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), _useramount);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
uint256 _extraAmount = _amount.mul(_selfGain.add(_parentGain)).div(100);
pool.extraAmount = pool.extraAmount.sub(_extraAmount);
pool.lpToken.safeTransfer(_msgSender(), _amount);
}
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
user.rewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(pool.accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), _pid, _amount, isNodeUser[_msgSender()]);
}
function enterStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
require(starNFT.ownerOf(_tokenId) == _msgSender(), "error NFT user");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
if (_nftAmountGain > 0) {
uint256 pending = _nftAmountGain.mul(pool.accStarPerShare).div(1e12).sub(user.nftRewardDebt);
if(pending > 0) {
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.nftAmount);
}
}
if (_tokenId > 0) {
starNFT.transferFrom(_msgSender(), address(this), _tokenId);
userNFTs[_msgSender()].push(_tokenId);
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
uint256 _extraAmount = _amount.add(_amount.mul(_selfGain.add(_parentGain)).div(100));
pool.extraAmount = pool.extraAmount.add(_extraAmount);
user.amount = user.amount.add(_amount);
user.nftAmount = user.nftAmount.add(_amount);
user.nftLastDeposit = block.timestamp;
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
_nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
}
user.rewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(pool.accStarPerShare).div(1e12);
}
function enterStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
require(starNFT.ownerOf(_tokenId) == _msgSender(), "error NFT user");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
if (_nftAmountGain > 0) {
uint256 pending = _nftAmountGain.mul(pool.accStarPerShare).div(1e12).sub(user.nftRewardDebt);
if(pending > 0) {
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.nftAmount);
}
}
if (_tokenId > 0) {
starNFT.transferFrom(_msgSender(), address(this), _tokenId);
userNFTs[_msgSender()].push(_tokenId);
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
uint256 _extraAmount = _amount.add(_amount.mul(_selfGain.add(_parentGain)).div(100));
pool.extraAmount = pool.extraAmount.add(_extraAmount);
user.amount = user.amount.add(_amount);
user.nftAmount = user.nftAmount.add(_amount);
user.nftLastDeposit = block.timestamp;
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
_nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
}
user.rewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(pool.accStarPerShare).div(1e12);
}
function enterStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
require(starNFT.ownerOf(_tokenId) == _msgSender(), "error NFT user");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
if (_nftAmountGain > 0) {
uint256 pending = _nftAmountGain.mul(pool.accStarPerShare).div(1e12).sub(user.nftRewardDebt);
if(pending > 0) {
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.nftAmount);
}
}
if (_tokenId > 0) {
starNFT.transferFrom(_msgSender(), address(this), _tokenId);
userNFTs[_msgSender()].push(_tokenId);
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
uint256 _extraAmount = _amount.add(_amount.mul(_selfGain.add(_parentGain)).div(100));
pool.extraAmount = pool.extraAmount.add(_extraAmount);
user.amount = user.amount.add(_amount);
user.nftAmount = user.nftAmount.add(_amount);
user.nftLastDeposit = block.timestamp;
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
_nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
}
user.rewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(pool.accStarPerShare).div(1e12);
}
function enterStakingNFT(uint256 _tokenId) public {
PoolInfo storage pool = poolInfo[0];
UserInfo storage user = userInfo[0][_msgSender()];
require(starNFT.ownerOf(_tokenId) == _msgSender(), "error NFT user");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
if (_nftAmountGain > 0) {
uint256 pending = _nftAmountGain.mul(pool.accStarPerShare).div(1e12).sub(user.nftRewardDebt);
if(pending > 0) {
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.nftAmount);
}
}
if (_tokenId > 0) {
starNFT.transferFrom(_msgSender(), address(this), _tokenId);
userNFTs[_msgSender()].push(_tokenId);
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
uint256 _extraAmount = _amount.add(_amount.mul(_selfGain.add(_parentGain)).div(100));
pool.extraAmount = pool.extraAmount.add(_extraAmount);
user.amount = user.amount.add(_amount);
user.nftAmount = user.nftAmount.add(_amount);
user.nftLastDeposit = block.timestamp;
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
_nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
}
user.rewardDebt = _amountGain.mul(pool.accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(pool.accStarPerShare).div(1e12);
}
emit Deposit(_msgSender(), 0, _tokenId, isNodeUser[_msgSender()]);
function leaveStakingNFT(uint256 _tokenId) public {
UserInfo storage user = userInfo[0][_msgSender()];
require(userNFTs[_msgSender()].length > 0, "no NFT");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
uint256 pending = _nftAmountGain.mul(poolInfo[0].accStarPerShare).div(1e12).sub(user.nftRewardDebt);
if(pending > 0) {
if (user.nftLastDeposit > block.timestamp.sub(604800)) {
pending = pending.mul(90).div(100);
starToken.safeTransfer(bonusAddr, pending.mul(10).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.nftAmount);
}
if (_tokenId > 0) {
uint256[] storage _userNFTs = userNFTs[_msgSender()];
for (uint256 i = 0; i < _userNFTs.length; i ++) {
if(_userNFTs[i] == _tokenId) {
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
if(_amount > 0) {
uint256 _self_parentGain = _selfGain.add(_parentGain);
uint256 _extraAmount = _amount.add(_amount.mul(_self_parentGain).div(100));
poolInfo[0].extraAmount = poolInfo[0].extraAmount.sub(_extraAmount);
user.amount = user.amount.sub(_amount);
user.nftAmount = user.nftAmount.sub(_amount);
_userNFTs[i] = _userNFTs[_userNFTs.length - 1];
_userNFTs.pop();
}
starNFT.transferFrom(address(this), _msgSender(), _tokenId);
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
_nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
user.rewardDebt = _amountGain.mul(poolInfo[0].accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(poolInfo[0].accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), 0, _amount, isNodeUser[_msgSender()]);
break;
}
}
}
}
function leaveStakingNFT(uint256 _tokenId) public {
UserInfo storage user = userInfo[0][_msgSender()];
require(userNFTs[_msgSender()].length > 0, "no NFT");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
uint256 pending = _nftAmountGain.mul(poolInfo[0].accStarPerShare).div(1e12).sub(user.nftRewardDebt);
if(pending > 0) {
if (user.nftLastDeposit > block.timestamp.sub(604800)) {
pending = pending.mul(90).div(100);
starToken.safeTransfer(bonusAddr, pending.mul(10).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.nftAmount);
}
if (_tokenId > 0) {
uint256[] storage _userNFTs = userNFTs[_msgSender()];
for (uint256 i = 0; i < _userNFTs.length; i ++) {
if(_userNFTs[i] == _tokenId) {
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
if(_amount > 0) {
uint256 _self_parentGain = _selfGain.add(_parentGain);
uint256 _extraAmount = _amount.add(_amount.mul(_self_parentGain).div(100));
poolInfo[0].extraAmount = poolInfo[0].extraAmount.sub(_extraAmount);
user.amount = user.amount.sub(_amount);
user.nftAmount = user.nftAmount.sub(_amount);
_userNFTs[i] = _userNFTs[_userNFTs.length - 1];
_userNFTs.pop();
}
starNFT.transferFrom(address(this), _msgSender(), _tokenId);
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
_nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
user.rewardDebt = _amountGain.mul(poolInfo[0].accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(poolInfo[0].accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), 0, _amount, isNodeUser[_msgSender()]);
break;
}
}
}
}
function leaveStakingNFT(uint256 _tokenId) public {
UserInfo storage user = userInfo[0][_msgSender()];
require(userNFTs[_msgSender()].length > 0, "no NFT");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
uint256 pending = _nftAmountGain.mul(poolInfo[0].accStarPerShare).div(1e12).sub(user.nftRewardDebt);
if(pending > 0) {
if (user.nftLastDeposit > block.timestamp.sub(604800)) {
pending = pending.mul(90).div(100);
starToken.safeTransfer(bonusAddr, pending.mul(10).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.nftAmount);
}
if (_tokenId > 0) {
uint256[] storage _userNFTs = userNFTs[_msgSender()];
for (uint256 i = 0; i < _userNFTs.length; i ++) {
if(_userNFTs[i] == _tokenId) {
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
if(_amount > 0) {
uint256 _self_parentGain = _selfGain.add(_parentGain);
uint256 _extraAmount = _amount.add(_amount.mul(_self_parentGain).div(100));
poolInfo[0].extraAmount = poolInfo[0].extraAmount.sub(_extraAmount);
user.amount = user.amount.sub(_amount);
user.nftAmount = user.nftAmount.sub(_amount);
_userNFTs[i] = _userNFTs[_userNFTs.length - 1];
_userNFTs.pop();
}
starNFT.transferFrom(address(this), _msgSender(), _tokenId);
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
_nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
user.rewardDebt = _amountGain.mul(poolInfo[0].accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(poolInfo[0].accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), 0, _amount, isNodeUser[_msgSender()]);
break;
}
}
}
}
function leaveStakingNFT(uint256 _tokenId) public {
UserInfo storage user = userInfo[0][_msgSender()];
require(userNFTs[_msgSender()].length > 0, "no NFT");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
uint256 pending = _nftAmountGain.mul(poolInfo[0].accStarPerShare).div(1e12).sub(user.nftRewardDebt);
if(pending > 0) {
if (user.nftLastDeposit > block.timestamp.sub(604800)) {
pending = pending.mul(90).div(100);
starToken.safeTransfer(bonusAddr, pending.mul(10).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.nftAmount);
}
if (_tokenId > 0) {
uint256[] storage _userNFTs = userNFTs[_msgSender()];
for (uint256 i = 0; i < _userNFTs.length; i ++) {
if(_userNFTs[i] == _tokenId) {
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
if(_amount > 0) {
uint256 _self_parentGain = _selfGain.add(_parentGain);
uint256 _extraAmount = _amount.add(_amount.mul(_self_parentGain).div(100));
poolInfo[0].extraAmount = poolInfo[0].extraAmount.sub(_extraAmount);
user.amount = user.amount.sub(_amount);
user.nftAmount = user.nftAmount.sub(_amount);
_userNFTs[i] = _userNFTs[_userNFTs.length - 1];
_userNFTs.pop();
}
starNFT.transferFrom(address(this), _msgSender(), _tokenId);
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
_nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
user.rewardDebt = _amountGain.mul(poolInfo[0].accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(poolInfo[0].accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), 0, _amount, isNodeUser[_msgSender()]);
break;
}
}
}
}
function leaveStakingNFT(uint256 _tokenId) public {
UserInfo storage user = userInfo[0][_msgSender()];
require(userNFTs[_msgSender()].length > 0, "no NFT");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
uint256 pending = _nftAmountGain.mul(poolInfo[0].accStarPerShare).div(1e12).sub(user.nftRewardDebt);
if(pending > 0) {
if (user.nftLastDeposit > block.timestamp.sub(604800)) {
pending = pending.mul(90).div(100);
starToken.safeTransfer(bonusAddr, pending.mul(10).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.nftAmount);
}
if (_tokenId > 0) {
uint256[] storage _userNFTs = userNFTs[_msgSender()];
for (uint256 i = 0; i < _userNFTs.length; i ++) {
if(_userNFTs[i] == _tokenId) {
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
if(_amount > 0) {
uint256 _self_parentGain = _selfGain.add(_parentGain);
uint256 _extraAmount = _amount.add(_amount.mul(_self_parentGain).div(100));
poolInfo[0].extraAmount = poolInfo[0].extraAmount.sub(_extraAmount);
user.amount = user.amount.sub(_amount);
user.nftAmount = user.nftAmount.sub(_amount);
_userNFTs[i] = _userNFTs[_userNFTs.length - 1];
_userNFTs.pop();
}
starNFT.transferFrom(address(this), _msgSender(), _tokenId);
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
_nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
user.rewardDebt = _amountGain.mul(poolInfo[0].accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(poolInfo[0].accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), 0, _amount, isNodeUser[_msgSender()]);
break;
}
}
}
}
function leaveStakingNFT(uint256 _tokenId) public {
UserInfo storage user = userInfo[0][_msgSender()];
require(userNFTs[_msgSender()].length > 0, "no NFT");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
uint256 pending = _nftAmountGain.mul(poolInfo[0].accStarPerShare).div(1e12).sub(user.nftRewardDebt);
if(pending > 0) {
if (user.nftLastDeposit > block.timestamp.sub(604800)) {
pending = pending.mul(90).div(100);
starToken.safeTransfer(bonusAddr, pending.mul(10).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.nftAmount);
}
if (_tokenId > 0) {
uint256[] storage _userNFTs = userNFTs[_msgSender()];
for (uint256 i = 0; i < _userNFTs.length; i ++) {
if(_userNFTs[i] == _tokenId) {
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
if(_amount > 0) {
uint256 _self_parentGain = _selfGain.add(_parentGain);
uint256 _extraAmount = _amount.add(_amount.mul(_self_parentGain).div(100));
poolInfo[0].extraAmount = poolInfo[0].extraAmount.sub(_extraAmount);
user.amount = user.amount.sub(_amount);
user.nftAmount = user.nftAmount.sub(_amount);
_userNFTs[i] = _userNFTs[_userNFTs.length - 1];
_userNFTs.pop();
}
starNFT.transferFrom(address(this), _msgSender(), _tokenId);
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
_nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
user.rewardDebt = _amountGain.mul(poolInfo[0].accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(poolInfo[0].accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), 0, _amount, isNodeUser[_msgSender()]);
break;
}
}
}
}
function leaveStakingNFT(uint256 _tokenId) public {
UserInfo storage user = userInfo[0][_msgSender()];
require(userNFTs[_msgSender()].length > 0, "no NFT");
updatePool(0);
(uint256 _selfGain, uint256 _parentGain) = starNode.nodeGain();
uint256 _amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
uint256 _nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
uint256 pending = _nftAmountGain.mul(poolInfo[0].accStarPerShare).div(1e12).sub(user.nftRewardDebt);
if(pending > 0) {
if (user.nftLastDeposit > block.timestamp.sub(604800)) {
pending = pending.mul(90).div(100);
starToken.safeTransfer(bonusAddr, pending.mul(10).div(100));
}
starToken.safeTransfer(_msgSender(), pending);
starNode.settleNode(_msgSender(), user.nftAmount);
}
if (_tokenId > 0) {
uint256[] storage _userNFTs = userNFTs[_msgSender()];
for (uint256 i = 0; i < _userNFTs.length; i ++) {
if(_userNFTs[i] == _tokenId) {
(, , uint256 _price, uint256 _multi) = nftLogic.starMeta(_tokenId);
uint256 _amount = _price.mul(_multi).div(100);
if(_amount > 0) {
uint256 _self_parentGain = _selfGain.add(_parentGain);
uint256 _extraAmount = _amount.add(_amount.mul(_self_parentGain).div(100));
poolInfo[0].extraAmount = poolInfo[0].extraAmount.sub(_extraAmount);
user.amount = user.amount.sub(_amount);
user.nftAmount = user.nftAmount.sub(_amount);
_userNFTs[i] = _userNFTs[_userNFTs.length - 1];
_userNFTs.pop();
}
starNFT.transferFrom(address(this), _msgSender(), _tokenId);
_amountGain = user.amount.add(user.amount.mul(_selfGain).div(100));
_nftAmountGain = user.nftAmount.add(user.nftAmount.mul(_selfGain).div(100));
user.rewardDebt = _amountGain.mul(poolInfo[0].accStarPerShare).div(1e12);
user.nftRewardDebt = _nftAmountGain.mul(poolInfo[0].accStarPerShare).div(1e12);
emit Withdraw(_msgSender(), 0, _amount, isNodeUser[_msgSender()]);
break;
}
}
}
}
function getStakingNFTAmount(address _user) view public returns (uint256) {
return userNFTs[_user].length;
}
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_msgSender()];
pool.lpToken.safeTransfer(_msgSender(), user.amount);
emit EmergencyWithdraw(_msgSender(), _pid, user.amount, isNodeUser[_msgSender()]);
user.amount = 0;
user.rewardDebt = 0;
}
function setBonus(address _addr) external onlyOwner {
require(address(0) != _addr, "bonus address can not be address 0");
bonusAddr = _addr;
}
function setStarNFT(address _addr) external onlyOwner {
require(address(0) != _addr, "NFT address can not be address 0");
starNFT = IERC721Upgradeable(_addr);
}
function setNFTLogic(address _addr) external onlyOwner {
require(address(0) != _addr, "logic address can not be address 0");
nftLogic = INFTLogic(_addr);
}
function getAllocationInfo() view public returns(address ,address ,address ,uint256 ,uint256 ,uint256 ) {
return (lockAddr,teamAddr,rewardAddr,lockRatio,teamRatio,rewardRatio);
}
function setAllocationInfo(address _lockAddr,address _teamAddr,address _rewardAddr,uint256 _lockRatio,uint256 _teamRatio,uint256 _rewardRatio) public onlyOwner {
lockAddr = _lockAddr;
teamAddr = _teamAddr;
rewardAddr = _rewardAddr;
lockRatio = _lockRatio;
teamRatio = _teamRatio;
rewardRatio = _rewardRatio;
}
function regNodeUser(address _user) external onlyNode {
require(address(0) != _user, '');
isNodeUser[_user] = true;
}
function setNode(address _node) public onlyOwner {
require(address(0) != _node, 'node can not be address 0');
starNode = IStarNode(_node);
}
modifier onlyNode() {
require(_msgSender() == address(starNode), "not node");
_;
}
}
| 13,256,765 |
[
1,
7786,
39,
580,
74,
353,
326,
4171,
434,
934,
297,
18,
8264,
848,
1221,
934,
297,
471,
3904,
353,
279,
284,
1826,
3058,
93,
18,
3609,
716,
518,
1807,
4953,
429,
471,
326,
3410,
341,
491,
87,
268,
2764,
409,
1481,
7212,
18,
1021,
23178,
903,
506,
906,
4193,
358,
279,
314,
1643,
82,
1359,
13706,
6835,
3647,
21807,
353,
18662,
715,
16859,
471,
326,
19833,
848,
2405,
358,
314,
1643,
82,
6174,
18,
21940,
9831,
6453,
518,
18,
670,
1306,
4095,
518,
1807,
7934,
17,
9156,
18,
611,
369,
324,
2656,
18,
3807,
434,
1517,
729,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
13453,
39,
580,
74,
353,
10188,
6934,
16,
14223,
6914,
10784,
429,
288,
203,
565,
1450,
14060,
10477,
10784,
429,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
10784,
429,
364,
467,
654,
39,
3462,
10784,
429,
31,
203,
203,
565,
1958,
25003,
288,
203,
3639,
2254,
5034,
1142,
758,
1724,
31,
203,
3639,
2254,
5034,
290,
1222,
6275,
31,
203,
3639,
2254,
5034,
290,
1222,
17631,
1060,
758,
23602,
31,
203,
3639,
2254,
5034,
290,
1222,
3024,
758,
1724,
31,
203,
565,
289,
203,
202,
203,
565,
1958,
8828,
966,
288,
203,
3639,
2254,
5034,
14036,
31,
203,
565,
289,
203,
202,
203,
565,
1758,
1071,
2176,
3178,
31,
203,
565,
1758,
1071,
5927,
3178,
31,
203,
565,
1758,
1071,
19890,
3178,
31,
203,
565,
2254,
5034,
1071,
2176,
8541,
31,
203,
565,
2254,
5034,
1071,
5927,
8541,
31,
203,
565,
2254,
5034,
1071,
19890,
8541,
31,
203,
203,
377,
203,
565,
2874,
261,
2867,
516,
2254,
5034,
63,
5717,
1071,
729,
50,
4464,
87,
31,
203,
203,
565,
871,
4019,
538,
305,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
16,
1426,
28452,
1299,
1769,
203,
565,
871,
3423,
9446,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
16,
1426,
28452,
1299,
1769,
203,
565,
871,
512,
6592,
75,
2075,
1190,
9446,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
16,
1426,
28452,
1299,
1769,
203,
203,
565,
467,
654,
39,
3462,
10784,
2
] |
./full_match/1/0x66600c4f55527C410D4067b21474c0fa1fe1331D/sources/contracts/Collection.sol
|
@notice Create a new sequence configuration. @dev The _engineData bytes parameter is arbitrary data that is passed directly to the engine powering this new sequence. The drop this sequence is associated with must be manageable by msg.sender. This is in addition to the onlyAuthorized modifier which asserts msg.sender can manage the control node of the whole collection. msg.sender is either a metalabel admin EOA, or a controller contract that has been authorized to do drops on the drop node. Prevent having a minted count before the sequence starts. This wouldn't break anything, but would cause the indexed "minted" amount from actual mints to differ from the sequence data tracking total supply, which is non-ideal and worth the small gas to check. We're not using a separate struct here for inputs that omits the minted count field, being able to copy from calldata to storage is nice.
|
function configureSequence(
SequenceData calldata _sequence,
bytes calldata _engineData
) external onlyAuthorized {
if (
!accessControl.nodeRegistry.isAuthorizedAddressForNode(
_sequence.dropNodeId,
msg.sender
)
) {
revert NotAuthorized();
}
_sequence.sealedAfterTimestamp > 0 &&
(_sequence.sealedBeforeTimestamp >=
_sequence.sealedAfterTimestamp ||
_sequence.sealedAfterTimestamp <= block.timestamp)
) {
revert InvalidSequenceConfig();
}
if (_sequence.minted != 0) {
revert InvalidSequenceConfig();
}
sequences[sequenceId] = _sequence;
emit SequenceConfigured(sequenceId, _sequence, _engineData);
}
| 4,932,304 |
[
1,
1684,
279,
394,
3102,
1664,
18,
225,
1021,
389,
8944,
751,
1731,
1569,
353,
11078,
501,
716,
353,
2275,
5122,
358,
326,
4073,
7212,
310,
333,
394,
3102,
18,
1021,
3640,
333,
3102,
353,
3627,
598,
1297,
506,
10680,
429,
635,
1234,
18,
15330,
18,
1220,
353,
316,
2719,
358,
326,
1338,
15341,
9606,
1492,
26124,
1234,
18,
15330,
848,
10680,
326,
3325,
756,
434,
326,
7339,
1849,
18,
1234,
18,
15330,
353,
3344,
279,
5100,
287,
873,
3981,
512,
28202,
16,
578,
279,
2596,
6835,
716,
711,
2118,
10799,
358,
741,
29535,
603,
326,
3640,
756,
18,
19412,
7999,
279,
312,
474,
329,
1056,
1865,
326,
3102,
2542,
18,
1220,
4102,
82,
1404,
898,
6967,
16,
1496,
4102,
4620,
326,
8808,
315,
81,
474,
329,
6,
3844,
628,
3214,
312,
28142,
358,
15221,
628,
326,
3102,
501,
11093,
2078,
14467,
16,
1492,
353,
1661,
17,
831,
287,
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,
5068,
4021,
12,
203,
3639,
8370,
751,
745,
892,
389,
6178,
16,
203,
3639,
1731,
745,
892,
389,
8944,
751,
203,
565,
262,
3903,
1338,
15341,
288,
203,
3639,
309,
261,
203,
5411,
401,
3860,
3367,
18,
2159,
4243,
18,
291,
15341,
1887,
31058,
12,
203,
7734,
389,
6178,
18,
7285,
15883,
16,
203,
7734,
1234,
18,
15330,
203,
5411,
262,
203,
3639,
262,
288,
203,
5411,
15226,
2288,
15341,
5621,
203,
3639,
289,
203,
203,
5411,
389,
6178,
18,
307,
18931,
4436,
4921,
405,
374,
597,
203,
5411,
261,
67,
6178,
18,
307,
18931,
4649,
4921,
1545,
203,
7734,
389,
6178,
18,
307,
18931,
4436,
4921,
747,
203,
7734,
389,
6178,
18,
307,
18931,
4436,
4921,
1648,
1203,
18,
5508,
13,
203,
3639,
262,
288,
203,
5411,
15226,
1962,
4021,
809,
5621,
203,
3639,
289,
203,
203,
3639,
309,
261,
67,
6178,
18,
81,
474,
329,
480,
374,
13,
288,
203,
5411,
15226,
1962,
4021,
809,
5621,
203,
3639,
289,
203,
203,
3639,
8463,
63,
6178,
548,
65,
273,
389,
6178,
31,
203,
3639,
3626,
8370,
15334,
12,
6178,
548,
16,
389,
6178,
16,
389,
8944,
751,
1769,
203,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-03-23
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMathUpgradeable {
/**
* @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;
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface IERC20Detailed {
function decimals() external view returns (uint8);
}
contract DeHiveTokensale is OwnableUpgradeable, PausableUpgradeable {
using SafeMathUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
/**
* EVENTS
**/
event DHVPurchased(address indexed user, address indexed purchaseToken, uint256 dhvAmount);
event TokensClaimed(address indexed user, uint256 dhvAmount);
/**
* CONSTANTS
**/
// *** TOKENSALE PARAMETERS START ***
uint256 public constant PRECISION = 1000000; //Up to 0.000001
uint256 public constant PRE_SALE_START = 1616594400; //Mar 24 2021 14:00:00 GMT
uint256 public constant PRE_SALE_END = 1616803140; //Mar 26 2021 23:59:00 GMT
uint256 public constant PUBLIC_SALE_START = 1618408800; //Apr 14 2021 14:00:00 GMT
uint256 public constant PUBLIC_SALE_END = 1618790340; //Apr 18 2021 23:59:00 GMT
uint256 public constant PRE_SALE_DHV_POOL = 450000 * 10 ** 18; // 5% DHV in total in presale pool
uint256 public constant PRE_SALE_DHV_NUX_POOL = 50000 * 10 ** 18; //
uint256 public constant PUBLIC_SALE_DHV_POOL = 1100000 * 10 ** 18; // 11% DHV in public sale pool
uint256 private constant WITHDRAWAL_PERIOD = 365 * 24 * 60 * 60; //1 year
// *** TOKENSALE PARAMETERS END ***
/***
* STORAGE
***/
uint256 public maxTokensAmount;
uint256 public maxGasPrice;
// *** VESTING PARAMETERS START ***
uint256 public vestingStart;
uint256 public vestingDuration; /*= 305 * 24 * 60 * 60*/ //305 days - until Apr 30 2021 00:00:00 GMT
// *** VESTING PARAMETERS END ***
address public DHVToken;
address internal USDTToken; /*= 0xdAC17F958D2ee523a2206206994597C13D831ec7 */
address internal DAIToken; /*= 0x6B175474E89094C44Da98b954EedeAC495271d0F*/
address internal NUXToken; /*= 0x89bD2E7e388fAB44AE88BEf4e1AD12b4F1E0911c*/
mapping (address => uint256) public purchased;
mapping (address => uint256) internal _claimed;
uint256 public purchasedWithNUX;
uint256 public purchasedPreSale;
uint256 public purchasedPublicSale;
uint256 public ETHRate;
mapping (address => uint256) public rates;
address private _treasury;
/***
* MODIFIERS
***/
/**
* @dev Throws if called with not supported token.
*/
modifier supportedCoin(address _token) {
require(_token == USDTToken || _token == DAIToken, "Token not supported");
_;
}
/**
* @dev Throws if called when no ongoing pre-sale or public sale.
*/
modifier onlySale() {
require(_isPreSale() || _isPublicSale(), "Sale stages are over or not started");
_;
}
/**
* @dev Throws if called when no ongoing pre-sale or public sale.
*/
modifier onlyPreSale() {
require(_isPreSale(), "Presale stages are over or not started");
_;
}
/**
* @dev Throws if sale stage is ongoing.
*/
modifier notOnSale() {
require(!_isPreSale(), "Presale is not over");
require(!_isPublicSale(), "Sale is not over");
_;
}
/**
* @dev Throws if gas price exceeds gas limit.
*/
modifier correctGas() {
require(maxGasPrice == 0 || tx.gasprice <= maxGasPrice, "Gas price exceeds limit");
_;
}
/***
* INITIALIZER AND SETTINGS
***/
/**
* @notice Initializes the contract with correct addresses settings
* @param treasury Address of the DeHive protocol's treasury where funds from sale go to
* @param dhv DHVToken mainnet address
*/
function initialize(address treasury, address dhv) public initializer {
require(treasury != address(0), "Zero address");
require(dhv != address(0), "Zero address");
__Ownable_init();
__Pausable_init();
_treasury = treasury;
DHVToken = dhv;
DAIToken = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
USDTToken = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
NUXToken = 0x89bD2E7e388fAB44AE88BEf4e1AD12b4F1E0911c;
vestingStart = 0;
vestingDuration = 305 * 24 * 60 * 60;
maxTokensAmount = 49600 * (10 ** 18); // around 50 ETH
}
/**
* @notice Updates current vesting start time. Can be used once
* @param _vestingStart New vesting start time
*/
function adminSetVestingStart(uint256 _vestingStart) virtual external onlyOwner{
require(vestingStart == 0, "Vesting start is already set");
require(_vestingStart > PUBLIC_SALE_END && block.timestamp < _vestingStart, "Incorrect time provided");
vestingStart = _vestingStart;
}
/**
* @notice Sets the rate for the chosen token based on the contracts precision
* @param _token ERC20 token address or zero address for ETH
* @param _rate Exchange rate based on precision (e.g. _rate = PRECISION corresponds to 1:1)
*/
function adminSetRates(address _token, uint256 _rate) external onlyOwner {
if (_token == address(0))
ETHRate = _rate;
else
rates[_token] = _rate;
}
/**
* @notice Allows owner to change the treasury address. Treasury is the address where all funds from sale go to
* @param treasury New treasury address
*/
function adminSetTreasury(address treasury) external onlyOwner notOnSale {
_treasury = treasury;
}
/**
* @notice Allows owner to change max allowed DHV token per address.
* @param _maxDHV New max DHV amount
*/
function adminSetMaxDHV(uint256 _maxDHV) external onlyOwner {
maxTokensAmount = _maxDHV;
}
/**
* @notice Allows owner to change the max allowed gas price. Prevents gas wars
* @param _maxGasPrice New max gas price
*/
function adminSetMaxGasPrice(uint256 _maxGasPrice) external onlyOwner {
maxGasPrice = _maxGasPrice;
}
/**
* @notice Stops purchase functions. Owner only
*/
function adminPause() external onlyOwner {
_pause();
}
/**
* @notice Unpauses purchase functions. Owner only
*/
function adminUnpause() external onlyOwner {
_unpause();
}
/***
* PURCHASE FUNCTIONS
***/
/**
* @notice For purchase with ETH
*/
receive() external virtual payable onlySale whenNotPaused {
_purchaseDHVwithETH();
}
/**
* @notice For purchase with allowed stablecoin (USDT and DAI)
* @param ERC20token Address of the token to be paid in
* @param ERC20amount Amount of the token to be paid in
*/
function purchaseDHVwithERC20(address ERC20token, uint256 ERC20amount) external onlySale supportedCoin(ERC20token) whenNotPaused correctGas {
require(ERC20amount > 0, "Zero amount");
uint256 purchaseAmount = _calcPurchaseAmount(ERC20token, ERC20amount);
require(maxTokensAmount == 0 ||
purchaseAmount.add(purchased[msg.sender]) <= maxTokensAmount, "Maximum allowed exceeded");
if (_isPreSale()) {
require(purchasedPreSale.add(purchaseAmount) <= PRE_SALE_DHV_POOL, "Not enough DHV in presale pool");
purchasedPreSale = purchasedPreSale.add(purchaseAmount);
} else {
require(purchaseAmount <= publicSaleAvailableDHV(), "Not enough DHV in sale pool");
purchasedPublicSale = purchasedPublicSale.add(purchaseAmount);
}
IERC20Upgradeable(ERC20token).safeTransferFrom(_msgSender(), _treasury, ERC20amount); // send ERC20 to Treasury
purchased[_msgSender()] = purchased[_msgSender()].add(purchaseAmount);
emit DHVPurchased(_msgSender(), ERC20token, purchaseAmount);
}
/**
* @notice For purchase with NUX token only. Available only for tokensale
* @param nuxAmount Amount of the NUX token
*/
function purchaseDHVwithNUX(uint256 nuxAmount) external onlyPreSale whenNotPaused correctGas {
require(nuxAmount > 0, "Zero amount");
uint256 purchaseAmount = _calcPurchaseAmount(NUXToken, nuxAmount);
require(maxTokensAmount == 0 ||
purchaseAmount.add(purchased[msg.sender]) <= maxTokensAmount, "Maximum allowed exceeded");
require(purchasedWithNUX.add(purchaseAmount) <= PRE_SALE_DHV_NUX_POOL, "Not enough DHV in NUX pool");
purchasedWithNUX = purchasedWithNUX.add(purchaseAmount);
IERC20Upgradeable(NUXToken).safeTransferFrom(_msgSender(), _treasury, nuxAmount);
purchased[_msgSender()] = purchased[_msgSender()].add(purchaseAmount);
emit DHVPurchased(_msgSender(), NUXToken, purchaseAmount);
}
/**
* @notice For purchase with ETH. ETH is left on the contract until withdrawn to treasury
*/
function purchaseDHVwithETH() external payable onlySale whenNotPaused {
require(msg.value > 0, "No ETH sent");
_purchaseDHVwithETH();
}
function _purchaseDHVwithETH() correctGas private {
uint256 purchaseAmount = _calcEthPurchaseAmount(msg.value);
require(maxTokensAmount == 0 ||
purchaseAmount.add(purchased[msg.sender]) <= maxTokensAmount, "Maximum allowed exceeded");
if (_isPreSale()) {
require(purchasedPreSale.add(purchaseAmount) <= PRE_SALE_DHV_POOL, "Not enough DHV in presale pool");
purchasedPreSale = purchasedPreSale.add(purchaseAmount);
} else {
require(purchaseAmount <= publicSaleAvailableDHV(), "Not enough DHV in sale pool");
purchasedPublicSale = purchasedPublicSale.add(purchaseAmount);
}
purchased[_msgSender()] = purchased[_msgSender()].add(purchaseAmount);
payable(_treasury).transfer(msg.value);
emit DHVPurchased(_msgSender(), address(0), purchaseAmount);
}
/**
* @notice Function to get available on public sale amount of DHV
* @notice Unsold NUX pool and pre-sale pool go to public sale
* @return The amount of the token released.
*/
function publicSaleAvailableDHV() public view returns(uint256) {
return PUBLIC_SALE_DHV_POOL.sub(purchasedPublicSale) +
PRE_SALE_DHV_POOL.sub(purchasedPreSale) +
PRE_SALE_DHV_NUX_POOL.sub(purchasedWithNUX);
}
/**
* @notice Function for the administrator to withdraw token (except DHV)
* @notice Withdrawals allowed only if there is no sale pending stage
* @param ERC20token Address of ERC20 token to withdraw from the contract
*/
function adminWithdrawERC20(address ERC20token) external onlyOwner notOnSale {
require(ERC20token != DHVToken || _canWithdrawDHV(), "DHV withdrawal is forbidden");
uint256 tokenBalance = IERC20Upgradeable(ERC20token).balanceOf(address(this));
IERC20Upgradeable(ERC20token).safeTransfer(_treasury, tokenBalance);
}
/**
* @notice Function for the administrator to withdraw ETH for refunds
* @notice Withdrawals allowed only if there is no sale pending stage
*/
function adminWithdraw() external onlyOwner notOnSale {
require(address(this).balance > 0, "Nothing to withdraw");
(bool success, ) = _treasury.call{value: address(this).balance}("");
require(success, "Transfer failed");
}
/**
* @notice Returns DHV amount for 1 external token
* @param _token External toke (DAI, USDT, NUX, 0 address for ETH)
*/
function rateForToken(address _token) external view returns(uint256) {
if (_token == address(0)) {
return _calcEthPurchaseAmount(10**18);
}
else {
return _calcPurchaseAmount(_token, 10**( uint256(IERC20Detailed(_token).decimals()) ));
}
}
/***
* VESTING INTERFACE
***/
/**
* @notice Transfers available for claim vested tokens to the user.
*/
function claim() external {
require(vestingStart!=0, "Vesting start is not set");
require(_isPublicSaleOver(), "Not allowed to claim now");
uint256 unclaimed = claimable(_msgSender());
require(unclaimed > 0, "TokenVesting: no tokens are due");
_claimed[_msgSender()] = _claimed[_msgSender()].add(unclaimed);
IERC20Upgradeable(DHVToken).safeTransfer(_msgSender(), unclaimed);
emit TokensClaimed(_msgSender(), unclaimed);
}
/**
* @notice Gets the amount of tokens the user has already claimed
* @param _user Address of the user who purchased tokens
* @return The amount of the token claimed.
*/
function claimed(address _user) external view returns (uint256) {
return _claimed[_user];
}
/**
* @notice Calculates the amount that has already vested but hasn't been claimed yet.
* @param _user Address of the user who purchased tokens
* @return The amount of the token vested and unclaimed.
*/
function claimable(address _user) public view returns (uint256) {
return _vestedAmount(_user).sub(_claimed[_user]);
}
/**
* @dev Calculates the amount that has already vested.
* @param _user Address of the user who purchased tokens
* @return Amount of DHV already vested
*/
function _vestedAmount(address _user) private view returns (uint256) {
if (block.timestamp >= vestingStart.add(vestingDuration)) {
return purchased[_user];
} else {
return purchased[_user].mul(block.timestamp.sub(vestingStart)).div(vestingDuration);
}
}
/***
* INTERNAL HELPERS
***/
/**
* @dev Checks if presale stage is on-going.
* @return True is presale is active
*/
function _isPreSale() virtual internal view returns (bool) {
return (block.timestamp >= PRE_SALE_START && block.timestamp < PRE_SALE_END);
}
/**
* @dev Checks if public sale stage is on-going.
* @return True is public sale is active
*/
function _isPublicSale() virtual internal view returns (bool) {
return (block.timestamp >= PUBLIC_SALE_START && block.timestamp < PUBLIC_SALE_END);
}
/**
* @dev Checks if public sale stage is over.
* @return True is public sale is over
*/
function _isPublicSaleOver() virtual internal view returns (bool) {
return (block.timestamp >= PUBLIC_SALE_END);
}
/**
* @dev Checks if public sale stage is over.
* @return True is public sale is over
*/
function _canWithdrawDHV() virtual internal view returns (bool) {
return (block.timestamp >= vestingStart.add(WITHDRAWAL_PERIOD) );
}
/**
* @dev Calculates DHV amount based on rate and token.
* @param _token Supported ERC20 token
* @param _amount Token amount to convert to DHV
* @return DHV amount
*/
function _calcPurchaseAmount(address _token, uint256 _amount) private view returns (uint256) {
uint256 purchaseAmount = _amount.mul(rates[_token]).div(PRECISION);
require(purchaseAmount > 0, "Rates not set");
uint8 _decimals = IERC20Detailed(_token).decimals();
if (_decimals < 18) {
purchaseAmount = purchaseAmount.mul(10 ** (18 - uint256(_decimals)));
}
return purchaseAmount;
}
/**
* @dev Calculates DHV amount based on rate and ETH amount.
* @param _amount ETH amount to convert to DHV
* @return DHV amount
*/
function _calcEthPurchaseAmount(uint256 _amount) private view returns (uint256) {
uint256 purchaseAmount = _amount.mul(ETHRate).div(PRECISION);
require(purchaseAmount > 0, "Rates not set");
return purchaseAmount;
}
}
contract DeHiveTokensaleMock is DeHiveTokensale {
uint256 public preSaleStart;
uint256 public preSaleEnd;
uint256 public publicSaleStart;
uint256 public publicSaleEnd;
function initialize(address _DAIToken,
address _USDTToken,
address _NUXToken,
address treasury,
address dhv) public initializer
{
DeHiveTokensale.initialize(treasury, dhv);
USDTToken = _USDTToken;
DAIToken = _DAIToken;
NUXToken = _NUXToken;
preSaleStart = 1616594400; //Mar 24 2021 14:00:00 GMT
preSaleEnd = 1616803140; //Mar 26 2021 23:59:00 GMT
publicSaleStart = 1618408800; //Apr 14 2021 14:00:00 GMT
publicSaleEnd = 1618790340; //Apr 18 2021 23:59:00 GMT
}
function getUSDTToken() public view returns(address){
return USDTToken;
}
function getDAIToken() public view returns(address){
return DAIToken;
}
function getNUXToken() public view returns(address){
return NUXToken;
}
function setPreSale(uint256 start, uint256 end) public {
preSaleStart = start;
preSaleEnd = end;
}
function setPublicSale(uint256 start, uint256 end) public {
publicSaleStart = start;
publicSaleEnd = end;
}
function adminSetVestingDuration(uint256 _duration) public {
vestingDuration = _duration;
}
function adminSetVestingStart(uint256 _vestingStart) override external {
vestingStart = _vestingStart;
}
function _isPreSale() override internal view returns (bool) {
return (block.timestamp >= preSaleStart && block.timestamp < preSaleEnd);
}
function _isPublicSale() override internal view returns (bool) {
return (block.timestamp >= publicSaleStart && block.timestamp < publicSaleEnd);
}
function _isPublicSaleOver() override internal view returns (bool) {
return (block.timestamp >= publicSaleEnd);
}
}
|
* @dev Checks if presale stage is on-going. @return True is presale is active/
|
function _isPreSale() virtual internal view returns (bool) {
return (block.timestamp >= PRE_SALE_START && block.timestamp < PRE_SALE_END);
}
| 229,580 |
[
1,
4081,
309,
4075,
5349,
6009,
353,
603,
17,
8162,
18,
327,
1053,
353,
4075,
5349,
353,
2695,
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,
445,
389,
291,
1386,
30746,
1435,
5024,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
261,
2629,
18,
5508,
1545,
7071,
67,
5233,
900,
67,
7570,
597,
1203,
18,
5508,
411,
7071,
67,
5233,
900,
67,
4415,
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
] |
pragma solidity 0.6.6;
library SafeMath {
function ADD145(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
function MUL161(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV829(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD954(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
library SignedSafeMath {
int256 constant private _int256_min421 = -2**255; //inject NONSTANDARD NAMING
function MUL161(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _int256_min421), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
function DIV829(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _int256_min421), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
function SUB54(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
function ADD145(int256 a, int256 b) internal pure returns (int256) { //inject NONSTANDARD NAMING
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
function AVG682(int256 _a, int256 _b) //inject NONSTANDARD NAMING
internal
pure
returns (int256)
{
if ((_a < 0 && _b > 0) || (_a > 0 && _b < 0)) {
return ADD145(_a, _b) / 2;
}
int256 remainder = (_a % 2 + _b % 2) / 2;
return ADD145(ADD145(_a / 2, _b / 2), remainder);
}
}
library Median {
using SignedSafeMath for int256;
int256 constant int_max839 = 2**255-1; //inject NONSTANDARD NAMING
function CALCULATE363(int256[] memory list) //inject NONSTANDARD NAMING
internal
pure
returns (int256)
{
return CALCULATEINPLACE706(COPY192(list));
}
function CALCULATEINPLACE706(int256[] memory list) //inject NONSTANDARD NAMING
internal
pure
returns (int256)
{
require(0 < list.length, "list must not be empty");
uint256 len = list.length;
uint256 middleIndex = len / 2;
if (len % 2 == 0) {
int256 median1;
int256 median2;
(median1, median2) = QUICKSELECTTWO107(list, 0, len - 1, middleIndex - 1, middleIndex);
return SignedSafeMath.AVG682(median1, median2);
} else {
return QUICKSELECT317(list, 0, len - 1, middleIndex);
}
}
uint256 constant shortselecttwo_max_length191 = 7; //inject NONSTANDARD NAMING
function SHORTSELECTTWO879( //inject NONSTANDARD NAMING
int256[] memory list,
uint256 lo,
uint256 hi,
uint256 k1,
uint256 k2
)
private
pure
returns (int256 k1th, int256 k2th)
{
// Uses an optimal sorting network (https://en.wikipedia.org/wiki/Sorting_network)
// for lists of length 7. Network layout is taken from
// http://jgamble.ripco.net/cgi-bin/nw.cgi?inputs=7&algorithm=hibbard&output=svg
uint256 len = hi + 1 - lo;
int256 x0 = list[lo + 0];
int256 x1 = 1 < len ? list[lo + 1] : int_max839;
int256 x2 = 2 < len ? list[lo + 2] : int_max839;
int256 x3 = 3 < len ? list[lo + 3] : int_max839;
int256 x4 = 4 < len ? list[lo + 4] : int_max839;
int256 x5 = 5 < len ? list[lo + 5] : int_max839;
int256 x6 = 6 < len ? list[lo + 6] : int_max839;
if (x0 > x1) {(x0, x1) = (x1, x0);}
if (x2 > x3) {(x2, x3) = (x3, x2);}
if (x4 > x5) {(x4, x5) = (x5, x4);}
if (x0 > x2) {(x0, x2) = (x2, x0);}
if (x1 > x3) {(x1, x3) = (x3, x1);}
if (x4 > x6) {(x4, x6) = (x6, x4);}
if (x1 > x2) {(x1, x2) = (x2, x1);}
if (x5 > x6) {(x5, x6) = (x6, x5);}
if (x0 > x4) {(x0, x4) = (x4, x0);}
if (x1 > x5) {(x1, x5) = (x5, x1);}
if (x2 > x6) {(x2, x6) = (x6, x2);}
if (x1 > x4) {(x1, x4) = (x4, x1);}
if (x3 > x6) {(x3, x6) = (x6, x3);}
if (x2 > x4) {(x2, x4) = (x4, x2);}
if (x3 > x5) {(x3, x5) = (x5, x3);}
if (x3 > x4) {(x3, x4) = (x4, x3);}
uint256 index1 = k1 - lo;
if (index1 == 0) {k1th = x0;}
else if (index1 == 1) {k1th = x1;}
else if (index1 == 2) {k1th = x2;}
else if (index1 == 3) {k1th = x3;}
else if (index1 == 4) {k1th = x4;}
else if (index1 == 5) {k1th = x5;}
else if (index1 == 6) {k1th = x6;}
else {revert("k1 out of bounds");}
uint256 index2 = k2 - lo;
if (k1 == k2) {return (k1th, k1th);}
else if (index2 == 0) {return (k1th, x0);}
else if (index2 == 1) {return (k1th, x1);}
else if (index2 == 2) {return (k1th, x2);}
else if (index2 == 3) {return (k1th, x3);}
else if (index2 == 4) {return (k1th, x4);}
else if (index2 == 5) {return (k1th, x5);}
else if (index2 == 6) {return (k1th, x6);}
else {revert("k2 out of bounds");}
}
function QUICKSELECT317(int256[] memory list, uint256 lo, uint256 hi, uint256 k) //inject NONSTANDARD NAMING
private
pure
returns (int256 kth)
{
require(lo <= k);
require(k <= hi);
while (lo < hi) {
if (hi - lo < shortselecttwo_max_length191) {
int256 ignore;
(kth, ignore) = SHORTSELECTTWO879(list, lo, hi, k, k);
return kth;
}
uint256 pivotIndex = PARTITION723(list, lo, hi);
if (k <= pivotIndex) {
// since pivotIndex < (original hi passed to partition),
// termination is guaranteed in this case
hi = pivotIndex;
} else {
// since (original lo passed to partition) <= pivotIndex,
// termination is guaranteed in this case
lo = pivotIndex + 1;
}
}
return list[lo];
}
function QUICKSELECTTWO107( //inject NONSTANDARD NAMING
int256[] memory list,
uint256 lo,
uint256 hi,
uint256 k1,
uint256 k2
)
internal // for testing
pure
returns (int256 k1th, int256 k2th)
{
require(k1 < k2);
require(lo <= k1 && k1 <= hi);
require(lo <= k2 && k2 <= hi);
while (true) {
if (hi - lo < shortselecttwo_max_length191) {
return SHORTSELECTTWO879(list, lo, hi, k1, k2);
}
uint256 pivotIdx = PARTITION723(list, lo, hi);
if (k2 <= pivotIdx) {
hi = pivotIdx;
} else if (pivotIdx < k1) {
lo = pivotIdx + 1;
} else {
assert(k1 <= pivotIdx && pivotIdx < k2);
k1th = QUICKSELECT317(list, lo, pivotIdx, k1);
k2th = QUICKSELECT317(list, pivotIdx + 1, hi, k2);
return (k1th, k2th);
}
}
}
function PARTITION723(int256[] memory list, uint256 lo, uint256 hi) //inject NONSTANDARD NAMING
private
pure
returns (uint256)
{
// We don't care about overflow of the addition, because it would require a list
// larger than any feasible computer's memory.
int256 pivot = list[(lo + hi) / 2];
lo -= 1; // this can underflow. that's intentional.
hi += 1;
while (true) {
do {
lo += 1;
} while (list[lo] < pivot);
do {
hi -= 1;
} while (list[hi] > pivot);
if (lo < hi) {
(list[lo], list[hi]) = (list[hi], list[lo]);
} else {
// Let orig_lo and orig_hi be the original values of lo and hi passed to partition.
// Then, hi < orig_hi, because hi decreases *strictly* monotonically
// in each loop iteration and
// - either list[orig_hi] > pivot, in which case the first loop iteration
// will achieve hi < orig_hi;
// - or list[orig_hi] <= pivot, in which case at least two loop iterations are
// needed:
// - lo will have to stop at least once in the interval
// [orig_lo, (orig_lo + orig_hi)/2]
// - (orig_lo + orig_hi)/2 < orig_hi
return hi;
}
}
}
function COPY192(int256[] memory list) //inject NONSTANDARD NAMING
private
pure
returns(int256[] memory)
{
int256[] memory list2 = new int256[](list.length);
for (uint256 i = 0; i < list.length; i++) {
list2[i] = list[i];
}
return list2;
}
}
contract Owned {
address payable public owner;
address private pendingOwner;
event OWNERSHIPTRANSFERREQUESTED940( //inject NONSTANDARD NAMING
address indexed from,
address indexed to
);
event OWNERSHIPTRANSFERRED48( //inject NONSTANDARD NAMING
address indexed from,
address indexed to
);
constructor() public {
owner = msg.sender;
}
function TRANSFEROWNERSHIP383(address _to) //inject NONSTANDARD NAMING
external
ONLYOWNER6()
{
pendingOwner = _to;
emit OWNERSHIPTRANSFERREQUESTED940(owner, _to);
}
function ACCEPTOWNERSHIP965() //inject NONSTANDARD NAMING
external
{
require(msg.sender == pendingOwner, "Must be proposed owner");
address oldOwner = owner;
owner = msg.sender;
pendingOwner = address(0);
emit OWNERSHIPTRANSFERRED48(oldOwner, msg.sender);
}
modifier ONLYOWNER6() { //inject NONSTANDARD NAMING
require(msg.sender == owner, "Only callable by owner");
_;
}
}
library SafeMath128 {
function ADD145(uint128 a, uint128 b) internal pure returns (uint128) { //inject NONSTANDARD NAMING
uint128 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB54(uint128 a, uint128 b) internal pure returns (uint128) { //inject NONSTANDARD NAMING
require(b <= a, "SafeMath: subtraction overflow");
uint128 c = a - b;
return c;
}
function MUL161(uint128 a, uint128 b) internal pure returns (uint128) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint128 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV829(uint128 a, uint128 b) internal pure returns (uint128) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint128 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD954(uint128 a, uint128 b) internal pure returns (uint128) { //inject NONSTANDARD NAMING
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
library SafeMath32 {
function ADD145(uint32 a, uint32 b) internal pure returns (uint32) { //inject NONSTANDARD NAMING
uint32 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB54(uint32 a, uint32 b) internal pure returns (uint32) { //inject NONSTANDARD NAMING
require(b <= a, "SafeMath: subtraction overflow");
uint32 c = a - b;
return c;
}
function MUL161(uint32 a, uint32 b) internal pure returns (uint32) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint32 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV829(uint32 a, uint32 b) internal pure returns (uint32) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint32 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD954(uint32 a, uint32 b) internal pure returns (uint32) { //inject NONSTANDARD NAMING
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
library SafeMath64 {
function ADD145(uint64 a, uint64 b) internal pure returns (uint64) { //inject NONSTANDARD NAMING
uint64 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB54(uint64 a, uint64 b) internal pure returns (uint64) { //inject NONSTANDARD NAMING
require(b <= a, "SafeMath: subtraction overflow");
uint64 c = a - b;
return c;
}
function MUL161(uint64 a, uint64 b) internal pure returns (uint64) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint64 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV829(uint64 a, uint64 b) internal pure returns (uint64) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint64 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD954(uint64 a, uint64 b) internal pure returns (uint64) { //inject NONSTANDARD NAMING
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
interface AggregatorInterface {
function LATESTANSWER348() external view returns (int256); //inject NONSTANDARD NAMING
function LATESTTIMESTAMP303() external view returns (uint256); //inject NONSTANDARD NAMING
function LATESTROUND494() external view returns (uint256); //inject NONSTANDARD NAMING
function GETANSWER896(uint256 roundId) external view returns (int256); //inject NONSTANDARD NAMING
function GETTIMESTAMP461(uint256 roundId) external view returns (uint256); //inject NONSTANDARD NAMING
event ANSWERUPDATED260(int256 indexed current, uint256 indexed roundId, uint256 updatedAt); //inject NONSTANDARD NAMING
event NEWROUND740(uint256 indexed roundId, address indexed startedBy, uint256 startedAt); //inject NONSTANDARD NAMING
}
interface AggregatorV3Interface {
function DECIMALS461() external view returns (uint8); //inject NONSTANDARD NAMING
function DESCRIPTION688() external view returns (string memory); //inject NONSTANDARD NAMING
function VERSION47() external view returns (uint256); //inject NONSTANDARD NAMING
// 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 GETROUNDDATA766(uint80 _roundId) //inject NONSTANDARD NAMING
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function LATESTROUNDDATA762() //inject NONSTANDARD NAMING
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
{
}
interface AggregatorValidatorInterface {
function VALIDATE11( //inject NONSTANDARD NAMING
uint256 previousRoundId,
int256 previousAnswer,
uint256 currentRoundId,
int256 currentAnswer
) external returns (bool);
}
interface LinkTokenInterface {
function ALLOWANCE493(address owner, address spender) external view returns (uint256 remaining); //inject NONSTANDARD NAMING
function APPROVE867(address spender, uint256 value) external returns (bool success); //inject NONSTANDARD NAMING
function BALANCEOF315(address owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING
function DECIMALS461() external view returns (uint8 decimalPlaces); //inject NONSTANDARD NAMING
function DECREASEAPPROVAL361(address spender, uint256 addedValue) external returns (bool success); //inject NONSTANDARD NAMING
function INCREASEAPPROVAL792(address spender, uint256 subtractedValue) external; //inject NONSTANDARD NAMING
function NAME612() external view returns (string memory tokenName); //inject NONSTANDARD NAMING
function SYMBOL16() external view returns (string memory tokenSymbol); //inject NONSTANDARD NAMING
function TOTALSUPPLY470() external view returns (uint256 totalTokensIssued); //inject NONSTANDARD NAMING
function TRANSFER233(address to, uint256 value) external returns (bool success); //inject NONSTANDARD NAMING
function TRANSFERANDCALL808(address to, uint256 value, bytes calldata data) external returns (bool success); //inject NONSTANDARD NAMING
function TRANSFERFROM838(address from, address to, uint256 value) external returns (bool success); //inject NONSTANDARD NAMING
}
contract FluxAggregator is AggregatorV2V3Interface, Owned {
using SafeMath for uint256;
using SafeMath128 for uint128;
using SafeMath64 for uint64;
using SafeMath32 for uint32;
struct Round {
int256 answer;
uint64 startedAt;
uint64 updatedAt;
uint32 answeredInRound;
}
struct RoundDetails {
int256[] submissions;
uint32 maxSubmissions;
uint32 minSubmissions;
uint32 timeout;
uint128 paymentAmount;
}
struct OracleStatus {
uint128 withdrawable;
uint32 startingRound;
uint32 endingRound;
uint32 lastReportedRound;
uint32 lastStartedRound;
int256 latestSubmission;
uint16 index;
address admin;
address pendingAdmin;
}
struct Requester {
bool authorized;
uint32 delay;
uint32 lastStartedRound;
}
struct Funds {
uint128 available;
uint128 allocated;
}
LinkTokenInterface public linkToken;
AggregatorValidatorInterface public validator;
// Round related params
uint128 public paymentAmount;
uint32 public maxSubmissionCount;
uint32 public minSubmissionCount;
uint32 public restartDelay;
uint32 public timeout;
uint8 public override decimals;
string public override description;
int256 immutable public minSubmissionValue;
int256 immutable public maxSubmissionValue;
uint256 constant public override version911 = 3; //inject NONSTANDARD NAMING
uint256 constant private reserve_rounds982 = 2; //inject NONSTANDARD NAMING
uint256 constant private max_oracle_count410 = 77; //inject NONSTANDARD NAMING
uint32 constant private round_max162 = 2**32-1; //inject NONSTANDARD NAMING
uint256 private constant validator_gas_limit564 = 100000; //inject NONSTANDARD NAMING
// An error specific to the Aggregator V3 Interface, to prevent possible
// confusion around accidentally reading unset values as reported values.
string constant private v3_no_data_error636 = "No data present"; //inject NONSTANDARD NAMING
uint32 private reportingRoundId;
uint32 internal latestRoundId;
mapping(address => OracleStatus) private oracles;
mapping(uint32 => Round) internal rounds;
mapping(uint32 => RoundDetails) internal details;
mapping(address => Requester) internal requesters;
address[] private oracleAddresses;
Funds private recordedFunds;
event AVAILABLEFUNDSUPDATED487( //inject NONSTANDARD NAMING
uint256 indexed amount
);
event ROUNDDETAILSUPDATED240( //inject NONSTANDARD NAMING
uint128 indexed paymentAmount,
uint32 indexed minSubmissionCount,
uint32 indexed maxSubmissionCount,
uint32 restartDelay,
uint32 timeout // measured in seconds
);
event ORACLEPERMISSIONSUPDATED311( //inject NONSTANDARD NAMING
address indexed oracle,
bool indexed whitelisted
);
event ORACLEADMINUPDATED140( //inject NONSTANDARD NAMING
address indexed oracle,
address indexed newAdmin
);
event ORACLEADMINUPDATEREQUESTED729( //inject NONSTANDARD NAMING
address indexed oracle,
address admin,
address newAdmin
);
event SUBMISSIONRECEIVED162( //inject NONSTANDARD NAMING
int256 indexed submission,
uint32 indexed round,
address indexed oracle
);
event REQUESTERPERMISSIONSSET676( //inject NONSTANDARD NAMING
address indexed requester,
bool authorized,
uint32 delay
);
event VALIDATORUPDATED807( //inject NONSTANDARD NAMING
address indexed previous,
address indexed current
);
constructor(
address _link,
uint128 _paymentAmount,
uint32 _timeout,
address _validator,
int256 _minSubmissionValue,
int256 _maxSubmissionValue,
uint8 _decimals,
string memory _description
) public {
linkToken = LinkTokenInterface(_link);
UPDATEFUTUREROUNDS948(_paymentAmount, 0, 0, 0, _timeout);
SETVALIDATOR301(_validator);
minSubmissionValue = _minSubmissionValue;
maxSubmissionValue = _maxSubmissionValue;
decimals = _decimals;
description = _description;
rounds[0].updatedAt = uint64(block.timestamp.SUB54(uint256(_timeout)));
}
function SUBMIT159(uint256 _roundId, int256 _submission) //inject NONSTANDARD NAMING
external
{
bytes memory error = VALIDATEORACLEROUND243(msg.sender, uint32(_roundId));
require(_submission >= minSubmissionValue, "value below minSubmissionValue");
require(_submission <= maxSubmissionValue, "value above maxSubmissionValue");
require(error.length == 0, string(error));
ORACLEINITIALIZENEWROUND887(uint32(_roundId));
RECORDSUBMISSION761(_submission, uint32(_roundId));
(bool updated, int256 newAnswer) = UPDATEROUNDANSWER573(uint32(_roundId));
PAYORACLE28(uint32(_roundId));
DELETEROUNDDETAILS708(uint32(_roundId));
if (updated) {
VALIDATEANSWER400(uint32(_roundId), newAnswer);
}
}
function CHANGEORACLES743( //inject NONSTANDARD NAMING
address[] calldata _removed,
address[] calldata _added,
address[] calldata _addedAdmins,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay
)
external
ONLYOWNER6()
{
for (uint256 i = 0; i < _removed.length; i++) {
REMOVEORACLE21(_removed[i]);
}
require(_added.length == _addedAdmins.length, "need same oracle and admin count");
require(uint256(ORACLECOUNT250()).ADD145(_added.length) <= max_oracle_count410, "max oracles allowed");
for (uint256 i = 0; i < _added.length; i++) {
ADDORACLE657(_added[i], _addedAdmins[i]);
}
UPDATEFUTUREROUNDS948(paymentAmount, _minSubmissions, _maxSubmissions, _restartDelay, timeout);
}
function UPDATEFUTUREROUNDS948( //inject NONSTANDARD NAMING
uint128 _paymentAmount,
uint32 _minSubmissions,
uint32 _maxSubmissions,
uint32 _restartDelay,
uint32 _timeout
)
public
ONLYOWNER6()
{
uint32 oracleNum = ORACLECOUNT250(); // Save on storage reads
require(_maxSubmissions >= _minSubmissions, "max must equal/exceed min");
require(oracleNum >= _maxSubmissions, "max cannot exceed total");
require(oracleNum == 0 || oracleNum > _restartDelay, "delay cannot exceed total");
require(recordedFunds.available >= REQUIREDRESERVE718(_paymentAmount), "insufficient funds for payment");
if (ORACLECOUNT250() > 0) {
require(_minSubmissions > 0, "min must be greater than 0");
}
paymentAmount = _paymentAmount;
minSubmissionCount = _minSubmissions;
maxSubmissionCount = _maxSubmissions;
restartDelay = _restartDelay;
timeout = _timeout;
emit ROUNDDETAILSUPDATED240(
paymentAmount,
_minSubmissions,
_maxSubmissions,
_restartDelay,
_timeout
);
}
function ALLOCATEDFUNDS634() //inject NONSTANDARD NAMING
external
view
returns (uint128)
{
return recordedFunds.allocated;
}
function AVAILABLEFUNDS625() //inject NONSTANDARD NAMING
external
view
returns (uint128)
{
return recordedFunds.available;
}
function UPDATEAVAILABLEFUNDS50() //inject NONSTANDARD NAMING
public
{
Funds memory funds = recordedFunds;
uint256 nowAvailable = linkToken.BALANCEOF315(address(this)).SUB54(funds.allocated);
if (funds.available != nowAvailable) {
recordedFunds.available = uint128(nowAvailable);
emit AVAILABLEFUNDSUPDATED487(nowAvailable);
}
}
function ORACLECOUNT250() public view returns (uint8) { //inject NONSTANDARD NAMING
return uint8(oracleAddresses.length);
}
function GETORACLES524() external view returns (address[] memory) { //inject NONSTANDARD NAMING
return oracleAddresses;
}
function LATESTANSWER348() //inject NONSTANDARD NAMING
public
view
virtual
override
returns (int256)
{
return rounds[latestRoundId].answer;
}
function LATESTTIMESTAMP303() //inject NONSTANDARD NAMING
public
view
virtual
override
returns (uint256)
{
return rounds[latestRoundId].updatedAt;
}
function LATESTROUND494() //inject NONSTANDARD NAMING
public
view
virtual
override
returns (uint256)
{
return latestRoundId;
}
function GETANSWER896(uint256 _roundId) //inject NONSTANDARD NAMING
public
view
virtual
override
returns (int256)
{
if (VALIDROUNDID399(_roundId)) {
return rounds[uint32(_roundId)].answer;
}
return 0;
}
function GETTIMESTAMP461(uint256 _roundId) //inject NONSTANDARD NAMING
public
view
virtual
override
returns (uint256)
{
if (VALIDROUNDID399(_roundId)) {
return rounds[uint32(_roundId)].updatedAt;
}
return 0;
}
function GETROUNDDATA766(uint80 _roundId) //inject NONSTANDARD NAMING
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
Round memory r = rounds[uint32(_roundId)];
require(r.answeredInRound > 0 && VALIDROUNDID399(_roundId), v3_no_data_error636);
return (
_roundId,
r.answer,
r.startedAt,
r.updatedAt,
r.answeredInRound
);
}
function LATESTROUNDDATA762() //inject NONSTANDARD NAMING
public
view
virtual
override
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return GETROUNDDATA766(latestRoundId);
}
function WITHDRAWABLEPAYMENT432(address _oracle) //inject NONSTANDARD NAMING
external
view
returns (uint256)
{
return oracles[_oracle].withdrawable;
}
function WITHDRAWPAYMENT607(address _oracle, address _recipient, uint256 _amount) //inject NONSTANDARD NAMING
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
// Safe to downcast _amount because the total amount of LINK is less than 2^128.
uint128 amount = uint128(_amount);
uint128 available = oracles[_oracle].withdrawable;
require(available >= amount, "insufficient withdrawable funds");
oracles[_oracle].withdrawable = available.SUB54(amount);
recordedFunds.allocated = recordedFunds.allocated.SUB54(amount);
assert(linkToken.TRANSFER233(_recipient, uint256(amount)));
}
function WITHDRAWFUNDS431(address _recipient, uint256 _amount) //inject NONSTANDARD NAMING
external
ONLYOWNER6()
{
uint256 available = uint256(recordedFunds.available);
require(available.SUB54(REQUIREDRESERVE718(paymentAmount)) >= _amount, "insufficient reserve funds");
require(linkToken.TRANSFER233(_recipient, _amount), "token transfer failed");
UPDATEAVAILABLEFUNDS50();
}
function GETADMIN40(address _oracle) //inject NONSTANDARD NAMING
external
view
returns (address)
{
return oracles[_oracle].admin;
}
function TRANSFERADMIN329(address _oracle, address _newAdmin) //inject NONSTANDARD NAMING
external
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
oracles[_oracle].pendingAdmin = _newAdmin;
emit ORACLEADMINUPDATEREQUESTED729(_oracle, msg.sender, _newAdmin);
}
function ACCEPTADMIN844(address _oracle) //inject NONSTANDARD NAMING
external
{
require(oracles[_oracle].pendingAdmin == msg.sender, "only callable by pending admin");
oracles[_oracle].pendingAdmin = address(0);
oracles[_oracle].admin = msg.sender;
emit ORACLEADMINUPDATED140(_oracle, msg.sender);
}
function REQUESTNEWROUND677() //inject NONSTANDARD NAMING
external
returns (uint80)
{
require(requesters[msg.sender].authorized, "not authorized requester");
uint32 current = reportingRoundId;
require(rounds[current].updatedAt > 0 || TIMEDOUT101(current), "prev round must be supersedable");
uint32 newRoundId = current.ADD145(1);
REQUESTERINITIALIZENEWROUND37(newRoundId);
return newRoundId;
}
function SETREQUESTERPERMISSIONS783(address _requester, bool _authorized, uint32 _delay) //inject NONSTANDARD NAMING
external
ONLYOWNER6()
{
if (requesters[_requester].authorized == _authorized) return;
if (_authorized) {
requesters[_requester].authorized = _authorized;
requesters[_requester].delay = _delay;
} else {
delete requesters[_requester];
}
emit REQUESTERPERMISSIONSSET676(_requester, _authorized, _delay);
}
function ONTOKENTRANSFER807(address, uint256, bytes calldata _data) //inject NONSTANDARD NAMING
external
{
require(_data.length == 0, "transfer doesn't accept calldata");
UPDATEAVAILABLEFUNDS50();
}
function ORACLEROUNDSTATE90(address _oracle, uint32 _queriedRoundId) //inject NONSTANDARD NAMING
external
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
require(msg.sender == tx.origin, "off-chain reading only");
if (_queriedRoundId > 0) {
Round storage round = rounds[_queriedRoundId];
RoundDetails storage details = details[_queriedRoundId];
return (
ELIGIBLEFORSPECIFICROUND479(_oracle, _queriedRoundId),
_queriedRoundId,
oracles[_oracle].latestSubmission,
round.startedAt,
details.timeout,
recordedFunds.available,
ORACLECOUNT250(),
(round.startedAt > 0 ? details.paymentAmount : paymentAmount)
);
} else {
return ORACLEROUNDSTATESUGGESTROUND66(_oracle);
}
}
function SETVALIDATOR301(address _newValidator) //inject NONSTANDARD NAMING
public
ONLYOWNER6()
{
address previous = address(validator);
if (previous != _newValidator) {
validator = AggregatorValidatorInterface(_newValidator);
emit VALIDATORUPDATED807(previous, _newValidator);
}
}
function INITIALIZENEWROUND636(uint32 _roundId) //inject NONSTANDARD NAMING
private
{
UPDATETIMEDOUTROUNDINFO506(_roundId.SUB54(1));
reportingRoundId = _roundId;
RoundDetails memory nextDetails = RoundDetails(
new int256[](0),
maxSubmissionCount,
minSubmissionCount,
timeout,
paymentAmount
);
details[_roundId] = nextDetails;
rounds[_roundId].startedAt = uint64(block.timestamp);
emit NEWROUND740(_roundId, msg.sender, rounds[_roundId].startedAt);
}
function ORACLEINITIALIZENEWROUND887(uint32 _roundId) //inject NONSTANDARD NAMING
private
{
if (!NEWROUND17(_roundId)) return;
uint256 lastStarted = oracles[msg.sender].lastStartedRound; // cache storage reads
if (_roundId <= lastStarted + restartDelay && lastStarted != 0) return;
INITIALIZENEWROUND636(_roundId);
oracles[msg.sender].lastStartedRound = _roundId;
}
function REQUESTERINITIALIZENEWROUND37(uint32 _roundId) //inject NONSTANDARD NAMING
private
{
if (!NEWROUND17(_roundId)) return;
uint256 lastStarted = requesters[msg.sender].lastStartedRound; // cache storage reads
require(_roundId > lastStarted + requesters[msg.sender].delay || lastStarted == 0, "must delay requests");
INITIALIZENEWROUND636(_roundId);
requesters[msg.sender].lastStartedRound = _roundId;
}
function UPDATETIMEDOUTROUNDINFO506(uint32 _roundId) //inject NONSTANDARD NAMING
private
{
if (!TIMEDOUT101(_roundId)) return;
uint32 prevId = _roundId.SUB54(1);
rounds[_roundId].answer = rounds[prevId].answer;
rounds[_roundId].answeredInRound = rounds[prevId].answeredInRound;
rounds[_roundId].updatedAt = uint64(block.timestamp);
delete details[_roundId];
}
function ELIGIBLEFORSPECIFICROUND479(address _oracle, uint32 _queriedRoundId) //inject NONSTANDARD NAMING
private
view
returns (bool _eligible)
{
if (rounds[_queriedRoundId].startedAt > 0) {
return ACCEPTINGSUBMISSIONS813(_queriedRoundId) && VALIDATEORACLEROUND243(_oracle, _queriedRoundId).length == 0;
} else {
return DELAYED922(_oracle, _queriedRoundId) && VALIDATEORACLEROUND243(_oracle, _queriedRoundId).length == 0;
}
}
function ORACLEROUNDSTATESUGGESTROUND66(address _oracle) //inject NONSTANDARD NAMING
private
view
returns (
bool _eligibleToSubmit,
uint32 _roundId,
int256 _latestSubmission,
uint64 _startedAt,
uint64 _timeout,
uint128 _availableFunds,
uint8 _oracleCount,
uint128 _paymentAmount
)
{
Round storage round = rounds[0];
OracleStatus storage oracle = oracles[_oracle];
bool shouldSupersede = oracle.lastReportedRound == reportingRoundId || !ACCEPTINGSUBMISSIONS813(reportingRoundId);
// Instead of nudging oracles to submit to the next round, the inclusion of
// the shouldSupersede bool in the if condition pushes them towards
// submitting in a currently open round.
if (SUPERSEDABLE18(reportingRoundId) && shouldSupersede) {
_roundId = reportingRoundId.ADD145(1);
round = rounds[_roundId];
_paymentAmount = paymentAmount;
_eligibleToSubmit = DELAYED922(_oracle, _roundId);
} else {
_roundId = reportingRoundId;
round = rounds[_roundId];
_paymentAmount = details[_roundId].paymentAmount;
_eligibleToSubmit = ACCEPTINGSUBMISSIONS813(_roundId);
}
if (VALIDATEORACLEROUND243(_oracle, _roundId).length != 0) {
_eligibleToSubmit = false;
}
return (
_eligibleToSubmit,
_roundId,
oracle.latestSubmission,
round.startedAt,
details[_roundId].timeout,
recordedFunds.available,
ORACLECOUNT250(),
_paymentAmount
);
}
function UPDATEROUNDANSWER573(uint32 _roundId) //inject NONSTANDARD NAMING
internal
returns (bool, int256)
{
if (details[_roundId].submissions.length < details[_roundId].minSubmissions) {
return (false, 0);
}
int256 newAnswer = Median.CALCULATEINPLACE706(details[_roundId].submissions);
rounds[_roundId].answer = newAnswer;
rounds[_roundId].updatedAt = uint64(block.timestamp);
rounds[_roundId].answeredInRound = _roundId;
latestRoundId = _roundId;
emit ANSWERUPDATED260(newAnswer, _roundId, now);
return (true, newAnswer);
}
function VALIDATEANSWER400( //inject NONSTANDARD NAMING
uint32 _roundId,
int256 _newAnswer
)
private
{
AggregatorValidatorInterface av = validator; // cache storage reads
if (address(av) == address(0)) return;
uint32 prevRound = _roundId.SUB54(1);
uint32 prevAnswerRoundId = rounds[prevRound].answeredInRound;
int256 prevRoundAnswer = rounds[prevRound].answer;
// We do not want the validator to ever prevent reporting, so we limit its
// gas usage and catch any errors that may arise.
try av.VALIDATE11{gas: validator_gas_limit564}(
prevAnswerRoundId,
prevRoundAnswer,
_roundId,
_newAnswer
) {} catch {}
}
function PAYORACLE28(uint32 _roundId) //inject NONSTANDARD NAMING
private
{
uint128 payment = details[_roundId].paymentAmount;
Funds memory funds = recordedFunds;
funds.available = funds.available.SUB54(payment);
funds.allocated = funds.allocated.ADD145(payment);
recordedFunds = funds;
oracles[msg.sender].withdrawable = oracles[msg.sender].withdrawable.ADD145(payment);
emit AVAILABLEFUNDSUPDATED487(funds.available);
}
function RECORDSUBMISSION761(int256 _submission, uint32 _roundId) //inject NONSTANDARD NAMING
private
{
require(ACCEPTINGSUBMISSIONS813(_roundId), "round not accepting submissions");
details[_roundId].submissions.push(_submission);
oracles[msg.sender].lastReportedRound = _roundId;
oracles[msg.sender].latestSubmission = _submission;
emit SUBMISSIONRECEIVED162(_submission, _roundId, msg.sender);
}
function DELETEROUNDDETAILS708(uint32 _roundId) //inject NONSTANDARD NAMING
private
{
if (details[_roundId].submissions.length < details[_roundId].maxSubmissions) return;
delete details[_roundId];
}
function TIMEDOUT101(uint32 _roundId) //inject NONSTANDARD NAMING
private
view
returns (bool)
{
uint64 startedAt = rounds[_roundId].startedAt;
uint32 roundTimeout = details[_roundId].timeout;
return startedAt > 0 && roundTimeout > 0 && startedAt.ADD145(roundTimeout) < block.timestamp;
}
function GETSTARTINGROUND70(address _oracle) //inject NONSTANDARD NAMING
private
view
returns (uint32)
{
uint32 currentRound = reportingRoundId;
if (currentRound != 0 && currentRound == oracles[_oracle].endingRound) {
return currentRound;
}
return currentRound.ADD145(1);
}
function PREVIOUSANDCURRENTUNANSWERED532(uint32 _roundId, uint32 _rrId) //inject NONSTANDARD NAMING
private
view
returns (bool)
{
return _roundId.ADD145(1) == _rrId && rounds[_rrId].updatedAt == 0;
}
function REQUIREDRESERVE718(uint256 payment) //inject NONSTANDARD NAMING
private
view
returns (uint256)
{
return payment.MUL161(ORACLECOUNT250()).MUL161(reserve_rounds982);
}
function ADDORACLE657( //inject NONSTANDARD NAMING
address _oracle,
address _admin
)
private
{
require(!ORACLEENABLED658(_oracle), "oracle already enabled");
require(_admin != address(0), "cannot set admin to 0");
require(oracles[_oracle].admin == address(0) || oracles[_oracle].admin == _admin, "owner cannot overwrite admin");
oracles[_oracle].startingRound = GETSTARTINGROUND70(_oracle);
oracles[_oracle].endingRound = round_max162;
oracles[_oracle].index = uint16(oracleAddresses.length);
oracleAddresses.push(_oracle);
oracles[_oracle].admin = _admin;
emit ORACLEPERMISSIONSUPDATED311(_oracle, true);
emit ORACLEADMINUPDATED140(_oracle, _admin);
}
function REMOVEORACLE21( //inject NONSTANDARD NAMING
address _oracle
)
private
{
require(ORACLEENABLED658(_oracle), "oracle not enabled");
oracles[_oracle].endingRound = reportingRoundId.ADD145(1);
address tail = oracleAddresses[uint256(ORACLECOUNT250()).SUB54(1)];
uint16 index = oracles[_oracle].index;
oracles[tail].index = index;
delete oracles[_oracle].index;
oracleAddresses[index] = tail;
oracleAddresses.pop();
emit ORACLEPERMISSIONSUPDATED311(_oracle, false);
}
function VALIDATEORACLEROUND243(address _oracle, uint32 _roundId) //inject NONSTANDARD NAMING
private
view
returns (bytes memory)
{
// cache storage reads
uint32 startingRound = oracles[_oracle].startingRound;
uint32 rrId = reportingRoundId;
if (startingRound == 0) return "not enabled oracle";
if (startingRound > _roundId) return "not yet enabled oracle";
if (oracles[_oracle].endingRound < _roundId) return "no longer allowed oracle";
if (oracles[_oracle].lastReportedRound >= _roundId) return "cannot report on previous rounds";
if (_roundId != rrId && _roundId != rrId.ADD145(1) && !PREVIOUSANDCURRENTUNANSWERED532(_roundId, rrId)) return "invalid round to report";
if (_roundId != 1 && !SUPERSEDABLE18(_roundId.SUB54(1))) return "previous round not supersedable";
}
function SUPERSEDABLE18(uint32 _roundId) //inject NONSTANDARD NAMING
private
view
returns (bool)
{
return rounds[_roundId].updatedAt > 0 || TIMEDOUT101(_roundId);
}
function ORACLEENABLED658(address _oracle) //inject NONSTANDARD NAMING
private
view
returns (bool)
{
return oracles[_oracle].endingRound == round_max162;
}
function ACCEPTINGSUBMISSIONS813(uint32 _roundId) //inject NONSTANDARD NAMING
private
view
returns (bool)
{
return details[_roundId].maxSubmissions != 0;
}
function DELAYED922(address _oracle, uint32 _roundId) //inject NONSTANDARD NAMING
private
view
returns (bool)
{
uint256 lastStarted = oracles[_oracle].lastStartedRound;
return _roundId > lastStarted + restartDelay || lastStarted == 0;
}
function NEWROUND17(uint32 _roundId) //inject NONSTANDARD NAMING
private
view
returns (bool)
{
return _roundId == reportingRoundId.ADD145(1);
}
function VALIDROUNDID399(uint256 _roundId) //inject NONSTANDARD NAMING
private
view
returns (bool)
{
return _roundId <= round_max162;
}
}
interface AccessControllerInterface {
function HASACCESS656(address user, bytes calldata data) external view returns (bool); //inject NONSTANDARD NAMING
}
contract SimpleWriteAccessController is AccessControllerInterface, Owned {
bool public checkEnabled;
mapping(address => bool) internal accessList;
event ADDEDACCESS832(address user); //inject NONSTANDARD NAMING
event REMOVEDACCESS756(address user); //inject NONSTANDARD NAMING
event CHECKACCESSENABLED184(); //inject NONSTANDARD NAMING
event CHECKACCESSDISABLED416(); //inject NONSTANDARD NAMING
constructor()
public
{
checkEnabled = true;
}
function HASACCESS656( //inject NONSTANDARD NAMING
address _user,
bytes memory
)
public
view
virtual
override
returns (bool)
{
return accessList[_user] || !checkEnabled;
}
function ADDACCESS313(address _user) //inject NONSTANDARD NAMING
external
ONLYOWNER6()
{
if (!accessList[_user]) {
accessList[_user] = true;
emit ADDEDACCESS832(_user);
}
}
function REMOVEACCESS708(address _user) //inject NONSTANDARD NAMING
external
ONLYOWNER6()
{
if (accessList[_user]) {
accessList[_user] = false;
emit REMOVEDACCESS756(_user);
}
}
function ENABLEACCESSCHECK558() //inject NONSTANDARD NAMING
external
ONLYOWNER6()
{
if (!checkEnabled) {
checkEnabled = true;
emit CHECKACCESSENABLED184();
}
}
function DISABLEACCESSCHECK244() //inject NONSTANDARD NAMING
external
ONLYOWNER6()
{
if (checkEnabled) {
checkEnabled = false;
emit CHECKACCESSDISABLED416();
}
}
modifier CHECKACCESS464() { //inject NONSTANDARD NAMING
require(HASACCESS656(msg.sender, msg.data), "No access");
_;
}
}
contract SimpleReadAccessController is SimpleWriteAccessController {
function HASACCESS656( //inject NONSTANDARD NAMING
address _user,
bytes memory _calldata
)
public
view
virtual
override
returns (bool)
{
return super.HASACCESS656(_user, _calldata) || _user == tx.origin;
}
}
contract AccessControlledAggregator is FluxAggregator, SimpleReadAccessController {
constructor(
address _link,
uint128 _paymentAmount,
uint32 _timeout,
address _validator,
int256 _minSubmissionValue,
int256 _maxSubmissionValue,
uint8 _decimals,
string memory _description
) public FluxAggregator(
_link,
_paymentAmount,
_timeout,
_validator,
_minSubmissionValue,
_maxSubmissionValue,
_decimals,
_description
){}
function GETROUNDDATA766(uint80 _roundId) //inject NONSTANDARD NAMING
public
view
override
CHECKACCESS464()
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return super.GETROUNDDATA766(_roundId);
}
function LATESTROUNDDATA762() //inject NONSTANDARD NAMING
public
view
override
CHECKACCESS464()
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
)
{
return super.LATESTROUNDDATA762();
}
function LATESTANSWER348() //inject NONSTANDARD NAMING
public
view
override
CHECKACCESS464()
returns (int256)
{
return super.LATESTANSWER348();
}
function LATESTROUND494() //inject NONSTANDARD NAMING
public
view
override
CHECKACCESS464()
returns (uint256)
{
return super.LATESTROUND494();
}
function LATESTTIMESTAMP303() //inject NONSTANDARD NAMING
public
view
override
CHECKACCESS464()
returns (uint256)
{
return super.LATESTTIMESTAMP303();
}
function GETANSWER896(uint256 _roundId) //inject NONSTANDARD NAMING
public
view
override
CHECKACCESS464()
returns (int256)
{
return super.GETANSWER896(_roundId);
}
function GETTIMESTAMP461(uint256 _roundId) //inject NONSTANDARD NAMING
public
view
override
CHECKACCESS464()
returns (uint256)
{
return super.GETTIMESTAMP461(_roundId);
}
}
|
Safe to downcast _amount because the total amount of LINK is less than 2^128.
|
{
require(oracles[_oracle].admin == msg.sender, "only callable by admin");
uint128 amount = uint128(_amount);
uint128 available = oracles[_oracle].withdrawable;
require(available >= amount, "insufficient withdrawable funds");
oracles[_oracle].withdrawable = available.SUB54(amount);
recordedFunds.allocated = recordedFunds.allocated.SUB54(amount);
assert(linkToken.TRANSFER233(_recipient, uint256(amount)));
}
| 13,067,143 |
[
1,
9890,
358,
2588,
4155,
389,
8949,
2724,
326,
2078,
3844,
434,
22926,
353,
5242,
2353,
576,
66,
10392,
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
] |
[
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,
225,
288,
203,
565,
2583,
12,
10610,
9558,
63,
67,
280,
16066,
8009,
3666,
422,
1234,
18,
15330,
16,
315,
3700,
4140,
635,
3981,
8863,
203,
203,
565,
2254,
10392,
3844,
273,
2254,
10392,
24899,
8949,
1769,
203,
565,
2254,
10392,
2319,
273,
578,
69,
9558,
63,
67,
280,
16066,
8009,
1918,
9446,
429,
31,
203,
565,
2583,
12,
5699,
1545,
3844,
16,
315,
2679,
11339,
598,
9446,
429,
284,
19156,
8863,
203,
203,
565,
578,
69,
9558,
63,
67,
280,
16066,
8009,
1918,
9446,
429,
273,
2319,
18,
8362,
6564,
12,
8949,
1769,
203,
565,
16421,
42,
19156,
18,
28172,
273,
16421,
42,
19156,
18,
28172,
18,
8362,
6564,
12,
8949,
1769,
203,
203,
565,
1815,
12,
1232,
1345,
18,
16596,
6553,
31026,
24899,
20367,
16,
2254,
5034,
12,
8949,
3719,
1769,
203,
225,
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
] |
./partial_match/56/0xc2AC373e6487815ebdb4a3a8D4Ae23F2404FB02e/sources/project_/contracts/Settlement.sol
|
remove an address from a transfer role
|
function removeTransferer(address transferer) public onlyRole(DEFAULT_ADMIN_ROLE) returns (bool success){
revokeRole(TRANSFER_ROLE, transferer);
return true;
}
| 11,196,143 |
[
1,
4479,
392,
1758,
628,
279,
7412,
2478,
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,
565,
445,
1206,
5912,
264,
12,
2867,
7412,
264,
13,
1071,
1338,
2996,
12,
5280,
67,
15468,
67,
16256,
13,
1135,
261,
6430,
2216,
15329,
203,
3639,
18007,
2996,
12,
16596,
6553,
67,
16256,
16,
7412,
264,
1769,
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,
-100,
-100,
-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/0xc70D7E1432449a14A7A7aC88B43ddDFdE7B305E6/sources/browser/MolVault_v2.sol
|
Reset bid and bidder
|
bidder = address(0);
| 701,617 |
[
1,
7013,
9949,
471,
9949,
765,
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,
9949,
765,
273,
1758,
12,
20,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title 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 Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Lock Token
*
* Token would be locked for thirty days after ICO. During this period
* new buyer could still trade their tokens.
*/
contract LockToken is StandardToken {
using SafeMath for uint256;
bool public isPublic;
uint256 public unLockTime;
PrivateToken public privateToken;
modifier onlyPrivateToken() {
require(msg.sender == address(privateToken));
_;
}
/**
* @dev Deposit is the function should only be called from PrivateToken
* When the user wants to deposit their private Token to Origin Token. They should
* let the Private Token invoke this function.
* @param _depositor address. The person who wants to deposit.
*/
function deposit(address _depositor, uint256 _value) public onlyPrivateToken returns(bool){
require(_value != 0);
balances[_depositor] = balances[_depositor].add(_value);
emit Transfer(privateToken, _depositor, _value);
return true;
}
constructor() public {
//2050/12/31 00:00:00.
unLockTime = 2556057600;
}
}
contract BCNTToken is LockToken{
string public constant name = "Bincentive SIT Token"; // solium-disable-line uppercase
string public constant symbol = "BCNT-SIT"; // solium-disable-line uppercase
uint8 public constant decimals = 18; // solium-disable-line uppercase
uint256 public constant INITIAL_SUPPLY = 1000000000 * (10 ** uint256(decimals));
mapping(bytes => bool) internal signatures;
event TransferPreSigned(address indexed from, address indexed to, address indexed delegate, uint256 amount, uint256 fee);
/**
* @notice Submit a presigned transfer
* @param _signature bytes The signature, issued by the owner.
* @param _to address The address which you want to transfer to.
* @param _value uint256 The amount of tokens to be transferred.
* @param _fee uint256 The amount of tokens paid to msg.sender, by the owner.
* @param _nonce uint256 Presigned transaction number.
* @param _validUntil uint256 Block number until which the presigned transaction is still valid.
*/
function transferPreSigned(
bytes _signature,
address _to,
uint256 _value,
uint256 _fee,
uint256 _nonce,
uint256 _validUntil
)
public
returns (bool)
{
require(_to != address(0));
require(signatures[_signature] == false);
require(block.number <= _validUntil);
bytes32 hashedTx = ECRecovery.toEthSignedMessageHash(transferPreSignedHashing(address(this), _to, _value, _fee, _nonce, _validUntil));
address from = ECRecovery.recover(hashedTx, _signature);
require(from != address(0));
balances[from] = balances[from].sub(_value).sub(_fee);
balances[_to] = balances[_to].add(_value);
balances[msg.sender] = balances[msg.sender].add(_fee);
signatures[_signature] = true;
emit Transfer(from, _to, _value);
emit Transfer(from, msg.sender, _fee);
emit TransferPreSigned(from, _to, msg.sender, _value, _fee);
return true;
}
/**
* @notice Hash (keccak256) of the payload used by transferPreSigned
* @param _token address The address of the token.
* @param _to address The address which you want to transfer to.
* @param _value uint256 The amount of tokens to be transferred.
* @param _fee uint256 The amount of tokens paid to msg.sender, by the owner.
* @param _nonce uint256 Presigned transaction number.
* @param _validUntil uint256 Block number until which the presigned transaction is still valid.
*/
function transferPreSignedHashing(
address _token,
address _to,
uint256 _value,
uint256 _fee,
uint256 _nonce,
uint256 _validUntil
)
public
pure
returns (bytes32)
{
/* "0d2d1bf5": transferPreSigned(address,address,uint256,uint256,uint256,uint256) */
return keccak256(bytes4(0x0a0fb66b), _token, _to, _value, _fee, _nonce, _validUntil);
}
function transferPreSignedHashingWithPrefix(
address _token,
address _to,
uint256 _value,
uint256 _fee,
uint256 _nonce,
uint256 _validUntil
)
public
pure
returns (bytes32)
{
return ECRecovery.toEthSignedMessageHash(transferPreSignedHashing(_token, _to, _value, _fee, _nonce, _validUntil));
}
/**
* @dev Constructor that gives _owner all of existing tokens.
*/
constructor(address _admin) public {
totalSupply_ = INITIAL_SUPPLY;
privateToken = new PrivateToken(
_admin, "Bincentive Private SIT Token", "BCNP-SIT", decimals, INITIAL_SUPPLY
);
}
}
/**
* @title DetailedERC20 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 DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
/**
* @title Eliptic curve signature operations
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
* TODO Remove this library once solidity supports passing a signature to ecrecover.
* See https://github.com/ethereum/solidity/issues/864
*/
library ECRecovery {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes sig)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
// solium-disable-next-line arg-overflow
return ecrecover(hash, v, r, s);
}
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
* and hash the result
*/
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
);
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
pragma solidity ^0.4.24;
pragma solidity ^0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
contract PrivateToken is StandardToken {
using SafeMath for uint256;
string public name; // solium-disable-line uppercase
string public symbol; // solium-disable-line uppercase
uint8 public decimals; // solium-disable-line uppercase
address public admin;
bool public isPublic;
uint256 public unLockTime;
LockToken originToken;
event StartPublicSale(uint256);
event Deposit(address indexed from, uint256 value);
/**
* @dev check if msg.sender is allowed to deposit Origin token.
*/
function isDepositAllowed() internal view{
// If the tokens isn't public yet all transfering are limited to origin tokens
require(isPublic);
require(msg.sender == admin || block.timestamp > unLockTime);
}
/**
* @dev Deposit msg.sender's origin token to real token
*/
function deposit() public returns (bool){
isDepositAllowed();
uint256 _value;
_value = balances[msg.sender];
require(_value > 0);
balances[msg.sender] = 0;
require(originToken.deposit(msg.sender, _value));
emit Deposit(msg.sender, _value);
}
/**
* @dev Deposit depositor's origin token from privateToken
* @param _depositor address The address of whom deposit the token.
*/
function adminDeposit(address _depositor) public onlyAdmin returns (bool){
isDepositAllowed();
uint256 _value;
_value = balances[_depositor];
require(_value > 0);
balances[_depositor] = 0;
require(originToken.deposit(_depositor, _value));
emit Deposit(_depositor, _value);
}
/**
* @dev Start Public sale and allow admin to deposit the token.
* normal users could deposit their tokens after the tokens unlocked
*/
function startPublicSale(uint256 _unLockTime) public onlyAdmin {
require(!isPublic);
isPublic = true;
unLockTime = _unLockTime;
emit StartPublicSale(_unLockTime);
}
/**
* @dev unLock the origin token and start the public sale.
*/
function unLock() public onlyAdmin{
require(isPublic);
unLockTime = block.timestamp;
}
modifier onlyAdmin() {
require(msg.sender == admin);
_;
}
constructor(address _admin, string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public{
originToken = LockToken(msg.sender);
admin = _admin;
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply_ = _totalSupply;
balances[admin] = _totalSupply;
emit Transfer(address(0), admin, _totalSupply);
}
}
|
* @dev Recover signer address from a message by using their signature @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. @param sig bytes signature, the signature is generated using web3.eth.sign()/ Check the signature length Divide the signature in r, s and v variables ecrecover takes the signature parameters, and the only way to get them currently is to use assembly. solium-disable-next-line security/no-inline-assembly Version of signature should be 27 or 28, but 0 and 1 are also possible versions If the version is correct return the signer address solium-disable-next-line arg-overflow
|
{
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65) {
return (address(0));
}
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
if (v < 27) {
v += 27;
}
if (v != 27 && v != 28) {
return (address(0));
return ecrecover(hash, v, r, s);
}
}
| 244,123 |
[
1,
27622,
10363,
1758,
628,
279,
883,
635,
1450,
3675,
3372,
225,
1651,
1731,
1578,
883,
16,
326,
1651,
353,
326,
6726,
883,
18,
18734,
353,
24616,
353,
326,
10363,
1758,
18,
225,
3553,
1731,
3372,
16,
326,
3372,
353,
4374,
1450,
3311,
23,
18,
546,
18,
2977,
1435,
19,
2073,
326,
3372,
769,
21411,
831,
326,
3372,
316,
436,
16,
272,
471,
331,
3152,
425,
1793,
3165,
5530,
326,
3372,
1472,
16,
471,
326,
1338,
4031,
358,
336,
2182,
4551,
353,
358,
999,
19931,
18,
3704,
5077,
17,
8394,
17,
4285,
17,
1369,
4373,
19,
2135,
17,
10047,
17,
28050,
4049,
434,
3372,
1410,
506,
12732,
578,
9131,
16,
1496,
374,
471,
404,
854,
2546,
3323,
5244,
971,
326,
1177,
353,
3434,
327,
326,
10363,
1758,
3704,
5077,
17,
8394,
17,
4285,
17,
1369,
1501,
17,
11512,
2,
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,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
225,
288,
203,
565,
1731,
1578,
436,
31,
203,
565,
1731,
1578,
272,
31,
203,
565,
2254,
28,
331,
31,
203,
203,
565,
309,
261,
7340,
18,
2469,
480,
15892,
13,
288,
203,
1377,
327,
261,
2867,
12,
20,
10019,
203,
565,
289,
203,
203,
565,
19931,
288,
203,
1377,
436,
519,
312,
945,
12,
1289,
12,
7340,
16,
3847,
3719,
203,
1377,
272,
519,
312,
945,
12,
1289,
12,
7340,
16,
5178,
3719,
203,
1377,
331,
519,
1160,
12,
20,
16,
312,
945,
12,
1289,
12,
7340,
16,
19332,
20349,
203,
565,
289,
203,
203,
565,
309,
261,
90,
411,
12732,
13,
288,
203,
1377,
331,
1011,
12732,
31,
203,
565,
289,
203,
203,
565,
309,
261,
90,
480,
12732,
597,
331,
480,
9131,
13,
288,
203,
1377,
327,
261,
2867,
12,
20,
10019,
203,
1377,
327,
425,
1793,
3165,
12,
2816,
16,
331,
16,
436,
16,
272,
1769,
203,
565,
289,
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
] |
pragma solidity ^0.4.2;
/*
Initially from : https://github.com/chriseth/solidity-examples/blob/master/queue.sol
Changed by: Jimmy Paris
Changed to be a queue of Demande (as a record of the asker's address and the asked value)
*/
contract QueueDemande
{
struct Demande{
address demandeur;
uint256 valeur;
}
struct Queue {
Demande[] data;
uint256 front;
uint256 back;
}
/// @dev the number of elements stored in the queue
function length(Queue storage q) constant internal returns (uint256) {
return q.back - q.front;
}
/// @dev the number of elements this queue can hold
function capacity(Queue storage q) constant internal returns (uint256) {
return q.data.length - 1;
}
/// @dev push a new element to the back of the queue
function push(Queue storage q, Demande dem) internal
{
if ((q.back + 1) % q.data.length == q.front)
return; // throw;
q.data[q.back] = dem;
q.back = (q.back + 1) % q.data.length;
}
/// @dev put a new element to the front of the queue
function replaceInFront(Queue storage q, Demande dem) internal
{
if (q.back == q.front)
return; // throw;
q.data[q.front] = dem;
}
/// @dev remove and return the element at the front of the queue
function pop(Queue storage q) internal returns (Demande dem)
{
if (q.back == q.front)
return; // throw;
dem = q.data[q.front];
delete q.data[q.front];
q.front = (q.front + 1) % q.data.length;
}
/// @dev copy and return the element at the front of the queue
function copyPop(Queue storage q) internal returns (Demande dem)
{
if (q.back == q.front)
return; // throw;
dem = q.data[q.front];
}
function containMinValueFromOther(Queue storage q, uint256 _minValue, address exceptAddr) internal returns (bool){
uint256 valeurComptee = 0;
uint256 i = q.front;
while(i < q.front + length(q) && valeurComptee < _minValue){
if (exceptAddr == q.data[i].demandeur) return false;
valeurComptee += q.data[i].valeur;
i++;
}
return valeurComptee >= _minValue;
}
function getTotalValue(Queue storage q) internal returns (uint256){
uint256 valeurComptee = 0;
uint256 i = q.front;
while(i < q.front + length(q)){
valeurComptee += q.data[i].valeur;
i++;
}
return valeurComptee;
}
/// @dev remove and return the element at the front of the queue
function get(Queue storage q, uint pos) internal returns (Demande dem)
{
if (pos >= length(q))
return; // throw;
dem = q.data[q.front + pos];
}
}
contract QueueDemandesEnCours is QueueDemande {
Queue requests;
function QueueDemandesEnCours() {
requests.data.length = 200;
}
function addRequest(address demandeur, uint256 valeur) {
push(requests, Demande(demandeur,valeur));
}
function replaceInFrontRequest(address demandeur, uint256 valeur) {
replaceInFront(requests, Demande(demandeur,valeur));
}
function popRequest() returns (address, uint256) {
var d = pop(requests);
return (d.demandeur,d.valeur);
}
function copyPopRequest() returns (address, uint256) {
var d = copyPop(requests);
return (d.demandeur,d.valeur);
}
function queueLength() returns (uint256) {
return length(requests);
}
function get(uint256 pos) returns (address, uint256) {
var d = get(requests, pos);
return (d.demandeur,d.valeur);
}
/// @dev check if a minimum value is asked in the queue, return false if it's asked by a specific address
function containMinValueFromOther(uint256 _minValue, address exceptAddr) returns (bool)
{
return containMinValueFromOther(requests, _minValue, exceptAddr);
}
//Get the total of the asked value in the queue
function getTotalValue() returns (uint256)
{
return getTotalValue(requests);
}
}
|
@dev the number of elements stored in the queue
|
function length(Queue storage q) constant internal returns (uint256) {
return q.back - q.front;
}
| 2,518,883 |
[
1,
5787,
1300,
434,
2186,
4041,
316,
326,
2389,
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,
769,
12,
3183,
2502,
1043,
13,
5381,
2713,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
1043,
18,
823,
300,
1043,
18,
10211,
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
] |
// File: contracts/lifecycle/PausableProxy.sol
pragma solidity ^0.4.24;
/**
* @title PausableProxy
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract PausableProxy {
/**
* @dev Storage slot with the paused state of the contract.
* This is the keccak-256 hash of "org.monetha.proxy.paused", and is
* validated in the constructor.
*/
bytes32 private constant PAUSED_OWNER_SLOT = 0x9e7945c55c116aa3404b99fe56db7af9613d3b899554a437c2616a4749a94d8a;
/**
* @dev The ClaimableProxy constructor validates PENDING_OWNER_SLOT constant.
*/
constructor() public {
assert(PAUSED_OWNER_SLOT == keccak256("org.monetha.proxy.paused"));
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_getPaused(), "contract should not be paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_getPaused(), "contract should be paused");
_;
}
/**
* @return True when the contract is paused.
*/
function _getPaused() internal view returns (bool paused) {
bytes32 slot = PAUSED_OWNER_SLOT;
assembly {
paused := sload(slot)
}
}
/**
* @dev Sets the paused state.
* @param _paused New paused state.
*/
function _setPaused(bool _paused) internal {
bytes32 slot = PAUSED_OWNER_SLOT;
assembly {
sstore(slot, _paused)
}
}
}
// File: contracts/ownership/OwnableProxy.sol
pragma solidity ^0.4.24;
/**
* @title OwnableProxy
*/
contract OwnableProxy is PausableProxy {
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Storage slot with the owner of the contract.
* This is the keccak-256 hash of "org.monetha.proxy.owner", and is
* validated in the constructor.
*/
bytes32 private constant OWNER_SLOT = 0x3ca57e4b51fc2e18497b219410298879868edada7e6fe5132c8feceb0a080d22;
/**
* @dev The OwnableProxy constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
assert(OWNER_SLOT == keccak256("org.monetha.proxy.owner"));
_setOwner(msg.sender);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == _getOwner());
_;
}
/**
* @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 whenNotPaused {
emit OwnershipRenounced(_getOwner());
_setOwner(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 whenNotPaused {
_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(_getOwner(), _newOwner);
_setOwner(_newOwner);
}
/**
* @return The owner address.
*/
function owner() public view returns (address) {
return _getOwner();
}
/**
* @return The owner address.
*/
function _getOwner() internal view returns (address own) {
bytes32 slot = OWNER_SLOT;
assembly {
own := sload(slot)
}
}
/**
* @dev Sets the address of the proxy owner.
* @param _newOwner Address of the new proxy owner.
*/
function _setOwner(address _newOwner) internal {
bytes32 slot = OWNER_SLOT;
assembly {
sstore(slot, _newOwner)
}
}
}
// File: contracts/ownership/ClaimableProxy.sol
pragma solidity ^0.4.24;
/**
* @title ClaimableProxy
* @dev Extension for the OwnableProxy contract, where the ownership needs to be claimed.
* This allows the new owner to accept the transfer.
*/
contract ClaimableProxy is OwnableProxy {
/**
* @dev Storage slot with the pending owner of the contract.
* This is the keccak-256 hash of "org.monetha.proxy.pendingOwner", and is
* validated in the constructor.
*/
bytes32 private constant PENDING_OWNER_SLOT = 0xcfd0c6ea5352192d7d4c5d4e7a73c5da12c871730cb60ff57879cbe7b403bb52;
/**
* @dev The ClaimableProxy constructor validates PENDING_OWNER_SLOT constant.
*/
constructor() public {
assert(PENDING_OWNER_SLOT == keccak256("org.monetha.proxy.pendingOwner"));
}
function pendingOwner() public view returns (address) {
return _getPendingOwner();
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == _getPendingOwner());
_;
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner whenNotPaused {
_setPendingOwner(newOwner);
}
/**
* @dev Allows the pendingOwner address to finalize the transfer.
*/
function claimOwnership() public onlyPendingOwner whenNotPaused {
emit OwnershipTransferred(_getOwner(), _getPendingOwner());
_setOwner(_getPendingOwner());
_setPendingOwner(address(0));
}
/**
* @return The pending owner address.
*/
function _getPendingOwner() internal view returns (address penOwn) {
bytes32 slot = PENDING_OWNER_SLOT;
assembly {
penOwn := sload(slot)
}
}
/**
* @dev Sets the address of the pending owner.
* @param _newPendingOwner Address of the new pending owner.
*/
function _setPendingOwner(address _newPendingOwner) internal {
bytes32 slot = PENDING_OWNER_SLOT;
assembly {
sstore(slot, _newPendingOwner)
}
}
}
// File: contracts/IPassportLogic.sol
pragma solidity ^0.4.24;
interface IPassportLogic {
/**
* @dev Returns the owner address of contract.
*/
function owner() external view returns (address);
/**** Storage Set Methods ***********/
/// @param _key The key for the record
/// @param _value The value for the record
function setAddress(bytes32 _key, address _value) external;
/// @param _key The key for the record
/// @param _value The value for the record
function setUint(bytes32 _key, uint _value) external;
/// @param _key The key for the record
/// @param _value The value for the record
function setInt(bytes32 _key, int _value) external;
/// @param _key The key for the record
/// @param _value The value for the record
function setBool(bytes32 _key, bool _value) external;
/// @param _key The key for the record
/// @param _value The value for the record
function setString(bytes32 _key, string _value) external;
/// @param _key The key for the record
/// @param _value The value for the record
function setBytes(bytes32 _key, bytes _value) external;
/// @param _key The key for the record
function setTxDataBlockNumber(bytes32 _key, bytes _data) external;
/// @param _key The key for the record
/// @param _value The value for the record
function setIPFSHash(bytes32 _key, string _value) external;
/**** Storage Delete Methods ***********/
/// @param _key The key for the record
function deleteAddress(bytes32 _key) external;
/// @param _key The key for the record
function deleteUint(bytes32 _key) external;
/// @param _key The key for the record
function deleteInt(bytes32 _key) external;
/// @param _key The key for the record
function deleteBool(bytes32 _key) external;
/// @param _key The key for the record
function deleteString(bytes32 _key) external;
/// @param _key The key for the record
function deleteBytes(bytes32 _key) external;
/// @param _key The key for the record
function deleteTxDataBlockNumber(bytes32 _key) external;
/// @param _key The key for the record
function deleteIPFSHash(bytes32 _key) external;
/**** Storage Get Methods ***********/
/// @param _factProvider The fact provider
/// @param _key The key for the record
function getAddress(address _factProvider, bytes32 _key) external view returns (bool success, address value);
/// @param _factProvider The fact provider
/// @param _key The key for the record
function getUint(address _factProvider, bytes32 _key) external view returns (bool success, uint value);
/// @param _factProvider The fact provider
/// @param _key The key for the record
function getInt(address _factProvider, bytes32 _key) external view returns (bool success, int value);
/// @param _factProvider The fact provider
/// @param _key The key for the record
function getBool(address _factProvider, bytes32 _key) external view returns (bool success, bool value);
/// @param _factProvider The fact provider
/// @param _key The key for the record
function getString(address _factProvider, bytes32 _key) external view returns (bool success, string value);
/// @param _factProvider The fact provider
/// @param _key The key for the record
function getBytes(address _factProvider, bytes32 _key) external view returns (bool success, bytes value);
/// @param _factProvider The fact provider
/// @param _key The key for the record
function getTxDataBlockNumber(address _factProvider, bytes32 _key) external view returns (bool success, uint blockNumber);
/// @param _factProvider The fact provider
/// @param _key The key for the record
function getIPFSHash(address _factProvider, bytes32 _key) external view returns (bool success, string value);
}
// File: contracts/storage/Storage.sol
pragma solidity ^0.4.24;
// Storage contracts holds all state.
// Do not change the order of the fields, аdd new fields to the end of the contract!
contract Storage is ClaimableProxy
{
/***************************************************************************
*** STORAGE VARIABLES. DO NOT REORDER!!! ADD NEW VARIABLE TO THE END!!! ***
***************************************************************************/
struct AddressValue {
bool initialized;
address value;
}
mapping(address => mapping(bytes32 => AddressValue)) internal addressStorage;
struct UintValue {
bool initialized;
uint value;
}
mapping(address => mapping(bytes32 => UintValue)) internal uintStorage;
struct IntValue {
bool initialized;
int value;
}
mapping(address => mapping(bytes32 => IntValue)) internal intStorage;
struct BoolValue {
bool initialized;
bool value;
}
mapping(address => mapping(bytes32 => BoolValue)) internal boolStorage;
struct StringValue {
bool initialized;
string value;
}
mapping(address => mapping(bytes32 => StringValue)) internal stringStorage;
struct BytesValue {
bool initialized;
bytes value;
}
mapping(address => mapping(bytes32 => BytesValue)) internal bytesStorage;
struct BlockNumberValue {
bool initialized;
uint blockNumber;
}
mapping(address => mapping(bytes32 => BlockNumberValue)) internal txBytesStorage;
bool private onlyFactProviderFromWhitelistAllowed;
mapping(address => bool) private factProviderWhitelist;
struct IPFSHashValue {
bool initialized;
string value;
}
mapping(address => mapping(bytes32 => IPFSHashValue)) internal ipfsHashStorage;
struct PrivateData {
string dataIPFSHash; // The IPFS hash of encrypted private data
bytes32 dataKeyHash; // The hash of symmetric key that was used to encrypt the data
}
struct PrivateDataValue {
bool initialized;
PrivateData value;
}
mapping(address => mapping(bytes32 => PrivateDataValue)) internal privateDataStorage;
enum PrivateDataExchangeState {Closed, Proposed, Accepted}
struct PrivateDataExchange {
address dataRequester; // The address of the data requester
uint256 dataRequesterValue; // The amount staked by the data requester
address passportOwner; // The address of the passport owner at the time of the data exchange proposition
uint256 passportOwnerValue; // Tha amount staked by the passport owner
address factProvider; // The private data provider
bytes32 key; // the key for the private data record
string dataIPFSHash; // The IPFS hash of encrypted private data
bytes32 dataKeyHash; // The hash of data symmetric key that was used to encrypt the data
bytes encryptedExchangeKey; // The encrypted exchange session key (only passport owner can decrypt it)
bytes32 exchangeKeyHash; // The hash of exchange session key
bytes32 encryptedDataKey; // The data symmetric key XORed with the exchange key
PrivateDataExchangeState state; // The state of private data exchange
uint256 stateExpired; // The state expiration timestamp
}
uint public openPrivateDataExchangesCount; // the count of open private data exchanges TODO: use it in contract destruction/ownership transfer logic
PrivateDataExchange[] public privateDataExchanges;
/***************************************************************************
*** END OF SECTION OF STORAGE VARIABLES ***
***************************************************************************/
event WhitelistOnlyPermissionSet(bool indexed onlyWhitelist);
event WhitelistFactProviderAdded(address indexed factProvider);
event WhitelistFactProviderRemoved(address indexed factProvider);
/**
* Restrict methods in such way, that they can be invoked only by allowed fact provider.
*/
modifier allowedFactProvider() {
require(isAllowedFactProvider(msg.sender));
_;
}
/**
* Returns true when the given address is an allowed fact provider.
*/
function isAllowedFactProvider(address _address) public view returns (bool) {
return !onlyFactProviderFromWhitelistAllowed || factProviderWhitelist[_address] || _address == _getOwner();
}
/**
* Returns true when a whitelist of fact providers is enabled.
*/
function isWhitelistOnlyPermissionSet() external view returns (bool) {
return onlyFactProviderFromWhitelistAllowed;
}
/**
* Enables or disables the use of a whitelist of fact providers.
*/
function setWhitelistOnlyPermission(bool _onlyWhitelist) onlyOwner external {
onlyFactProviderFromWhitelistAllowed = _onlyWhitelist;
emit WhitelistOnlyPermissionSet(_onlyWhitelist);
}
/**
* Returns true if fact provider is added to the whitelist.
*/
function isFactProviderInWhitelist(address _address) external view returns (bool) {
return factProviderWhitelist[_address];
}
/**
* Allows owner to add fact provider to whitelist.
*/
function addFactProviderToWhitelist(address _address) onlyOwner external {
factProviderWhitelist[_address] = true;
emit WhitelistFactProviderAdded(_address);
}
/**
* Allows owner to remove fact provider from whitelist.
*/
function removeFactProviderFromWhitelist(address _address) onlyOwner external {
delete factProviderWhitelist[_address];
emit WhitelistFactProviderRemoved(_address);
}
}
// File: contracts/storage/AddressStorageLogic.sol
pragma solidity ^0.4.24;
contract AddressStorageLogic is Storage {
event AddressUpdated(address indexed factProvider, bytes32 indexed key);
event AddressDeleted(address indexed factProvider, bytes32 indexed key);
/// @param _key The key for the record
/// @param _value The value for the record
function setAddress(bytes32 _key, address _value) external {
_setAddress(_key, _value);
}
/// @param _key The key for the record
function deleteAddress(bytes32 _key) external {
_deleteAddress(_key);
}
/// @param _factProvider The fact provider
/// @param _key The key for the record
function getAddress(address _factProvider, bytes32 _key) external view returns (bool success, address value) {
return _getAddress(_factProvider, _key);
}
function _setAddress(bytes32 _key, address _value) allowedFactProvider internal {
addressStorage[msg.sender][_key] = AddressValue({
initialized : true,
value : _value
});
emit AddressUpdated(msg.sender, _key);
}
function _deleteAddress(bytes32 _key) allowedFactProvider internal {
delete addressStorage[msg.sender][_key];
emit AddressDeleted(msg.sender, _key);
}
function _getAddress(address _factProvider, bytes32 _key) internal view returns (bool success, address value) {
AddressValue storage initValue = addressStorage[_factProvider][_key];
return (initValue.initialized, initValue.value);
}
}
// File: contracts/storage/UintStorageLogic.sol
pragma solidity ^0.4.24;
contract UintStorageLogic is Storage {
event UintUpdated(address indexed factProvider, bytes32 indexed key);
event UintDeleted(address indexed factProvider, bytes32 indexed key);
/// @param _key The key for the record
/// @param _value The value for the record
function setUint(bytes32 _key, uint _value) external {
_setUint(_key, _value);
}
/// @param _key The key for the record
function deleteUint(bytes32 _key) external {
_deleteUint(_key);
}
/// @param _factProvider The fact provider
/// @param _key The key for the record
function getUint(address _factProvider, bytes32 _key) external view returns (bool success, uint value) {
return _getUint(_factProvider, _key);
}
function _setUint(bytes32 _key, uint _value) allowedFactProvider internal {
uintStorage[msg.sender][_key] = UintValue({
initialized : true,
value : _value
});
emit UintUpdated(msg.sender, _key);
}
function _deleteUint(bytes32 _key) allowedFactProvider internal {
delete uintStorage[msg.sender][_key];
emit UintDeleted(msg.sender, _key);
}
function _getUint(address _factProvider, bytes32 _key) internal view returns (bool success, uint value) {
UintValue storage initValue = uintStorage[_factProvider][_key];
return (initValue.initialized, initValue.value);
}
}
// File: contracts/storage/IntStorageLogic.sol
pragma solidity ^0.4.24;
contract IntStorageLogic is Storage {
event IntUpdated(address indexed factProvider, bytes32 indexed key);
event IntDeleted(address indexed factProvider, bytes32 indexed key);
/// @param _key The key for the record
/// @param _value The value for the record
function setInt(bytes32 _key, int _value) external {
_setInt(_key, _value);
}
/// @param _key The key for the record
function deleteInt(bytes32 _key) external {
_deleteInt(_key);
}
/// @param _factProvider The fact provider
/// @param _key The key for the record
function getInt(address _factProvider, bytes32 _key) external view returns (bool success, int value) {
return _getInt(_factProvider, _key);
}
function _setInt(bytes32 _key, int _value) allowedFactProvider internal {
intStorage[msg.sender][_key] = IntValue({
initialized : true,
value : _value
});
emit IntUpdated(msg.sender, _key);
}
function _deleteInt(bytes32 _key) allowedFactProvider internal {
delete intStorage[msg.sender][_key];
emit IntDeleted(msg.sender, _key);
}
function _getInt(address _factProvider, bytes32 _key) internal view returns (bool success, int value) {
IntValue storage initValue = intStorage[_factProvider][_key];
return (initValue.initialized, initValue.value);
}
}
// File: contracts/storage/BoolStorageLogic.sol
pragma solidity ^0.4.24;
contract BoolStorageLogic is Storage {
event BoolUpdated(address indexed factProvider, bytes32 indexed key);
event BoolDeleted(address indexed factProvider, bytes32 indexed key);
/// @param _key The key for the record
/// @param _value The value for the record
function setBool(bytes32 _key, bool _value) external {
_setBool(_key, _value);
}
/// @param _key The key for the record
function deleteBool(bytes32 _key) external {
_deleteBool(_key);
}
/// @param _factProvider The fact provider
/// @param _key The key for the record
function getBool(address _factProvider, bytes32 _key) external view returns (bool success, bool value) {
return _getBool(_factProvider, _key);
}
function _setBool(bytes32 _key, bool _value) allowedFactProvider internal {
boolStorage[msg.sender][_key] = BoolValue({
initialized : true,
value : _value
});
emit BoolUpdated(msg.sender, _key);
}
function _deleteBool(bytes32 _key) allowedFactProvider internal {
delete boolStorage[msg.sender][_key];
emit BoolDeleted(msg.sender, _key);
}
function _getBool(address _factProvider, bytes32 _key) internal view returns (bool success, bool value) {
BoolValue storage initValue = boolStorage[_factProvider][_key];
return (initValue.initialized, initValue.value);
}
}
// File: contracts/storage/StringStorageLogic.sol
pragma solidity ^0.4.24;
contract StringStorageLogic is Storage {
event StringUpdated(address indexed factProvider, bytes32 indexed key);
event StringDeleted(address indexed factProvider, bytes32 indexed key);
/// @param _key The key for the record
/// @param _value The value for the record
function setString(bytes32 _key, string _value) external {
_setString(_key, _value);
}
/// @param _key The key for the record
function deleteString(bytes32 _key) external {
_deleteString(_key);
}
/// @param _factProvider The fact provider
/// @param _key The key for the record
function getString(address _factProvider, bytes32 _key) external view returns (bool success, string value) {
return _getString(_factProvider, _key);
}
function _setString(bytes32 _key, string _value) allowedFactProvider internal {
stringStorage[msg.sender][_key] = StringValue({
initialized : true,
value : _value
});
emit StringUpdated(msg.sender, _key);
}
function _deleteString(bytes32 _key) allowedFactProvider internal {
delete stringStorage[msg.sender][_key];
emit StringDeleted(msg.sender, _key);
}
function _getString(address _factProvider, bytes32 _key) internal view returns (bool success, string value) {
StringValue storage initValue = stringStorage[_factProvider][_key];
return (initValue.initialized, initValue.value);
}
}
// File: contracts/storage/BytesStorageLogic.sol
pragma solidity ^0.4.24;
contract BytesStorageLogic is Storage {
event BytesUpdated(address indexed factProvider, bytes32 indexed key);
event BytesDeleted(address indexed factProvider, bytes32 indexed key);
/// @param _key The key for the record
/// @param _value The value for the record
function setBytes(bytes32 _key, bytes _value) external {
_setBytes(_key, _value);
}
/// @param _key The key for the record
function deleteBytes(bytes32 _key) external {
_deleteBytes(_key);
}
/// @param _factProvider The fact provider
/// @param _key The key for the record
function getBytes(address _factProvider, bytes32 _key) external view returns (bool success, bytes value) {
return _getBytes(_factProvider, _key);
}
function _setBytes(bytes32 _key, bytes _value) allowedFactProvider internal {
bytesStorage[msg.sender][_key] = BytesValue({
initialized : true,
value : _value
});
emit BytesUpdated(msg.sender, _key);
}
function _deleteBytes(bytes32 _key) allowedFactProvider internal {
delete bytesStorage[msg.sender][_key];
emit BytesDeleted(msg.sender, _key);
}
function _getBytes(address _factProvider, bytes32 _key) internal view returns (bool success, bytes value) {
BytesValue storage initValue = bytesStorage[_factProvider][_key];
return (initValue.initialized, initValue.value);
}
}
// File: contracts/storage/TxDataStorageLogic.sol
pragma solidity ^0.4.24;
/**
* @title TxDataStorage
* @dev This contract saves only the block number for the input data. The input data is not stored into
* Ethereum storage, but it can be decoded from the transaction input data later.
*/
contract TxDataStorageLogic is Storage {
event TxDataUpdated(address indexed factProvider, bytes32 indexed key);
event TxDataDeleted(address indexed factProvider, bytes32 indexed key);
/// @param _key The key for the record
/// @param _data The data for the record. Ignore "unused function parameter" warning, it's not commented out so that
/// it would remain in the ABI file.
function setTxDataBlockNumber(bytes32 _key, bytes _data) allowedFactProvider external {
_data;
txBytesStorage[msg.sender][_key] = BlockNumberValue({
initialized : true,
blockNumber : block.number
});
emit TxDataUpdated(msg.sender, _key);
}
/// @param _key The key for the record
function deleteTxDataBlockNumber(bytes32 _key) allowedFactProvider external {
delete txBytesStorage[msg.sender][_key];
emit TxDataDeleted(msg.sender, _key);
}
/// @param _factProvider The fact provider
/// @param _key The key for the record
function getTxDataBlockNumber(address _factProvider, bytes32 _key) external view returns (bool success, uint blockNumber) {
return _getTxDataBlockNumber(_factProvider, _key);
}
function _getTxDataBlockNumber(address _factProvider, bytes32 _key) private view returns (bool success, uint blockNumber) {
BlockNumberValue storage initValue = txBytesStorage[_factProvider][_key];
return (initValue.initialized, initValue.blockNumber);
}
}
// File: contracts/storage/IPFSStorageLogic.sol
pragma solidity ^0.4.24;
contract IPFSStorageLogic is Storage {
event IPFSHashUpdated(address indexed factProvider, bytes32 indexed key);
event IPFSHashDeleted(address indexed factProvider, bytes32 indexed key);
/// @param _key The key for the record
/// @param _value The value for the record
function setIPFSHash(bytes32 _key, string _value) external {
_setIPFSHash(_key, _value);
}
/// @param _key The key for the record
function deleteIPFSHash(bytes32 _key) external {
_deleteIPFSHash(_key);
}
/// @param _factProvider The fact provider
/// @param _key The key for the record
function getIPFSHash(address _factProvider, bytes32 _key) external view returns (bool success, string value) {
return _getIPFSHash(_factProvider, _key);
}
function _setIPFSHash(bytes32 _key, string _value) allowedFactProvider internal {
ipfsHashStorage[msg.sender][_key] = IPFSHashValue({
initialized : true,
value : _value
});
emit IPFSHashUpdated(msg.sender, _key);
}
function _deleteIPFSHash(bytes32 _key) allowedFactProvider internal {
delete ipfsHashStorage[msg.sender][_key];
emit IPFSHashDeleted(msg.sender, _key);
}
function _getIPFSHash(address _factProvider, bytes32 _key) internal view returns (bool success, string value) {
IPFSHashValue storage initValue = ipfsHashStorage[_factProvider][_key];
return (initValue.initialized, initValue.value);
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: contracts/storage/PrivateDataStorageLogic.sol
pragma solidity ^0.4.24;
contract PrivateDataStorageLogic is Storage {
using SafeMath for uint256;
event PrivateDataHashesUpdated(address indexed factProvider, bytes32 indexed key);
event PrivateDataHashesDeleted(address indexed factProvider, bytes32 indexed key);
event PrivateDataExchangeProposed(uint256 indexed exchangeIdx, address indexed dataRequester, address indexed passportOwner);
event PrivateDataExchangeAccepted(uint256 indexed exchangeIdx, address indexed dataRequester, address indexed passportOwner);
event PrivateDataExchangeClosed(uint256 indexed exchangeIdx);
event PrivateDataExchangeDisputed(uint256 indexed exchangeIdx, bool indexed successful, address indexed cheater);
uint256 constant public privateDataExchangeProposeTimeout = 1 days;
uint256 constant public privateDataExchangeAcceptTimeout = 1 days;
/// @param _key The key for the record
/// @param _dataIPFSHash The IPFS hash of encrypted private data
/// @param _dataKeyHash The hash of symmetric key that was used to encrypt the data
function setPrivateDataHashes(bytes32 _key, string _dataIPFSHash, bytes32 _dataKeyHash) external {
_setPrivateDataHashes(_key, _dataIPFSHash, _dataKeyHash);
}
/// @param _key The key for the record
function deletePrivateDataHashes(bytes32 _key) external {
_deletePrivateDataHashes(_key);
}
/// @param _factProvider The fact provider
/// @param _key The key for the record
function getPrivateDataHashes(address _factProvider, bytes32 _key) external view returns (bool success, string dataIPFSHash, bytes32 dataKeyHash) {
return _getPrivateDataHashes(_factProvider, _key);
}
/**
* @dev returns the number of private data exchanges created.
*/
function getPrivateDataExchangesCount() public constant returns (uint256 count) {
return privateDataExchanges.length;
}
/// @param _factProvider The fact provider
/// @param _key The key for the record
/// @param _encryptedExchangeKey The encrypted exchange session key (only passport owner can decrypt it)
/// @param _exchangeKeyHash The hash of exchange session key
function proposePrivateDataExchange(
address _factProvider,
bytes32 _key,
bytes _encryptedExchangeKey,
bytes32 _exchangeKeyHash
) external payable {
(bool success, string memory dataIPFSHash, bytes32 dataKeyHash) = _getPrivateDataHashes(_factProvider, _key);
require(success, "private data must exist");
address passportOwner = _getOwner();
bytes32 encryptedDataKey;
PrivateDataExchange memory exchange = PrivateDataExchange({
dataRequester : msg.sender,
dataRequesterValue : msg.value,
passportOwner : passportOwner,
passportOwnerValue : 0,
factProvider : _factProvider,
key : _key,
dataIPFSHash : dataIPFSHash,
dataKeyHash : dataKeyHash,
encryptedExchangeKey : _encryptedExchangeKey,
exchangeKeyHash : _exchangeKeyHash,
encryptedDataKey : encryptedDataKey,
state : PrivateDataExchangeState.Proposed,
stateExpired : _nowSeconds() + privateDataExchangeProposeTimeout
});
privateDataExchanges.push(exchange);
_incOpenPrivateDataExchangesCount();
uint256 exchangeIdx = privateDataExchanges.length - 1;
emit PrivateDataExchangeProposed(exchangeIdx, msg.sender, passportOwner);
}
/// @param _exchangeIdx The private data exchange index
/// @param _encryptedDataKey The data symmetric key XORed with the exchange key
function acceptPrivateDataExchange(uint256 _exchangeIdx, bytes32 _encryptedDataKey) external payable {
require(_exchangeIdx < privateDataExchanges.length, "invalid exchange index");
PrivateDataExchange storage exchange = privateDataExchanges[_exchangeIdx];
require(msg.sender == exchange.passportOwner, "only passport owner allowed");
require(PrivateDataExchangeState.Proposed == exchange.state, "exchange must be in proposed state");
require(msg.value >= exchange.dataRequesterValue, "need to stake at least data requester amount");
require(_nowSeconds() < exchange.stateExpired, "exchange state expired");
exchange.passportOwnerValue = msg.value;
exchange.encryptedDataKey = _encryptedDataKey;
exchange.state = PrivateDataExchangeState.Accepted;
exchange.stateExpired = _nowSeconds() + privateDataExchangeAcceptTimeout;
emit PrivateDataExchangeAccepted(_exchangeIdx, exchange.dataRequester, msg.sender);
}
/// @param _exchangeIdx The private data exchange index
function finishPrivateDataExchange(uint256 _exchangeIdx) external {
require(_exchangeIdx < privateDataExchanges.length, "invalid exchange index");
PrivateDataExchange storage exchange = privateDataExchanges[_exchangeIdx];
require(PrivateDataExchangeState.Accepted == exchange.state, "exchange must be in accepted state");
require(_nowSeconds() > exchange.stateExpired || msg.sender == exchange.dataRequester, "exchange must be either expired or be finished by the data requester");
exchange.state = PrivateDataExchangeState.Closed;
// transfer all exchange staked money to passport owner
uint256 val = exchange.dataRequesterValue.add(exchange.passportOwnerValue);
require(exchange.passportOwner.send(val));
_decOpenPrivateDataExchangesCount();
emit PrivateDataExchangeClosed(_exchangeIdx);
}
/// @param _exchangeIdx The private data exchange index
function timeoutPrivateDataExchange(uint256 _exchangeIdx) external {
require(_exchangeIdx < privateDataExchanges.length, "invalid exchange index");
PrivateDataExchange storage exchange = privateDataExchanges[_exchangeIdx];
require(PrivateDataExchangeState.Proposed == exchange.state, "exchange must be in proposed state");
require(msg.sender == exchange.dataRequester, "only data requester allowed");
require(_nowSeconds() > exchange.stateExpired, "exchange must be expired");
exchange.state = PrivateDataExchangeState.Closed;
// return staked amount to data requester
require(exchange.dataRequester.send(exchange.dataRequesterValue));
_decOpenPrivateDataExchangesCount();
emit PrivateDataExchangeClosed(_exchangeIdx);
}
/// @param _exchangeIdx The private data exchange index
/// @param _exchangeKey The unencrypted exchange session key
function disputePrivateDataExchange(uint256 _exchangeIdx, bytes32 _exchangeKey) external {
require(_exchangeIdx < privateDataExchanges.length, "invalid exchange index");
PrivateDataExchange storage exchange = privateDataExchanges[_exchangeIdx];
require(PrivateDataExchangeState.Accepted == exchange.state, "exchange must be in accepted state");
require(msg.sender == exchange.dataRequester, "only data requester allowed");
require(_nowSeconds() < exchange.stateExpired, "exchange must not be expired");
require(keccak256(abi.encodePacked(_exchangeKey)) == exchange.exchangeKeyHash, "exchange key hash must match");
bytes32 dataKey = _exchangeKey ^ exchange.encryptedDataKey;
// data symmetric key is XORed with exchange key
bool validDataKey = keccak256(abi.encodePacked(dataKey)) == exchange.dataKeyHash;
exchange.state = PrivateDataExchangeState.Closed;
uint256 val = exchange.dataRequesterValue.add(exchange.passportOwnerValue);
address cheater;
if (validDataKey) {// the data key was valid -> data requester cheated
require(exchange.passportOwner.send(val));
cheater = exchange.dataRequester;
} else {// the data key is invalid -> passport owner cheated
require(exchange.dataRequester.send(val));
cheater = exchange.passportOwner;
}
_decOpenPrivateDataExchangesCount();
emit PrivateDataExchangeClosed(_exchangeIdx);
emit PrivateDataExchangeDisputed(_exchangeIdx, !validDataKey, cheater);
}
function _incOpenPrivateDataExchangesCount() internal {
if (++openPrivateDataExchangesCount == 1) {
// don't allow passport owner to transfer ownership and destroy passport when there are open exchanges
_setPaused(true);
}
}
function _decOpenPrivateDataExchangesCount() internal {
if (--openPrivateDataExchangesCount == 0) {
// allow passport owner to transfer ownership and destroy passport when all exchanges are closed
_setPaused(false);
}
}
function _setPrivateDataHashes(bytes32 _key, string _dataIPFSHash, bytes32 _dataKeyHash) allowedFactProvider internal {
privateDataStorage[msg.sender][_key] = PrivateDataValue({
initialized : true,
value : PrivateData({
dataIPFSHash : _dataIPFSHash,
dataKeyHash : _dataKeyHash
})
});
emit PrivateDataHashesUpdated(msg.sender, _key);
}
function _deletePrivateDataHashes(bytes32 _key) allowedFactProvider internal {
delete privateDataStorage[msg.sender][_key];
emit PrivateDataHashesDeleted(msg.sender, _key);
}
function _getPrivateDataHashes(address _factProvider, bytes32 _key) internal view returns (bool success, string dataIPFSHash, bytes32 dataKeyHash) {
PrivateDataValue storage initValue = privateDataStorage[_factProvider][_key];
return (initValue.initialized, initValue.value.dataIPFSHash, initValue.value.dataKeyHash);
}
function _nowSeconds() private view returns(uint256) {
uint256 t = now;
// In Quorum blockchain timestamp is in nanoseconds, not seconds:
// https://github.com/jpmorganchase/quorum/issues/713
// https://github.com/jpmorganchase/quorum/issues/190
if (t > 150000000000000000) {
t /= 1000000000;
}
return t;
}
}
// File: contracts/PassportLogic.sol
pragma solidity ^0.4.24;
contract PassportLogic
is IPassportLogic
, ClaimableProxy
, AddressStorageLogic
, UintStorageLogic
, IntStorageLogic
, BoolStorageLogic
, StringStorageLogic
, BytesStorageLogic
, TxDataStorageLogic
, IPFSStorageLogic
, PrivateDataStorageLogic
{}
|
@param _factProvider The fact provider @param _key The key for the record
|
function getIPFSHash(address _factProvider, bytes32 _key) external view returns (bool success, string value) {
return _getIPFSHash(_factProvider, _key);
}
| 12,267,629 |
[
1,
67,
3493,
2249,
1021,
5410,
2893,
225,
389,
856,
1021,
498,
364,
326,
1409,
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,
336,
2579,
4931,
2310,
12,
2867,
389,
3493,
2249,
16,
1731,
1578,
389,
856,
13,
3903,
1476,
1135,
261,
6430,
2216,
16,
533,
460,
13,
288,
203,
3639,
327,
389,
588,
2579,
4931,
2310,
24899,
3493,
2249,
16,
389,
856,
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
] |
/**
*Submitted for verification at Etherscan.io on 2021-05-13
*/
/**
*Submitted for verification at Etherscan.io on 2021-05-11
*/
pragma solidity 0.5.17;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* IMPORTANT: It is unsafe to assume that an address for which this
* function returns false is an externally-owned account (EOA) and not a
* contract.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _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");
}
}
/**
* @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;
}
}
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract PauserRole is Context {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(_msgSender());
}
modifier onlyPauser() {
require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(_msgSender());
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context, PauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = _msgSender();
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @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 Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data)
public returns (bytes4);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
contract IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in `owner`'s account.
*/
function balanceOf(address owner) public view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) public view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) public;
function approve(address to, uint256 tokenId) public;
function getApproved(uint256 tokenId) public view returns (address operator);
function setApprovalForAll(address operator, bool _approved) public;
function isApprovedForAll(address owner, address operator) public view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public;
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
}
/**
* @dev Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].current();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address owner = _tokenOwner[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public {
address owner = 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"
);
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param to operator address to set the approval
* @param approved representing the status of the approval to be set
*/
function setApprovalForAll(address to, bool approved) public {
require(to != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][to] = approved;
emit ApprovalForAll(_msgSender(), to, approved);
}
/**
* @dev Tells whether an operator is approved by a given owner.
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transferFrom(from, to, tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransferFrom(from, to, tokenId, _data);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function _safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) internal {
_transferFrom(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
address owner = _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) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].increment();
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own");
_clearApproval(tokenId);
_ownedTokensCount[owner].decrement();
_tokenOwner[tokenId] = address(0);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal {
_burn(ownerOf(tokenId), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_clearApproval(tokenId);
_ownedTokensCount[from].decrement();
_ownedTokensCount[to].increment();
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* This function is deprecated.
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
internal returns (bool)
{
if (!to.isContract()) {
return true;
}
bytes4 retval = IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data);
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Private function to clear current approval of a given token ID.
* @param tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(uint256 tokenId) private {
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
contract ERC721Metadata is Context, ERC165, ERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/**
* @dev Constructor function
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns an URI for a given token ID.
* Throws if the token ID does not exist. May return an empty string.
* @param tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _tokenURIs[tokenId];
}
/**
* @dev Internal function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function _setTokenURI(uint256 tokenId, string memory uri) internal {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = uri;
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use _burn(uint256) instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Enumerable is IERC721 {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256 tokenId);
function tokenByIndex(uint256 index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token with optional enumeration extension logic
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Constructor function.
*/
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to transferFrom, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transferFrom(address from, address to, uint256 tokenId) internal {
super._transferFrom(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to address the beneficiary that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal {
super._mint(to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
_addTokenToAllTokensEnumeration(tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* Deprecated, use {ERC721-_burn} instead.
* @param owner owner of the token to burn
* @param tokenId uint256 ID of the token being burned
*/
function _burn(address owner, uint256 tokenId) internal {
super._burn(owner, tokenId);
_removeTokenFromOwnerEnumeration(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_removeTokenFromAllTokensEnumeration(tokenId);
}
/**
* @dev Gets the list of token IDs of the requested owner.
* @param owner address owning the tokens
* @return uint256[] List of token IDs owned by the requested address
*/
function _tokensOfOwner(address owner) internal view returns (uint256[] storage) {
return _ownedTokens[owner];
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _ownedTokens[from].length.sub(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
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length.sub(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
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
contract IERC721Full is IERC721, IERC721Enumerable, IERC721Metadata {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @title Full ERC721 Token
* @dev This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology.
*
* See https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Full is ERC721, ERC721Enumerable, ERC721Metadata {
constructor (string memory name, string memory symbol) public ERC721Metadata(name, symbol) {
// solhint-disable-previous-line no-empty-blocks
}
}
contract RequestableOwnable is Ownable, Pausable {
/**
* @dev Stores the future owner whose approval is requested.
*/
address private _newOwner;
/**
* @dev Stores the status of the request for destruction.
*/
bool private _destructRequestStatus;
event OwnershipTransferRequested(address indexed previousOwner, address indexed newOwner);
event OwnershipTransferRejected(address indexed rejecter, address indexed newOwner);
event DestructRequestStatusSet(address indexed requester, bool status);
event DestructAccepted(address indexed accepter);
event DestructRejected(address indexed rejecter);
constructor() public {
}
/**
* @dev Returns the address of the future owner after they accept.
*/
function newOwner() public view returns (address) {
return _newOwner;
}
/**
* @dev Throws if called by any account other than the future owner.
*/
modifier onlyNewOwner() {
require(isNewOwner(), "RequestableOwnable: caller is not the new owner");
_;
}
/**
* @dev Returns true if the caller is the future owner.
*/
function isNewOwner() public view returns (bool) {
return _msgSender() == _newOwner;
}
/**
* @dev Registers a request to transfer ownership of the contract to a new account (`newOwnerIn`).
* @param newOwnerIn address the account of the future owner.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwnerIn) public onlyOwner {
require(_newOwner == address(0), "RequestableOwnable: cannot change non-zero newOwner");
require(newOwnerIn != address(0), "RequestableOwnable: cannot change to zero newOwner");
require(newOwnerIn != owner(), "RequestableOwnable: cannot change to same owner");
require(!_destructRequestStatus, "RequestableOwnable: destruct is requested");
_newOwner = newOwnerIn;
emit OwnershipTransferRequested(owner(), newOwnerIn);
}
/**
* @dev Effectively transfers the ownership to the new account.
* Can only be called by the new owner.
*/
function acceptOwnership() public onlyNewOwner {
_addPauser(_newOwner);
_removePauser(owner());
_newOwner = address(0);
Ownable._transferOwnership(_msgSender());
}
/**
* @dev Rejects the ownership transfer request.
* Can only be called by the old or the new owner.
*/
function rejectOwnership() public {
address newOwnerIn = _newOwner;
require(_msgSender() == newOwnerIn || isOwner(), "RequestableOwnable: caller is neither the new owner nor the current owner");
_newOwner = address(0);
emit OwnershipTransferRejected(_msgSender(), newOwnerIn);
}
/**
* @dev overridden
*/
function renounceOwnership() public whenPaused {
_removePauser(owner());
Ownable.renounceOwnership();
}
/**
* @dev Updates the destruct request, the first step to destroy the contract.
* @param status bool the new destruct request status.
* Can only be called by the contract owner, and when the contract is paused, to avoid mishaps.
*/
function setDestructRequestStatus(bool status) public onlyOwner whenPaused {
require(_destructRequestStatus != status, "RequestableOwnable: no change in status");
_destructRequestStatus = status;
emit DestructRequestStatusSet(_msgSender(), status);
}
/**
* @dev Returns the destruct request status.
* Can only be called by the contract owner, and when the contract is paused, to avoid mishaps.
*/
function isDestructRequested() public view returns (bool) {
return _destructRequestStatus;
}
/**
* @dev Let's someone effectively destroy the contract.
* Can only be called when the destruct request has been made.
*/
function _acceptDestruct() internal {
require(_destructRequestStatus, "RequestableOwnable: destruct is not requested");
emit DestructAccepted(_msgSender());
selfdestruct(_msgSender());
}
/**
* @dev Let's someone remove the destruct request.
* Can only be called when the destruct request has been made.
*/
function _rejectDestruct() internal {
require(_destructRequestStatus, "RequestableOwnable: destruct is not requested");
_destructRequestStatus = false;
emit DestructRejected(_msgSender());
}
/**
* @dev overridden
*/
function renouncePauser() public {
require(msg.sender != owner(), "RequestableOwnable: owner cannot renounce pauser");
PauserRole.renouncePauser();
}
/**
* @dev Removes the mentioned pauser.
* @param account address address of the pauser to remove
* Can only be called by the contract owner.
*/
function removePauser(address account) public onlyOwner {
require(account != msg.sender, "RequestableOwnable: owner cannot remove itself as pauser");
PauserRole._removePauser(account);
}
/**
* @dev overridden
*/
function unpause() public {
require(!_destructRequestStatus, "RequestableOwnable: destruct is requested");
Pausable.unpause();
}
}
contract KycList is Ownable {
/**
* @dev Stores the status of customers known by their address.
*/
mapping(address => bool) kycStatuses;
event KycStatusSet(address indexed admin, address indexed customer, bool status);
/**
* @dev Function to set the current KYC status of a customer.
* Only available to the contract's owner.
* @param customer address address by which the customer is known
* @param status bool new KYC status
*/
function setKycStatus(address customer, bool status) public onlyOwner {
require(kycStatuses[customer] != status, "KycList: no change to kyc status");
kycStatuses[customer] = status;
emit KycStatusSet(_msgSender(), customer, status);
}
/**
* @dev Function to get the current KYC status of a customer.
* @param customer address address by which the customer is known
* @return bool current KYC status
*/
function isKyced(address customer) public view returns (bool status) {
return kycStatuses[customer];
}
}
contract MyNxToken is RequestableOwnable, KycList, ERC721Full {
string constant internal NAME = "Club Necaxa";
string constant internal SYMBOL = "NECA";
uint256 constant internal TOKENID = 1;
event TokenUriSet(address indexed admin, uint256 indexed tokenId, string uri);
/**
* @dev Creates the contract and mints the only token.
* @param tokenUri string The metadata URI of the only token.
*/
constructor(string memory tokenUri) ERC721Full(NAME, SYMBOL) public {
ERC721Enumerable._mint(_msgSender(), TOKENID);
ERC721Metadata._setTokenURI(TOKENID, tokenUri);
}
/**
* @dev Function to set the token URI for a given token.
* Reverts if the token ID does not exist.
* Only accessible to the contract owner, and when the contract is not paused.
* @param tokenId uint256 ID of the token to set its URI
* @param uri string URI to assign
*/
function setTokenURI(uint256 tokenId, string memory uri) public onlyOwner whenNotPaused {
ERC721Metadata._setTokenURI(tokenId, uri);
emit TokenUriSet(_msgSender(), tokenId, uri);
}
/**
* @dev override
*/
function transferFrom(address from, address to, uint256 tokenId) public whenNotPaused {
require(isKyced(to), "MyNxToken: recipient is not Kyced by admin");
ERC721.transferFrom(from, to, tokenId);
}
/**
* @dev override
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public whenNotPaused {
require(isKyced(to), "MyNxToken: recipient is not Kyced by admin");
ERC721.safeTransferFrom(from, to, tokenId, _data);
}
/**
* @dev override
*/
function setApprovalForAll(address to, bool approved) public whenNotPaused {
ERC721.setApprovalForAll(to, approved);
}
/**
* @dev override
*/
function approve(address to, uint256 tokenId) public whenNotPaused {
ERC721.approve(to, tokenId);
}
/**
* @dev Let's someone effectively destroy the contract.
* Can only be called by the token holder, when the destruct request has been made.
*/
function acceptDestruct() public {
require(ownerOf(TOKENID) == _msgSender(), "MyNxToken: caller is not the token holder");
RequestableOwnable._acceptDestruct();
}
/**
* @dev Let's someone remove the destruct request.
* Can only be called by the token holder, when the destruct request has been made.
*/
function rejectDestruct() public {
require(ownerOf(TOKENID) == _msgSender(), "MyNxToken: caller is not the token holder");
RequestableOwnable._rejectDestruct();
}
}
|
* @dev Let's someone remove the destruct request. Can only be called when the destruct request has been made./
|
function _rejectDestruct() internal {
require(_destructRequestStatus, "RequestableOwnable: destruct is not requested");
_destructRequestStatus = false;
emit DestructRejected(_msgSender());
}
| 8,025,003 |
[
1,
24181,
1807,
18626,
1206,
326,
23819,
590,
18,
4480,
1338,
506,
2566,
1347,
326,
23819,
590,
711,
2118,
7165,
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
] |
[
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,
389,
24163,
6305,
8813,
1435,
2713,
288,
203,
3639,
2583,
24899,
5489,
8813,
691,
1482,
16,
315,
691,
429,
5460,
429,
30,
23819,
353,
486,
3764,
8863,
203,
3639,
389,
5489,
8813,
691,
1482,
273,
629,
31,
203,
3639,
3626,
10597,
8813,
19902,
24899,
3576,
12021,
10663,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./traits/TokenTraits.sol";
import "./traits/ITraits.sol";
import "./IVampireGame.sol";
/// @title The Vampire Game NFT contract
///
/// Note: The original Wolf Game's contract was used as insipiration, and a
/// few parts of the contract were taken directly, in particular the trait selection
/// and rarity using Walker's Alias method, and using a separate `Traits` contract
/// for getting the tokenURI.
///
/// Some info about how this contract works:
///
/// ### On-chain vs Off-chain
///
/// What is on-chain here?
/// - The generated traits
/// - The revealed traits metadata
/// - The traits img data
///
/// What is off-chain?
/// - The random number we get for batch reveals.
/// - The non-revealed image.
///
/// ### Minting and Revealing
///
/// 1. The user mints an NFT
/// 2. A seed is assigned for OG and Gen0 batches, this reveals the NFTs.
///
/// Why? We believe that as long as minting and revealing happens in the same
/// transaction, people will be able to cheat. So first you commit to minting, then
/// the seed is released.
///
/// ### Traits
///
/// The traits are all stored on-chain in another contract "Traits" similar to Wolf Game.
///
/// ### Game Controllers
///
/// For us to be able to expand on this game, future "game controller" contracts will be
/// able to freely call `mint` functions, and `transferFrom`, the logic to safeguard
/// those functions will be delegated to those contracts.
///
contract VampireGame is
IVampireGame,
IVampireGameControls,
ERC721,
Ownable,
Pausable,
ReentrancyGuard
{
/// ==== Events
event TokenRevealed(uint256 indexed tokenId, uint256 seed);
event OGRevealed(uint256 seed);
event Gen0Revealed(uint256 seed);
/// ==== Immutable Properties
/// @notice max amount of tokens that can be minted
uint16 public immutable maxSupply;
/// @notice max amount of og tokens
uint16 public immutable ogSupply;
/// @notice address to withdraw the eth
address private immutable splitter;
/// @notice minting price in wei
uint256 public immutable mintPrice;
/// ==== Mutable Properties
/// @notice current amount of minted tokens
uint16 public totalSupply;
/// @notice max amount of gen 0 tokens (tokens that can be bought with eth)
uint16 public genZeroSupply;
/// @notice seed for the OGs who minted contract v1
uint256 public ogSeed;
/// @notice seed for all Gen 0 except for OGs
uint256 public genZeroSeed;
/// @notice contract storing the traits data
ITraits public traits;
/// @notice game controllers they can access special functions
mapping(uint16 => uint256) public tokenSeeds;
/// @notice game controllers they can access special functions
mapping(address => bool) public controllers;
/// === Constructor
/// @dev constructor, most of the immutable props can be set here so it's easier to test
/// @param _mintPrice price to mint one token in wei
/// @param _maxSupply maximum amount of available tokens to mint
/// @param _genZeroSupply maxiumum amount of tokens that can be bought with eth
/// @param _splitter address to where the funds will go
constructor(
uint256 _mintPrice,
uint16 _maxSupply,
uint16 _genZeroSupply,
uint16 _ogSupply,
address _splitter
) ERC721("The Vampire Game", "VGAME") {
mintPrice = _mintPrice;
maxSupply = _maxSupply;
genZeroSupply = _genZeroSupply;
ogSupply = _ogSupply;
splitter = _splitter;
_pause();
}
/// ==== Modifiers
modifier onlyControllers() {
require(controllers[_msgSender()], "ONLY_CONTROLLERS");
_;
}
/// ==== Airdrop
function airdropToOwners(
address v1Contract,
uint16 from,
uint16 to
) external onlyOwner {
require(to >= from);
IERC721 v1 = IERC721(v1Contract);
for (uint16 i = from; i <= to; i++) {
_mint(v1.ownerOf(i), i);
}
totalSupply += (to - from + 1);
}
/// ==== Minting
/// @notice mint an unrevealed token using eth
/// @param amount amount to mint
function mintWithETH(uint16 amount)
external
payable
whenNotPaused
nonReentrant
{
require(amount > 0, "INVALID_AMOUNT");
require(amount * mintPrice == msg.value, "WRONG_VALUE");
uint16 supply = totalSupply;
require(supply + amount <= genZeroSupply, "NOT_ENOUGH_TOKENS");
totalSupply = supply + amount;
address to = _msgSender();
for (uint16 i = 0; i < amount; i++) {
_safeMint(to, supply + i);
}
}
/// ==== Revealing
/// @notice set the seed for the OG tokens. Once this is set, it cannot be changed!
function revealOgTokens(uint256 seed) external onlyOwner {
require(ogSeed == 0, "ALREADY_SET");
ogSeed = seed;
emit OGRevealed(seed);
}
/// @notice set the seed for the non-og Gen 0 tokens. Once this is set, it cannot be changed!
function revealGenZeroTokens(uint256 seed) external onlyOwner {
require(genZeroSeed == 0, "ALREADY_SET");
genZeroSeed = seed;
emit Gen0Revealed(seed);
}
/// ====================
/// @notice Calculate the seed for a specific token
/// - For OG tokens, the seed is derived from ogSeed
/// - For Gen 0 tokens, the seed is derived from genZeroSeed
/// - For other tokens, there is a seed for each for each
function seedForToken(uint16 tokenId) public view returns (uint256) {
uint16 supply = totalSupply;
uint16 og = ogSupply;
if (tokenId < og) {
// amount of minted tokens needs to be greater than or equal to the og supply
uint256 seed = ogSeed;
if (supply >= og && seed != 0) {
return
uint256(keccak256(abi.encodePacked(seed, "og", tokenId)));
}
return 0;
}
// read from storage only once
uint16 pt = genZeroSupply;
if (tokenId < pt) {
// amount of minted tokens needs to be greater than or equal to the og supply
uint256 seed = genZeroSeed;
if (supply >= pt && seed != 0) {
return
uint256(keccak256(abi.encodePacked(seed, "ze", tokenId)));
}
return 0;
}
if (supply > tokenId) {
return tokenSeeds[tokenId];
}
return 0;
}
/// ==== Functions to calculate traits given a seed
function _isVampire(uint256 seed) private pure returns (bool) {
return (seed & 0xFFFF) % 10 == 0;
}
/// Human Traits
function _tokenTraitHumanSkin(uint256 seed) private pure returns (uint8) {
uint256 traitSeed = (seed >> 16) & 0xFFFF;
uint256 trait = traitSeed % 5;
if (traitSeed >> 8 < [50, 15, 15, 250, 255][trait]) return uint8(trait);
return [3, 4, 4, 0, 3][trait];
}
function _tokenTraitHumanFace(uint256 seed) private pure returns (uint8) {
uint256 traitSeed = (seed >> 32) & 0xFFFF;
uint256 trait = traitSeed % 19;
if (
traitSeed >> 8 <
[
133,
189,
57,
255,
243,
133,
114,
135,
168,
38,
222,
57,
95,
57,
152,
114,
57,
133,
189
][trait]
) return uint8(trait);
return
[1, 0, 3, 1, 3, 3, 3, 4, 7, 4, 8, 4, 8, 10, 10, 10, 18, 18, 14][
trait
];
}
function _tokenTraitHumanTShirt(uint256 seed) private pure returns (uint8) {
uint256 traitSeed = (seed >> 48) & 0xFFFF;
uint256 trait = traitSeed % 28;
if (
traitSeed >> 8 <
[
181,
224,
147,
236,
220,
168,
160,
84,
173,
224,
221,
254,
140,
252,
224,
250,
100,
207,
84,
252,
196,
140,
228,
140,
255,
183,
241,
140
][trait]
) return uint8(trait);
return
[
1,
0,
3,
1,
3,
3,
4,
11,
11,
4,
9,
10,
13,
11,
13,
14,
15,
15,
20,
17,
19,
24,
20,
24,
22,
26,
24,
26
][trait];
}
function _tokenTraitHumanPants(uint256 seed) private pure returns (uint8) {
uint256 traitSeed = (seed >> 64) & 0xFFFF;
uint256 trait = traitSeed % 16;
if (
traitSeed >> 8 <
[
126,
171,
225,
240,
227,
112,
255,
240,
217,
80,
64,
160,
228,
80,
64,
167
][trait]
) return uint8(trait);
return [2, 0, 1, 2, 3, 3, 4, 6, 7, 4, 6, 7, 8, 8, 15, 12][trait];
}
function _tokenTraitHumanBoots(uint256 seed) private pure returns (uint8) {
uint256 traitSeed = (seed >> 80) & 0xFFFF;
uint256 trait = traitSeed % 6;
if (traitSeed >> 8 < [150, 30, 60, 255, 150, 60][trait])
return uint8(trait);
return [0, 3, 3, 0, 3, 4][trait];
}
function _tokenTraitHumanAccessory(uint256 seed)
private
pure
returns (uint8)
{
uint256 traitSeed = (seed >> 96) & 0xFFFF;
uint256 trait = traitSeed % 20;
if (
traitSeed >> 8 <
[
210,
135,
80,
245,
235,
110,
80,
100,
190,
100,
255,
160,
215,
80,
100,
185,
250,
240,
240,
100
][trait]
) return uint8(trait);
return
[
0,
0,
3,
0,
3,
4,
10,
12,
4,
16,
8,
16,
10,
17,
18,
12,
15,
16,
17,
18
][trait];
}
function _tokenTraitHumanHair(uint256 seed) private pure returns (uint8) {
uint256 traitSeed = (seed >> 112) & 0xFFFF;
uint256 trait = traitSeed % 10;
if (
traitSeed >> 8 <
[250, 115, 100, 40, 175, 255, 180, 100, 175, 185][trait]
) return uint8(trait);
return [0, 0, 4, 6, 0, 4, 5, 9, 6, 8][trait];
}
/// ==== Vampire Traits
function _tokenTraitVampireSkin(uint256 seed) private pure returns (uint8) {
uint256 traitSeed = (seed >> 16) & 0xFFFF;
uint256 trait = traitSeed % 13;
if (
traitSeed >> 8 <
[234, 239, 234, 234, 255, 234, 244, 249, 130, 234, 234, 247, 234][
trait
]
) return uint8(trait);
return [0, 0, 1, 2, 3, 4, 5, 6, 12, 7, 9, 10, 11][trait];
}
function _tokenTraitVampireFace(uint256 seed) private pure returns (uint8) {
uint256 traitSeed = (seed >> 32) & 0xFFFF;
uint256 trait = traitSeed % 15;
if (
traitSeed >> 8 <
[
45,
255,
165,
60,
195,
195,
45,
120,
75,
75,
105,
120,
255,
180,
150
][trait]
) return uint8(trait);
return [1, 0, 1, 4, 2, 4, 5, 12, 12, 13, 13, 14, 5, 12, 13][trait];
}
function _tokenTraitVampireClothes(uint256 seed)
private
pure
returns (uint8)
{
uint256 traitSeed = (seed >> 48) & 0xFFFF;
uint256 trait = traitSeed % 27;
if (
traitSeed >> 8 <
[
147,
180,
246,
201,
210,
252,
219,
189,
195,
156,
177,
171,
165,
225,
135,
135,
186,
135,
150,
243,
135,
255,
231,
141,
183,
150,
135
][trait]
) return uint8(trait);
return
[
2,
2,
0,
2,
3,
4,
5,
6,
7,
3,
3,
4,
4,
8,
5,
6,
13,
13,
19,
16,
19,
19,
21,
21,
21,
21,
22
][trait];
}
function _tokenTraitVampireCape(uint256 seed) private pure returns (uint8) {
uint256 traitSeed = (seed >> 128) & 0xFFFF;
uint256 trait = traitSeed % 9;
if (traitSeed >> 8 < [9, 9, 150, 90, 9, 210, 9, 9, 255][trait])
return uint8(trait);
return [5, 5, 0, 2, 8, 3, 8, 8, 5][trait];
}
function _tokenTraitVampirePredatorIndex(uint256 seed)
private
pure
returns (uint8)
{
uint256 traitSeed = (seed >> 144) & 0xFFFF;
uint256 trait = traitSeed % 4;
if (traitSeed >> 8 < [255, 8, 160, 73][trait]) return uint8(trait);
return [0, 0, 0, 2][trait];
}
/// ==== State Control
/// @notice set the max amount of gen 0 tokens
function setGenZeroSupply(uint16 _genZeroSupply) external onlyOwner {
require(genZeroSupply != _genZeroSupply, "NO_CHANGES");
genZeroSupply = _genZeroSupply;
}
/// @notice set the contract for the traits rendering
/// @param _traits the contract address
function setTraits(address _traits) external onlyOwner {
traits = ITraits(_traits);
}
/// @notice add controller authority to an address
/// @param _controller address to the game controller
function addController(address _controller) external onlyOwner {
controllers[_controller] = true;
}
/// @notice remove controller authority from an address
/// @param _controller address to the game controller
function removeController(address _controller) external onlyOwner {
controllers[_controller] = false;
}
/// ==== Withdraw
/// @notice withdraw the ether from the contract
function withdraw() external onlyOwner {
uint256 contractBalance = address(this).balance;
// solhint-disable-next-line avoid-low-level-calls
(bool sent, ) = splitter.call{value: contractBalance}("");
require(sent, "FAILED_TO_WITHDRAW");
}
/// @notice withdraw ERC20 tokens from the contract
/// people always randomly transfer ERC20 tokens to the
/// @param erc20TokenAddress the ERC20 token address
/// @param recipient who will get the tokens
/// @param amount how many tokens
function withdrawERC20(
address erc20TokenAddress,
address recipient,
uint256 amount
) external onlyOwner {
IERC20 erc20Contract = IERC20(erc20TokenAddress);
bool sent = erc20Contract.transfer(recipient, amount);
require(sent, "ERC20_WITHDRAW_FAILED");
}
/// @notice reserve some tokens for the team. Can only reserve gen 0 tokens
/// we also need token 0 to so setup market places before mint
function reserve(address to, uint16 amount) external onlyOwner {
uint16 supply = totalSupply;
require(supply + amount < genZeroSupply);
totalSupply = supply + amount;
for (uint16 i = 0; i < amount; i++) {
_safeMint(to, supply + i);
}
}
/// ==== pause/unpause
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
/// ==== IVampireGameControls Overrides
/// @notice see {IVampireGameControls.mintFromController}
function mintFromController(address receiver, uint16 amount)
external
override
whenNotPaused
onlyControllers
{
uint16 supply = totalSupply;
require(supply + amount <= maxSupply, "NOT_ENOUGH_TOKENS");
totalSupply = supply + amount;
for (uint256 i = 0; i < amount; i++) {
_safeMint(receiver, supply + i);
}
}
/// @notice for a game controller to reveal the metadata of multiple token ids
function controllerRevealTokens(
uint16[] calldata tokenIds,
uint256[] calldata seeds
) external override whenNotPaused onlyControllers {
require(
tokenIds.length == seeds.length,
"INPUTS_SHOULD_HAVE_SAME_LENGTH"
);
for (uint256 i = 0; i < tokenIds.length; i++) {
require(tokenSeeds[tokenIds[i]] == 0, "ALREADY_REVEALED");
tokenSeeds[tokenIds[i]] = seeds[i];
emit TokenRevealed(tokenIds[i], seeds[i]);
}
}
/// ==== IVampireGame Overrides
/// @notice see {IVampireGame.getTotalSupply}
function getTotalSupply() external view override returns (uint16) {
return totalSupply;
}
/// @notice see {IVampireGame.getOGSupply}
function getOGSupply() external view override returns (uint16) {
return ogSupply;
}
/// @notice see {IVampireGame.getGenZeroSupply}
function getGenZeroSupply() external view override returns (uint16) {
return genZeroSupply;
}
/// @notice see {IVampireGame.getMaxSupply}
function getMaxSupply() external view override returns (uint16) {
return maxSupply;
}
/// @notice see {IVampireGame.getTokenTraits}
function getTokenTraits(uint16 tokenId)
external
view
override
returns (TokenTraits memory tt)
{
uint256 seed = seedForToken(tokenId);
require(seed != 0, "NOT_REVEALED");
tt.isVampire = _isVampire(seed);
if (tt.isVampire) {
tt.skin = _tokenTraitVampireSkin(seed);
tt.face = _tokenTraitVampireFace(seed);
tt.clothes = _tokenTraitVampireClothes(seed);
tt.cape = _tokenTraitVampireCape(seed);
tt.predatorIndex = _tokenTraitVampirePredatorIndex(seed);
} else {
tt.skin = _tokenTraitHumanSkin(seed);
tt.face = _tokenTraitHumanFace(seed);
tt.clothes = _tokenTraitHumanTShirt(seed);
tt.pants = _tokenTraitHumanPants(seed);
tt.boots = _tokenTraitHumanBoots(seed);
tt.accessory = _tokenTraitHumanAccessory(seed);
tt.hair = _tokenTraitHumanHair(seed);
}
}
function isTokenVampire(uint16 tokenId)
external
view
override
returns (bool)
{
return _isVampire(seedForToken(tokenId));
}
function getPredatorIndex(uint16 tokenId)
external
view
override
returns (uint8)
{
uint256 seed = seedForToken(tokenId);
require(seed != 0, "NOT_REVEALED");
return _tokenTraitVampirePredatorIndex(seed);
}
/// @notice see {IVampireGame.isTokenRevealed(tokenId)}
function isTokenRevealed(uint16 tokenId)
public
view
override
returns (bool)
{
return seedForToken(tokenId) != 0;
}
/// ==== ERC721 Overrides
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
// Hardcode approval of game controllers
if (!controllers[_msgSender()])
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
return traits.tokenURI(tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
struct TokenTraits {
bool isVampire;
// Shared Traits
uint8 skin;
uint8 face;
uint8 clothes;
// Human-only Traits
uint8 pants;
uint8 boots;
uint8 accessory;
uint8 hair;
// Vampire-only Traits
uint8 cape;
uint8 predatorIndex;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
interface ITraits {
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import "./traits/TokenTraits.sol";
/// @notice Interface to interact with the VampireGame contract
interface IVampireGame {
/// @notice get the amount of tokens minted
function getTotalSupply() external view returns (uint16);
/// @notice get tthe amount of og supply
function getOGSupply() external view returns (uint16);
/// @notice get the total supply of gen-0
function getGenZeroSupply() external view returns (uint16);
/// @notice get the total supply of tokens
function getMaxSupply() external view returns (uint16);
/// @notice get the TokenTraits for a given tokenId
function getTokenTraits(uint16 tokenId) external view returns (TokenTraits memory);
/// @notice check if token id a vampire
function isTokenVampire(uint16 tokenId) external view returns (bool);
/// @notice get the Predator Index for a given tokenId
function getPredatorIndex(uint16 tokenId) external view returns (uint8);
/// @notice returns true if a token is aleady revealed
function isTokenRevealed(uint16 tokenId) external view returns (bool);
}
/// @notice Interface to control parts of the VampireGame ERC 721
interface IVampireGameControls {
/// @notice mint any amount of nft to any address
/// Requirements:
/// - message sender should be an allowed address (game contract)
/// - amount + totalSupply() has to be smaller than MAX_SUPPLY
function mintFromController(address receiver, uint16 amount) external;
/// @notice reveal a list of tokens using specific seeds for each
function controllerRevealTokens(uint16[] calldata tokenIds, uint256[] calldata seeds) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
@notice withdraw ERC20 tokens from the contract people always randomly transfer ERC20 tokens to the @param erc20TokenAddress the ERC20 token address @param recipient who will get the tokens @param amount how many tokens
|
function withdrawERC20(
address erc20TokenAddress,
address recipient,
uint256 amount
) external onlyOwner {
IERC20 erc20Contract = IERC20(erc20TokenAddress);
bool sent = erc20Contract.transfer(recipient, amount);
require(sent, "ERC20_WITHDRAW_FAILED");
}
| 588,793 |
[
1,
1918,
9446,
4232,
39,
3462,
2430,
628,
326,
6835,
16951,
3712,
20153,
7412,
4232,
39,
3462,
2430,
358,
326,
225,
6445,
71,
3462,
1345,
1887,
326,
4232,
39,
3462,
1147,
1758,
225,
8027,
10354,
903,
336,
326,
2430,
225,
3844,
3661,
4906,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
598,
9446,
654,
39,
3462,
12,
203,
3639,
1758,
6445,
71,
3462,
1345,
1887,
16,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3903,
1338,
5541,
288,
203,
3639,
467,
654,
39,
3462,
6445,
71,
3462,
8924,
273,
467,
654,
39,
3462,
12,
12610,
3462,
1345,
1887,
1769,
203,
3639,
1426,
3271,
273,
6445,
71,
3462,
8924,
18,
13866,
12,
20367,
16,
3844,
1769,
203,
3639,
2583,
12,
7569,
16,
315,
654,
39,
3462,
67,
9147,
40,
10821,
67,
11965,
8863,
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
] |
pragma solidity ^0.4.17;
contract DADetails {
//STRUCTS
struct FileAttachment {
string[] ipfsHash;
string fileName;
string fileType;
address uploadedBy;
}
struct EventLog {
//string id;
uint date;
string party;
string description;
string ipfsHash;
}
// EVENTS
event StateChanged(ContractStates newState);
// ... all the state changes ...
// FIELDS
uint eventId;
address public applicant;
string public daid;
uint public dateLodged;
uint public dateApproved;
//...
// parcels {LotId, SectionId, PlanId, PlanType};
string public description;
uint public estimatedCost;
string public lga;
// construction certificate lodge date
uint public ccDateLodged;
// construction certificate approved date
uint public ccDateApproved;
// construction certificate description
string public ccDescription;
// Sub division certificate lodge date
uint public sdcDateLodged;
// Sub division certificate approved date
uint public sdcDateApproved;
// sub division certificate description
string public sdcDescription;
// Plan approve certificate lodge date
uint public planApproveDateLodged;
// Plan registered certificate approved date
uint public planRegisteredDateApproved;
// Plan registered certificate description
string public planRegisteredDescription;
// status: DALodged, DApproval
string[] public fileNames;
mapping (string => FileAttachment) attachments;
string[] public eventLogIds;
mapping (string => EventLog) eventLogs;
// contract states
enum ContractStates {DALodged, DAApproved, CCLodged, CCApproved, SCLodged, SCApproved, PlanLodged, PlanRegistered }
ContractStates public State;
// statechangedevents[]
// CONSTRUCTOR
function DADetails (string _daId, uint _dateLodged, string _description, string _lga) public {
applicant = msg.sender;
daid = _daId;
dateLodged = _dateLodged;
description = _description;
lga = _lga;
}
// METHODS
// function change the state
function ChangeState(ContractStates newState) public {
State = newState;
StateChanged(newState);
}
// function returns the current state
function getCurrentState() public view returns (ContractStates) {
return State;
}
// function changes the state to DA lodged
function DALodge (address _applicant, string _daid, uint _dateLodged, string _description, string _lga, uint _estimatedcost, uint _dateApproved) public {
applicant = msg.sender;
daid = _daid;
dateLodged = _dateLodged;
description = _description;
lga = _lga;
estimatedCost = _estimatedcost;
dateApproved = _dateApproved;
ChangeState(ContractStates.DALodged);
}
// function changes the state to DA Approved if current contract state is DA Lodged
function DAApprove(bool DAApproveResult) public returns (bool) {
require(State == ContractStates.DALodged);
if(DAApproveResult) {
ChangeState(ContractStates.DAApproved);
}
return true;
}
// function changes the state to construction (CC) lodged if current contract state is DAApproved approved
function CCLodge (uint _ccDateLodged, string _ccDescription, uint _ccDateApproved) public {
require(State == ContractStates.DAApproved);
ccDateLodged = _ccDateLodged;
ccDescription = _ccDescription;
ccDateApproved = _ccDateApproved;
ChangeState(ContractStates.CCLodged);
}
// function changes the state to construction (CC) approved if current contract state is construction (CC) lodged
function CCApprove(bool CCApproveResult) public returns (bool) {
require(State == ContractStates.CCLodged);
if(CCApproveResult) {
ChangeState(ContractStates.CCApproved);
}
return true;
}
// function changes the state to sub division (SC) lodged if current contract state is construction (CC) approved
function SCLodge (uint _sdcDateLodged, string _sdcDescription, uint _sdcDateApproved) public {
require(State == ContractStates.CCApproved);
sdcDateLodged = _sdcDateLodged;
sdcDescription = _sdcDescription;
sdcDateApproved = _sdcDateApproved;
ChangeState(ContractStates.SCLodged);
}
// function changes the state to sub division (SC) approved if current contract state is sub division (SC) lodged
function SCApprove(bool SCApproveResult) public returns (bool) {
require(State == ContractStates.SCLodged);
if(SCApproveResult) {
ChangeState(ContractStates.SCApproved);
}
return true;
}
// function changes the state to Plan lodged if current contract state is sub divison approved
function PlanApprove (uint _planApproveDateLodged, string _planRegisteredDescription, uint _planRegisteredDateApproved) public {
require(State == ContractStates.SCApproved);
planApproveDateLodged = _planApproveDateLodged;
planRegisteredDateApproved = _planRegisteredDateApproved;
planRegisteredDescription = _planRegisteredDescription;
ChangeState(ContractStates.PlanLodged);
}
// function changes the state to PlanRegistered if current contract state is Plan Lodged
function PlanRegister(bool PlanRegisteredResult) public returns (bool) {
require(State == ContractStates.PlanLodged);
if (PlanRegisteredResult) {
ChangeState(ContractStates.PlanRegistered);
}
return true;
}
// get the hash of all the geographic files associated with this contract
function getGeoFiles() public view returns(string) {
return "[]";
}
function addAttachment(string fileName, string fileType, address uploadedBy, string ipfsHash) public returns(bool) {
// look for the file name in the contract already
var attachment = attachments[fileName];
// if it's there, simply add the ipfs hash to the array of hashes, update the filetype and uploadedby
// if it's not, we get a blank one back, so this will fill it in.
if (attachment.uploadedBy == 0x00) {
fileNames.push(fileName);
}
attachment.ipfsHash.push(ipfsHash);
attachment.fileType = fileType;
attachment.uploadedBy = uploadedBy;
attachment.fileName = fileName;
attachments[fileName] = attachment;
}
function getFileNamesCount() public view returns(uint256) {
return fileNames.length;
}
function getFileName(uint256 index) public view returns(string) {
return fileNames[index];
}
function getFileType(string fileName) public view returns(string) {
var attachment = attachments[fileName];
return attachment.fileType;
}
function getLatestIpfsHash(string fileName) public view returns(string) {
var attachment = attachments[fileName];
if (attachment.uploadedBy == 0x00) {
return "";
} else {
return attachment.ipfsHash[attachment.ipfsHash.length - 1];
}
}
function getAttachmentVersionCount(string fileName) public view returns(uint256) {
var attachment = attachments[fileName];
if (attachment.uploadedBy == 0x00) {
return 0;
} else {
return attachment.ipfsHash.length;
}
}
function getAttachmentVersionByIndex(string fileName, uint256 index) public view returns(string) {
var attachment = attachments[fileName];
if (attachment.uploadedBy == 0x00) {
return "";
} else if (attachment.ipfsHash.length < index + 1) {
return "";
} else {
return attachment.ipfsHash[index];
}
}
function getUploadedBy(string fileName) public view returns(address) {
var attachment = attachments[fileName];
return attachment.uploadedBy;
}
// Concate string
function strConcat(string _a, string _b, string _c) internal returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
string memory abcde = new string(_ba.length + _bb.length + _bc.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) {
babcde[k++] = _ba[i];
}
for (i = 0; i < _bb.length; i++) {
babcde[k++] = _bb[i];
}
for (i = 0; i < _bc.length; i++) {
babcde[k++] = _bc[i];
}
return string(babcde);
}
function uintToString(uint v) constant returns (string) {
if (v==0) {
return "0";
}
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory s = new bytes(i);
for (uint j = 0; j < i; j++) {
s[j] = reversed[i - 1 - j];
}
return string(s);
}
function addEventLog(string _party, string _description, string _ipfsHash) public returns(string) {
var length = uintToString(getEventLogsCount());
var eventLogId = strConcat(daid, "_", length);
var eventLog = EventLog(now, _party, _description, _ipfsHash);
eventLogIds.push(eventLogId);
eventLogs[eventLogId] = eventLog;
return eventLogId;
}
function getEventLogPartyById(string eventLogId) public view returns(string) {
var eventLog = eventLogs[eventLogId];
return eventLog.party;
}
function getEventLogDateById(string eventLogId) public view returns(uint) {
var eventLog = eventLogs[eventLogId];
return eventLog.date;
}
function getEventLogDescriptionById(string eventLogId) public view returns(string) {
var eventLog = eventLogs[eventLogId];
return eventLog.description;
}
function getEventLogIpfsHashById(string eventLogId) public view returns(string) {
var eventLog = eventLogs[eventLogId];
return eventLog.ipfsHash;
}
function getEventLogId(uint256 index) public view returns(string) {
return eventLogIds[index];
}
function getEventLogsCount() public view returns (uint256) {
return eventLogIds.length;
}
}
|
function changes the state to construction (CC) lodged if current contract state is DAApproved approved
|
function CCLodge (uint _ccDateLodged, string _ccDescription, uint _ccDateApproved) public {
require(State == ContractStates.DAApproved);
ccDateLodged = _ccDateLodged;
ccDescription = _ccDescription;
ccDateApproved = _ccDateApproved;
ChangeState(ContractStates.CCLodged);
}
| 1,821,426 |
[
1,
915,
3478,
326,
919,
358,
16171,
261,
6743,
13,
328,
369,
2423,
309,
783,
6835,
919,
353,
463,
37,
31639,
20412,
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,
385,
5017,
369,
908,
261,
11890,
389,
952,
1626,
48,
369,
2423,
16,
533,
389,
952,
3291,
16,
2254,
389,
952,
1626,
31639,
13,
1071,
288,
4202,
203,
3639,
2583,
12,
1119,
422,
13456,
7629,
18,
9793,
31639,
1769,
27699,
3639,
203,
3639,
4946,
1626,
48,
369,
2423,
273,
389,
952,
1626,
48,
369,
2423,
31,
203,
3639,
4946,
3291,
273,
389,
952,
3291,
31,
203,
3639,
4946,
1626,
31639,
273,
389,
952,
1626,
31639,
31,
203,
203,
3639,
7576,
1119,
12,
8924,
7629,
18,
39,
5017,
369,
2423,
1769,
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
] |
./partial_match/1/0x6Ea3966187E86242965aB29Bc9dA9486B9fB8586/sources/contracts/Calculations.sol
|
* @notice Calculates the percentage of principal to return to users if a knock in occurs. Iterates through all knock-in barriers and checks the ratio of (spot/strike) for each asset Returns the minimum of the knock-in ratios. @param self is the FCNVaultMetadata @param cegaStateAddress is address of cegaState/ Only calculate the ratio if it is a knock in barrier
|
function calculateKnockInRatio(
FCNVaultMetadata storage self,
address cegaStateAddress
) public view returns (uint256) {
OptionBarrier[] memory optionBarriers = self.optionBarriers;
uint256 optionBarriersCount = self.optionBarriersCount;
uint256 minRatioBps = LARGE_CONSTANT;
for (uint256 i = 0; i < optionBarriersCount; i++) {
OptionBarrier memory optionBarrier = optionBarriers[i];
address oracle = getOracleAddress(optionBarrier, cegaStateAddress);
(, int256 answer, , , ) = IOracle(oracle).latestRoundData();
if (optionBarrier.barrierType == OptionBarrierType.KnockIn) {
uint256 ratioBps = (uint256(answer) * LARGE_CONSTANT) / optionBarrier.strikeAbsoluteValue;
minRatioBps = Math.min(ratioBps, minRatioBps);
}
}
return ((minRatioBps * BPS_DECIMALS)) / LARGE_CONSTANT;
}
| 3,646,508 |
[
1,
10587,
326,
11622,
434,
8897,
358,
327,
358,
3677,
309,
279,
15516,
975,
316,
9938,
18,
3016,
815,
3059,
777,
15516,
975,
17,
267,
4653,
566,
414,
471,
4271,
326,
7169,
434,
261,
19032,
19,
701,
2547,
13,
364,
1517,
3310,
2860,
326,
5224,
434,
326,
15516,
975,
17,
267,
25706,
18,
225,
365,
353,
326,
478,
39,
11679,
3714,
2277,
225,
276,
11061,
1119,
1887,
353,
1758,
434,
276,
11061,
1119,
19,
5098,
4604,
326,
7169,
309,
518,
353,
279,
15516,
975,
316,
24651,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
4604,
47,
82,
975,
382,
8541,
12,
203,
3639,
478,
39,
11679,
3714,
2277,
2502,
365,
16,
203,
3639,
1758,
276,
11061,
1119,
1887,
203,
565,
262,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2698,
5190,
10342,
8526,
3778,
1456,
5190,
566,
414,
273,
365,
18,
3482,
5190,
566,
414,
31,
203,
3639,
2254,
5034,
1456,
5190,
566,
414,
1380,
273,
365,
18,
3482,
5190,
566,
414,
1380,
31,
203,
203,
3639,
2254,
5034,
1131,
8541,
38,
1121,
273,
511,
28847,
67,
25878,
31,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
1456,
5190,
566,
414,
1380,
31,
277,
27245,
288,
203,
5411,
2698,
5190,
10342,
3778,
1456,
5190,
10342,
273,
1456,
5190,
566,
414,
63,
77,
15533,
203,
5411,
1758,
20865,
273,
17971,
16873,
1887,
12,
3482,
5190,
10342,
16,
276,
11061,
1119,
1887,
1769,
203,
5411,
261,
16,
509,
5034,
5803,
16,
269,
269,
262,
273,
1665,
16873,
12,
280,
16066,
2934,
13550,
11066,
751,
5621,
203,
203,
5411,
309,
261,
3482,
5190,
10342,
18,
3215,
10342,
559,
422,
2698,
5190,
10342,
559,
18,
47,
82,
975,
382,
13,
288,
203,
7734,
2254,
5034,
7169,
38,
1121,
273,
261,
11890,
5034,
12,
13490,
13,
380,
511,
28847,
67,
25878,
13,
342,
1456,
5190,
10342,
18,
701,
2547,
10368,
620,
31,
203,
7734,
1131,
8541,
38,
1121,
273,
2361,
18,
1154,
12,
9847,
38,
1121,
16,
1131,
8541,
38,
1121,
1769,
203,
5411,
289,
203,
3639,
289,
203,
3639,
327,
14015,
1154,
8541,
38,
2
] |
// SPDX-License-Identifier: MIT
pragma solidity =0.8.4;
import "./IERC20.sol";
contract LeveragePool {
address public admin;
IERC20 public collateralToken;
IOracle public oracle;
IFundingRateModel public fundingRateModel;
uint256 public epochStartTime;
uint256 public epoch;
int256 public price;
int256 public adminFees;
int256 public constant PRECISION = 10**18; // 1
int256 public constant SECONDS_PER_YEAR = 31556952;
int256 public TRANSACTION_FEE = 3*10**15; // 0.3% fee
int256 public ADMIN_FEES = 2*10**17; // 20%
int256 public LIQUIDITYPOOL_FEES = 8*10**17; // 80%
int256 public CHANGE_CAP = 5*10**16; // 5%
uint256 public epochPeriod=15; //60*60; // 1 hour (15 seconds for testing)
uint256 public waitPeriod= 5; //6*60; // 6 minutes (5 seconds for testing)
mapping(address => UserInfo) public userInfo;
Pool[] public pools;
mapping(uint256 => mapping (uint256 => PoolEpochData)) public poolEpochData;
struct UserInfo {
uint256 index;
Action[] actions;
int256 withdrawableCollateral;
mapping(uint256 =>int256) shares;
}
struct Action {
uint256 epoch;
uint256 pool;
int256 depositAmount;
int256 withdrawAmount;
}
struct Pool {
int256 shares;
int256 collateral;
int256 leverage;
int256 rebalanceMultiplier;
bool isLiquidityPool;
}
struct PoolEpochData {
int256 sharesPerCollateralDeposit;
int256 collateralPerShareWithdraw;
int256 deposits;
int256 withdrawals;
}
struct PoolAmounts {
int256 longAmount;
int256 shortAmount;
int256 liquidityPoolAmount;
int256 rebalanceAmount;
int256 longLeverage;
int256 shortLeverage;
int256 liquidityPoolLeverage;
}
struct Rates {
int256 longFundingRate;
int256 shortFundingRate;
int256 liquidityPoolFundingRate;
int256 rebalanceRate;
int256 rebalanceLiquidityPoolRate;
}
constructor(
IERC20 _collateralToken,
IOracle _oracle,
IFundingRateModel _fundingRateModel,
uint256 _inception
) {
collateralToken = _collateralToken;
oracle = _oracle;
fundingRateModel = _fundingRateModel;
price = int256(getPrice());
admin = msg.sender;
epochStartTime = _inception==0?block.timestamp:_inception;
}
/* ========== EXTERNAL STATE CHANGING ========== */
/**
* Schedule a deposit for the next epoch
**/
function deposit(int256 amount, uint256 pool) external {
require (pool<pools.length,"Pool not initialized");
require (amount>=0,"amount needs to be positive");
_bookKeeping(msg.sender);
UserInfo storage info = userInfo[msg.sender];
// Try to pay from the withdrawableCollateral first
int256 transferAmount = amount;
if (info.withdrawableCollateral>0) {
if (transferAmount>info.withdrawableCollateral) {
transferAmount-=info.withdrawableCollateral;
info.withdrawableCollateral=0;
} else {
info.withdrawableCollateral-=transferAmount;
transferAmount=0;
}
}
if (transferAmount>0 && address(collateralToken)!=address(0x0)) require(collateralToken.transferFrom(msg.sender,address(this),uint256(transferAmount)),"Transfer failed");
Action memory action;
action.epoch = _getNextEpoch();
action.pool = pool;
action.depositAmount = amount;
info.actions.push(action);
PoolEpochData storage data = poolEpochData[action.epoch][action.pool];
data.deposits+=amount;
emit DepositInPool(msg.sender,amount,pool,action.epoch);
}
/**
* Schedule a withdraw for the next epoch
**/
function withdraw(int256 amount, uint256 pool) external {
require (pool<pools.length,"Pool not initialized");
require (amount>=0,"amount needs to be positive");
_bookKeeping(msg.sender);
UserInfo storage info = userInfo[msg.sender];
require(info.shares[pool]>=amount,"No enough shares");
info.shares[pool]-=amount;
Action memory action;
action.epoch = _getNextEpoch();
action.pool = pool;
action.withdrawAmount = amount;
info.actions.push(action);
PoolEpochData storage data = poolEpochData[action.epoch][action.pool];
data.withdrawals+=amount;
emit WithdrawFromPool(msg.sender,amount,pool,action.epoch);
}
/**
* Withdraw available collateral to the user
**/
function withdrawCollateral(int256 amount) external {
require (amount>=0,"amount needs to be positive");
_bookKeeping(msg.sender);
UserInfo storage info = userInfo[msg.sender];
if (amount<=0) amount = info.withdrawableCollateral; // withdraw all
require (info.withdrawableCollateral>=amount,"Balance to low");
info.withdrawableCollateral-=amount;
if (amount>0 && address(collateralToken)!=address(0x0)) require(collateralToken.transfer(msg.sender,uint256(amount)),"Transfer failed");
}
/**
* Start a new epoch external call, free to call
**/
function startNextEpoch() external {
_startNextEpoch();
}
/**
* Withdraw admin fees
**/
function withdrawAdminFees(int256 amount) external {
require (msg.sender==admin,"Only admin");
require (amount<=adminFees,"Not enough funds");
adminFees-=amount;
if (address(collateralToken)!=address(0x0)) require(collateralToken.transfer(msg.sender,uint256(amount)),"Transfer failed");
}
/**
* Do the bookkeeping for a user (for testing)
**/
function bookKeeping() external {
_bookKeeping(msg.sender);
}
/**
* Add a new pool
**/
function addPool(int256 leverage,bool isLiquidityPool) internal {
_addPool(leverage,isLiquidityPool);
}
/**
* Set epoch period and waiting period
**/
function setEpochPeriods(uint256 _epochPeriod, uint256 _waitPeriod) external {
require (msg.sender==admin,"Only admin");
require (_epochPeriod>0 && _waitPeriod>0,"Periods can not be 0");
require (_waitPeriod<=_epochPeriod,"Wait period too long");
epochPeriod = _epochPeriod;
waitPeriod = _waitPeriod;
emit SetEpochPeriods(_epochPeriod,_waitPeriod);
}
/**
* Set transaction fees and division between the admin and the liquidity pools
**/
function setFees(int256 _TRANSACTION_FEE, int256 _ADMIN_FEES, int256 _LIQUIDITYPOOL_FEES) external {
require (msg.sender==admin,"Only admin");
require (_TRANSACTION_FEE>=0 && _ADMIN_FEES>=0 && _LIQUIDITYPOOL_FEES>=0,"Fees can not be negative");
require (_TRANSACTION_FEE<=2*10**16,"Transaction fee too high"); // max 2%
require (_ADMIN_FEES + _LIQUIDITYPOOL_FEES == PRECISION,"Fees not correct");
TRANSACTION_FEE = _TRANSACTION_FEE;
ADMIN_FEES = _ADMIN_FEES;
LIQUIDITYPOOL_FEES = _LIQUIDITYPOOL_FEES;
emit SetFees(_TRANSACTION_FEE,_ADMIN_FEES,_LIQUIDITYPOOL_FEES);
}
/**
* Set a new Admin
**/
function setAdmin(address newAdmin) external {
require (msg.sender==admin,"Only admin");
require (newAdmin!=address(0x0),"Admin can not be zero");
admin = newAdmin;
}
/**
* Set a new CHANGE_CAP
**/
function setChangeCap(int256 _CHANGE_CAP) external {
require (msg.sender==admin,"Only admin");
CHANGE_CAP = _CHANGE_CAP;
}
/**
* Set a new Oracle
**/
function setOracle(address newOracle) external {
require (msg.sender==admin,"Only admin");
oracle = IOracle(newOracle);
}
/**
* Set a new funding rate model
**/
function setFundingRateModel(address newFundingRateModel) external {
require (msg.sender==admin,"Only admin");
fundingRateModel = IFundingRateModel(newFundingRateModel);
}
/**
* Add pools default pools
**/
function initializePools() external {
require (pools.length==0,"Pools allready initialized");
_addPool(1,true);
_addPool(1,false);
_addPool(-1,false);
_addPool(2,true);
_addPool(2,false);
_addPool(-2,false);
_addPool(3,true);
_addPool(3,false);
_addPool(-3,false);
}
/* ========== EXTERNAL "VIEWS" ========== */
/**
* Calculate the total amounts over all pools and the leverage for longs/shorts/liquidity pool
**/
function calculatePoolAmounts() external view returns (PoolAmounts memory amounts) {
amounts = _calculatePoolAmounts();
}
/**
* Get the number of shares for the given user per pool.
* This is not a view, because we do bookkeeping first, but hopfully we can used it as such.
**/
function getUserShares(address user) external returns (int256[] memory shares) {
_bookKeeping(user);
return _getUserShares(user);
}
function getUserSharesView(address user) external view returns (int256[] memory shares) {
return _getUserShares(user);
}
function _getUserShares(address user) internal view returns (int256[] memory shares) {
UserInfo storage info = userInfo[user];
shares = new int256[](pools.length);
for (uint256 i=0;i<pools.length;i++) {
shares[i] = info.shares[i];
}
return shares;
}
/**
* Get the collateral owned for the given user per pool.
* This is not a view, because we do bookkeeping first, but hopfully we can used it as such.
**/
function getUserDeposits(address user) external returns (int256[] memory deposits) {
_bookKeeping(user);
return _getUserDeposits(user);
}
function getUserDepositsView(address user) external view returns (int256[] memory deposits) {
return _getUserDeposits(user);
}
function _getUserDeposits(address user) internal view returns (int256[] memory deposits) {
UserInfo storage info = userInfo[user];
deposits = new int256[](pools.length);
for (uint256 i=0;i<pools.length;i++) {
if (pools[i].shares>0) deposits[i] = info.shares[i]*pools[i].collateral/pools[i].shares;
}
}
/**
* Get the pernding actions for the given user.
* This is not a view, because we do bookkeeping first, but hopfully we can used it as such.
**/
function getUserActions(address user) external returns (Action[] memory) {
_bookKeeping(user);
return _getUserActionsView(user);
}
function getUserActionsView(address user) external view returns (Action[] memory) {
return _getUserActionsView(user);
}
function _getUserActionsView(address user) internal view returns (Action[] memory actions) {
UserInfo storage info = userInfo[user];
actions = new Action[](info.actions.length-info.index);
for (uint256 i=info.index;i<info.actions.length;i++) {
actions[i-info.index]=info.actions[i];
}
}
/**
* Get the withdrawable collateral for the given user.
* This is not a view, because we do bookkeeping first, but hopfully we can used it as such.
**/
function getWithdrawableCollateral(address user) external returns (int256) {
_bookKeeping(user);
UserInfo storage info = userInfo[user];
return info.withdrawableCollateral;
}
function getWithdrawableCollateralView(address user) external view returns (int256) {
UserInfo storage info = userInfo[user];
return info.withdrawableCollateral;
}
/**
* Get current funding and rebalancing rates.
**/
function getRates() external view returns (Rates memory rates) {
return getRates(_calculatePoolAmounts());
}
/**
* Return the number of pools
**/
function getNoPools() external view returns (uint256) {
return pools.length;
}
/* ========== INTERNAL STATE CHANGING ========== */
/**
* Do the bookkeeping for the current user, by applying the deposits and withdrawels of all epochs that have past.
*/
function _bookKeeping(address user) internal {
UserInfo storage info = userInfo[user];
while (info.index<info.actions.length) {
Action storage action = info.actions[info.index];
if (action.epoch<=epoch) {
PoolEpochData storage data = poolEpochData[action.epoch][action.pool];
if (action.depositAmount>0) {
int256 newShares = (action.depositAmount*data.sharesPerCollateralDeposit/PRECISION);
info.shares[action.pool]+=newShares;
} else if (action.withdrawAmount>0) {
int256 withdrawn = (action.withdrawAmount*data.collateralPerShareWithdraw/PRECISION);
info.withdrawableCollateral+=withdrawn;
}
delete info.actions[info.index];
info.index++;
} else break;
}
}
/**
* Start a new epoch if the time is up.
* Step 1: Apply the price change over the last period to all the pools, do it multiple times if price has change more than the CHANGE_CAP.
* Step 2: Apply the funding and rebalance rates for all the pools.
* Step 3: Do all deposits/withdrawels.
* Step 4: Distribute the fees among the liquidity pools.
**/
function _startNextEpoch() internal {
// check for next epoch time
if (block.timestamp>=epochStartTime+epochPeriod) {
epoch++;
emit Epoch(epoch,price);
epochStartTime+=epochPeriod;
{ // Apply the price change to all the pools
int256 prevPrice=price;
price = int256(getPrice());
bool lastLoop;
while (!lastLoop) {
int256 change = (price-prevPrice)*PRECISION/prevPrice;
if (change>CHANGE_CAP) change = CHANGE_CAP;
else if (change<-CHANGE_CAP) change = -CHANGE_CAP;
else lastLoop=true;
PoolAmounts memory amounts = _calculatePoolAmounts();
int256 longChange=change*amounts.longLeverage/PRECISION;
int256 shortChange=change*amounts.shortLeverage/PRECISION;
int256 liquidityPoolChange = change*amounts.liquidityPoolLeverage/PRECISION;
for (uint256 i=0;i<pools.length;i++) {
Pool storage pool = pools[i];
if (pool.isLiquidityPool) {
pool.collateral+= (pool.collateral*pool.leverage*liquidityPoolChange/PRECISION);
} else if (pool.leverage>0) {
pool.collateral+= (pool.collateral*pool.leverage*longChange/PRECISION);
} else {
pool.collateral+= (pool.collateral*pool.leverage*shortChange/PRECISION);
}
}
if (!lastLoop) { // Change was capped, continue with appliying the rest of the change
prevPrice=prevPrice+prevPrice*change/PRECISION;
}
}
}
{ // Handle the funding and rebalance rates
PoolAmounts memory amounts = _calculatePoolAmounts();
Rates memory rates = getRates(amounts);
for (uint256 i=0;i<pools.length;i++) {
Pool storage pool = pools[i];
if (pool.isLiquidityPool) {
pool.collateral-= (pool.collateral*pool.leverage*rates.liquidityPoolFundingRate*int256(epochPeriod)/(SECONDS_PER_YEAR*PRECISION)) + (pool.collateral*pool.leverage)*rates.rebalanceLiquidityPoolRate*int256(epochPeriod)/(SECONDS_PER_YEAR*PRECISION);
} else if (pool.leverage>0) {
pool.collateral-= (pool.collateral*pool.leverage*rates.longFundingRate*int256(epochPeriod)/(SECONDS_PER_YEAR*PRECISION)) + (pool.collateral*pool.rebalanceMultiplier)*rates.rebalanceRate*int256(epochPeriod)/(SECONDS_PER_YEAR*PRECISION);
} else {
pool.collateral-= (-pool.collateral*pool.leverage*rates.shortFundingRate*int256(epochPeriod)/(SECONDS_PER_YEAR*PRECISION)) + (pool.collateral*pool.rebalanceMultiplier)*rates.rebalanceRate*int256(epochPeriod)/(SECONDS_PER_YEAR*PRECISION);
}
}
}
int256 sumFees=0;
{ // Do the deposits/withdrawels
PoolAmounts memory amounts = _calculatePoolAmounts();
for (uint256 i=0;i<pools.length;i++) {
Pool storage pool = pools[i];
PoolEpochData storage data = poolEpochData[epoch][i];
int256 actualLeverage;
if (pool.isLiquidityPool) {
actualLeverage = pool.leverage*amounts.liquidityPoolLeverage/PRECISION;
if (actualLeverage<0) actualLeverage=-actualLeverage;
} else if (pool.leverage>0) {
actualLeverage = pool.leverage*amounts.longLeverage/PRECISION;
} else {
actualLeverage = -pool.leverage*amounts.shortLeverage/PRECISION;
}
int256 depositAmount = data.deposits;
if (depositAmount>0) {
// Fee is relative to actual leverage
int256 fees = depositAmount*TRANSACTION_FEE*actualLeverage/PRECISION;
if (pool.shares>0) data.sharesPerCollateralDeposit=(pool.shares*PRECISION/pool.collateral)*(depositAmount-fees)/depositAmount;
else data.sharesPerCollateralDeposit = PRECISION*(depositAmount-fees)/depositAmount;
pool.shares+=depositAmount*data.sharesPerCollateralDeposit/PRECISION;
pool.collateral+=depositAmount-fees;
sumFees+=fees;
}
int256 withdrawAmount = data.withdrawals;
if (withdrawAmount>0) {
// Fee is relative to actual leverage
int256 fees = withdrawAmount*TRANSACTION_FEE*actualLeverage/PRECISION;
int256 collateralPerShare = pool.collateral*PRECISION/pool.shares;
data.collateralPerShareWithdraw=collateralPerShare*(withdrawAmount-fees)/withdrawAmount;
pool.shares-=withdrawAmount;
pool.collateral-=withdrawAmount*collateralPerShare/PRECISION;
sumFees+=fees;
}
}
}
{ // Distribute the fees among the liquidity pools and the admin
PoolAmounts memory amounts = _calculatePoolAmounts();
if (amounts.liquidityPoolAmount>0) {
adminFees+=sumFees*ADMIN_FEES/PRECISION;
int256 liquidityPoolFees=sumFees*LIQUIDITYPOOL_FEES/PRECISION;
for (uint256 i=0;i<pools.length;i++) {
Pool storage pool = pools[i];
if (pool.isLiquidityPool) {
pool.collateral+=liquidityPoolFees*pool.collateral*pool.leverage/amounts.liquidityPoolAmount;
}
}
} else {
adminFees+=sumFees;
}
}
// Emit logs (removed, costing too much gas)
/*for (uint256 i=0;i<pools.length;i++) {
Pool storage pool = pools[i];
PoolEpochData storage data = poolEpochData[epoch][i];
emit EpochPool(epoch,i,pool.shares,pool.collateral,data.sharesPerCollateralDeposit,data.collateralPerShareWithdraw);
}*/
}
}
/**
* Add a new Pool
**/
function _addPool(int256 leverage,bool isLiquidityPool) internal {
require (msg.sender==admin,"Only admin");
require (leverage!=0,"Leverage can not be zero");
require (!isLiquidityPool || leverage>0,"Liquidity pool leverage must be positive");
for (uint256 i=0;i<pools.length;i++) {
require (leverage!=pools[i].leverage || isLiquidityPool!=pools[i].isLiquidityPool,"Pool already exists");
}
Pool memory pool;
pool.leverage = leverage;
pool.isLiquidityPool = isLiquidityPool;
if (!isLiquidityPool) pool.rebalanceMultiplier = (leverage*leverage - leverage)/2;
pools.push(pool);
emit AddPool(leverage,isLiquidityPool);
}
/* ========== INTERNAL VIEWS ========== */
/**
* Calculate the total amounts over all pools and the leverage for longs/shorts/liquidity pool
**/
function _calculatePoolAmounts() internal view returns (PoolAmounts memory amounts) {
for (uint256 i=0;i<pools.length;i++) {
Pool storage pool = pools[i];
if (pool.isLiquidityPool) {
amounts.liquidityPoolAmount+= pool.collateral*pool.leverage;
} else if (pool.leverage>0) {
amounts.longAmount+= pool.collateral*pool.leverage;
amounts.rebalanceAmount+= pool.collateral*pool.rebalanceMultiplier;
} else {
amounts.shortAmount-= pool.collateral*pool.leverage;
amounts.rebalanceAmount+= pool.collateral*pool.rebalanceMultiplier;
}
}
if (amounts.longAmount>amounts.shortAmount) {
int256 missingAmount=amounts.longAmount-amounts.shortAmount;
if (missingAmount<amounts.liquidityPoolAmount) {
if (missingAmount>0) amounts.liquidityPoolLeverage = -missingAmount*PRECISION/amounts.liquidityPoolAmount;
amounts.longLeverage = amounts.shortLeverage = PRECISION;
} else {
if (amounts.longAmount>0) amounts.longLeverage = (amounts.shortAmount+amounts.liquidityPoolAmount)*PRECISION/amounts.longAmount;
else amounts.longLeverage = PRECISION;
amounts.shortLeverage = PRECISION;
amounts.liquidityPoolLeverage = -PRECISION;
}
} else {
int256 missingAmount=amounts.shortAmount-amounts.longAmount;
if (missingAmount<amounts.liquidityPoolAmount) {
if (missingAmount>0) {
amounts.liquidityPoolLeverage = missingAmount*PRECISION/amounts.liquidityPoolAmount;
}
amounts.longLeverage = amounts.shortLeverage = PRECISION;
} else {
if (amounts.shortAmount>0) amounts.shortLeverage = (amounts.longAmount+amounts.liquidityPoolAmount)*PRECISION/amounts.shortAmount;
else amounts.shortLeverage = PRECISION;
amounts.longLeverage = amounts.liquidityPoolLeverage = PRECISION;
}
}
}
/**
* Determine the next epoch a user can deposit/withdraw in
**/
function _getNextEpoch() view internal returns (uint256 nextEpoch) {
if (block.timestamp>=epochStartTime+epochPeriod-waitPeriod) nextEpoch = epoch+2;
else nextEpoch = epoch+1;
}
/**
* Get the price from the oracle
**/
function getPrice() internal view returns (uint256 _price) {
if (address(oracle)!=address(0)) _price = oracle.getPrice();
else _price = block.timestamp; //for testing
}
/**
* Get all the rates from the funding rate model
**/
function getRates(PoolAmounts memory amounts) internal view returns (Rates memory rates) {
if (address(fundingRateModel)!=address(0x0)) {
(rates.longFundingRate,rates.shortFundingRate,rates.liquidityPoolFundingRate,rates.rebalanceRate,rates.rebalanceLiquidityPoolRate) = fundingRateModel.getFundingRate(amounts.longAmount,amounts.shortAmount,amounts.liquidityPoolAmount,amounts.rebalanceAmount);
}
}
event DepositInPool(address adr,int256 amount,uint256 poolNo,uint256 epoch);
event WithdrawFromPool(address adr,int256 amount,uint256 poolNo,uint256 epoch);
event Epoch(uint256 epoch,int256 price);
event EpochPool(uint256 epoch,uint256 pool,int256 shares,int256 collateral,int256 sharesPerCollateralDeposit,int256 collateralPerShareWithdraw);
event AddPool(int256 leverage,bool isLiquidityPool);
event SetFees(int256 TRANSACTION_FEE, int256 ADMIN_FEES, int256 LIQUIDITYPOOL_FEES);
event SetEpochPeriods(uint256 epochPeriod, uint256 waitPeriod);
}
interface IOracle {
function getPrice() external view returns (uint256);
}
contract TestOracle is IOracle {
address admin;
uint256 price=10**18;
constructor() {
admin = msg.sender;
}
function getPrice() override external view returns (uint256) {
return price;
}
function setPrice(uint256 _price) external {
require(admin==msg.sender,"Only admin");
price = _price;
}
}
interface IFundingRateModel {
function getFundingRate(int256 _longAmount,int256 _shortAmount,int256 _liquidityPoolAmount,int256 _rebalanceAmount) external view returns (int256,int256,int256,int256,int256);
}
contract BaseInterestRateModel is IFundingRateModel {
address admin;
int256 public constant PRECISION = 10**18;
int256 public FUNDING_MULTIPLIER = PRECISION;
int256 public REBALANCING_MULTIPLIER = PRECISION;
int256 public MAX_REBALANCE_RATE = 10**18;
constructor() {
admin = msg.sender;
}
function setMultipliers(int256 _FUNDING_MULTIPLIER, int256 _REBALANCING_MULTIPLIER) external {
require(admin==msg.sender,"Only admin");
FUNDING_MULTIPLIER=_FUNDING_MULTIPLIER;
REBALANCING_MULTIPLIER = _REBALANCING_MULTIPLIER;
}
function setMaxRebalanceRate(int256 _MAX_REBALANCE_RATE) external {
require(admin==msg.sender,"Only admin");
MAX_REBALANCE_RATE =_MAX_REBALANCE_RATE;
}
function getFundingRate(int256 _longAmount,int256 _shortAmount,int256 _liquidityPoolAmount,int256 _rebalanceAmount) override external view returns (int256 longFundingRate,int256 shortFundingRate,int256 liquidityPoolFundingRate,int256 rebalanceRate,int256 rebalanceLiquidityPoolRate) {
if (_shortAmount>0 && _longAmount>_shortAmount) { // longs pay shorts
longFundingRate = ((_longAmount-_shortAmount)*PRECISION/_longAmount)*FUNDING_MULTIPLIER/PRECISION;
int256 missingAmount = _longAmount-_shortAmount;
if (missingAmount>_liquidityPoolAmount) {
shortFundingRate = liquidityPoolFundingRate = -longFundingRate*_longAmount/(_shortAmount+_liquidityPoolAmount);
} else {
shortFundingRate = -longFundingRate;
if (_liquidityPoolAmount>0) liquidityPoolFundingRate = shortFundingRate*missingAmount/_liquidityPoolAmount;
}
} else if (_longAmount>0 && _shortAmount>_longAmount) { // Shorts pay longs
shortFundingRate = ((_shortAmount-_longAmount)*PRECISION/_shortAmount)*FUNDING_MULTIPLIER/PRECISION;
int256 missingAmount = _shortAmount-_longAmount;
if (missingAmount>_liquidityPoolAmount) {
longFundingRate = liquidityPoolFundingRate = -shortFundingRate*_shortAmount/(_longAmount+_liquidityPoolAmount);
} else {
longFundingRate = -shortFundingRate;
if (_liquidityPoolAmount>0) liquidityPoolFundingRate = longFundingRate*missingAmount/_liquidityPoolAmount;
}
}
if (_liquidityPoolAmount>0) { // calculate the rebalancing rates
rebalanceRate = (_rebalanceAmount*REBALANCING_MULTIPLIER/_liquidityPoolAmount);
if (_rebalanceAmount>0) {
if (rebalanceRate>MAX_REBALANCE_RATE) rebalanceRate=MAX_REBALANCE_RATE;
rebalanceLiquidityPoolRate = -rebalanceRate*_rebalanceAmount/_liquidityPoolAmount;
}
}
}
}
|
* Do the bookkeeping for the current user, by applying the deposits and withdrawels of all epochs that have past./
|
function _bookKeeping(address user) internal {
UserInfo storage info = userInfo[user];
while (info.index<info.actions.length) {
Action storage action = info.actions[info.index];
if (action.epoch<=epoch) {
PoolEpochData storage data = poolEpochData[action.epoch][action.pool];
if (action.depositAmount>0) {
int256 newShares = (action.depositAmount*data.sharesPerCollateralDeposit/PRECISION);
info.shares[action.pool]+=newShares;
int256 withdrawn = (action.withdrawAmount*data.collateralPerShareWithdraw/PRECISION);
info.withdrawableCollateral+=withdrawn;
}
delete info.actions[info.index];
info.index++;
} else break;
}
}
| 1,069,293 |
[
1,
3244,
326,
6978,
10102,
310,
364,
326,
783,
729,
16,
635,
13650,
326,
443,
917,
1282,
471,
598,
9446,
10558,
434,
777,
25480,
716,
1240,
8854,
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,
389,
3618,
11523,
310,
12,
2867,
729,
13,
2713,
288,
203,
3639,
25003,
2502,
1123,
273,
16753,
63,
1355,
15533,
203,
3639,
1323,
261,
1376,
18,
1615,
32,
1376,
18,
4905,
18,
2469,
13,
288,
203,
5411,
4382,
2502,
1301,
273,
1123,
18,
4905,
63,
1376,
18,
1615,
15533,
203,
5411,
309,
261,
1128,
18,
12015,
32,
33,
12015,
13,
288,
203,
7734,
8828,
14638,
751,
2502,
501,
273,
2845,
14638,
751,
63,
1128,
18,
12015,
6362,
1128,
18,
6011,
15533,
203,
7734,
309,
261,
1128,
18,
323,
1724,
6275,
34,
20,
13,
288,
203,
10792,
509,
5034,
394,
24051,
273,
261,
1128,
18,
323,
1724,
6275,
14,
892,
18,
30720,
2173,
13535,
2045,
287,
758,
1724,
19,
3670,
26913,
1769,
203,
10792,
1123,
18,
30720,
63,
1128,
18,
6011,
3737,
33,
2704,
24051,
31,
203,
10792,
509,
5034,
598,
9446,
82,
273,
261,
1128,
18,
1918,
9446,
6275,
14,
892,
18,
12910,
2045,
287,
2173,
9535,
1190,
9446,
19,
3670,
26913,
1769,
203,
10792,
1123,
18,
1918,
9446,
429,
13535,
2045,
287,
15,
33,
1918,
9446,
82,
31,
203,
7734,
289,
203,
7734,
1430,
1123,
18,
4905,
63,
1376,
18,
1615,
15533,
203,
7734,
1123,
18,
1615,
9904,
31,
203,
5411,
289,
469,
898,
31,
203,
3639,
289,
203,
565,
289,
203,
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
] |
pragma solidity 0.8.0;
// SPDX-License-Identifier: MIT
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./interfaces/ILiquidityProvider.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
interface IMigrator {
// Perform LP token migration from legacy UniswapV2 to TacoSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// TacoSwap must mint EXACTLY the same amount of TacoSwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrateLP(IERC20 token) external returns (IERC20);
}
/**
* @title eTacoChef is the master of eTaco
* @notice eTacoChef contract:
* - Users can:
* # Deposit
* # Harvest
* # Withdraw
* # SpeedStake
*/
contract eTacoChef is OwnableUpgradeable, ReentrancyGuardUpgradeable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @notice Info of each user
* @param amount: How many LP tokens the user has provided
* @param rewardDebt: Reward debt. See explanation below
* @dev Any point in time, the amount of eTacos entitled to a user but is pending to be distributed is:
* pending reward = (user.amount * pool.accRewardPerShare) - user.rewardDebt
* Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
* 1. The pool's `accRewardPerShare` (and `lastRewardBlock`) gets updated.
* 2. User receives the pending reward sent to his/her address.
* 3. User's `amount` gets updated.
* 4. User's `rewardDebt` gets updated.
*/
struct UserInfo {
uint256 amount;
uint256 rewardDebt;
}
/**
* @notice Info of each pool
* @param lpToken: Address of LP token contract
* @param allocPoint: How many allocation points assigned to this pool. eTacos to distribute per block
* @param lastRewardBlock: Last block number that eTacos distribution occurs
* @param accRewardPerShare: Accumulated eTacos per share, times 1e12. See below
*/
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. eTacos to distribute per block.
uint256 lastRewardBlock; // Last block number that eTacos distribution occurs.
uint256 accRewardPerShare; // Accumulated eTacos per share, times 1e12. See below.
}
/// The eTaco TOKEN!
IERC20 public etaco;
/// Dev address.
address public devaddr;
/// The Liquidity Provider
ILiquidityProvider public provider;
/// Block number when bonus eTaco period ends.
uint256 public endBlock;
/// eTaco tokens created in first block.
uint256 public rewardPerBlock;
/// The migrator contract. Can only be set through governance (owner).
IMigrator public migrator;
/// Info of each pool.
PoolInfo[] public poolInfo;
/// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
mapping(address => bool) public isPoolExist;
/// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
/// The block number when eTaco mining starts.
uint256 public startBlock;
uint256 private _apiID;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event Provider(address oldProvider, address newProvider);
event Api(uint256 id);
event Migrator(address migratorAddress);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
uint256 amount
);
modifier poolExists(uint256 _pid) {
require(_pid < poolInfo.length, "Pool does not exist");
_;
}
modifier onlyMigrator() {
require(
msg.sender == address(migrator),
"eTacoChef: Only migrator can call"
);
_;
}
function initialize(
IERC20 _etaco,
uint256 _rewardPerBlock,
uint256 _startBlock
) public initializer {
__Ownable_init();
__ReentrancyGuard_init();
require(address(_etaco) != address(0x0), "eTacoChef::set zero address");
etaco = _etaco;
devaddr = msg.sender;
rewardPerBlock = _rewardPerBlock;
startBlock = _startBlock;
}
/// @return All pools amount
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
/**
* @notice Add a new lp to the pool. Can only be called by the owner
* @param _allocPoint: allocPoint for new pool
* @param _lpToken: address of lpToken for new pool
* @param _withUpdate: if true, update all pools
*/
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
require(
!isPoolExist[address(_lpToken)],
"eTacoChef:: LP token already added"
);
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock
? block.number
: startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accRewardPerShare: 0
})
);
isPoolExist[address(_lpToken)] = true;
}
/**
* @notice Update the given pool's eTaco allocation point. Can only be called by the owner
*/
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner poolExists(_pid) {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
/**
* @notice Set the migrator contract. Can only be called by the owner
* @param _migrator: migrator contract
*/
function setMigrator(IMigrator _migrator) external onlyOwner {
migrator = _migrator;
emit Migrator(address(_migrator));
}
function setProviderConfigs(ILiquidityProvider _provider, uint256 _api)
external
onlyOwner
{
provider = _provider;
_apiID = _api;
}
function setStartBlock(uint256 _startBlock) external onlyOwner {
startBlock = _startBlock;
}
function setRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner {
massUpdatePools();
rewardPerBlock = _rewardPerBlock;
}
function setPoolLPToken(uint256 _pid, address _lpToken) external onlyOwner {
require(!isPoolExist[_lpToken], "eTacoChef:: LP token already added");
poolInfo[_pid].lpToken = IERC20(_lpToken);
isPoolExist[_lpToken] = true;
isPoolExist[address(poolInfo[_pid].lpToken)] = false;
}
/**
* @notice Migrate lp token to another lp contract. Can be called by anyone
* @param _pid: ID of pool which message sender wants to migrate
*/
function migrate(uint256 _pid) public onlyOwner {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrateLP(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
/**
* @param _from: block number from which the reward is calculated
* @param _to: block number before which the reward is calculated
* @return Return reward multiplier over the given _from to _to block
*/
function getMultiplier(uint256 _from, uint256 _to)
public
view
returns (uint256)
{
if (_from < startBlock) {
_from = startBlock;
}
return rewardPerBlock.mul(_to.sub(_from));
}
/**
* @notice View function to see pending eTacos on frontend
* @param _pid: pool ID for which reward must be calculated
* @param _user: user address for which reward must be calculated
* @return Return reward for user
*/
function pendingReward(uint256 _pid, address _user)
external
view
poolExists(_pid)
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accRewardPerShare = pool.accRewardPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(
pool.lastRewardBlock,
block.number
);
uint256 etacoReward = multiplier.mul(pool.allocPoint).div(
totalAllocPoint
);
accRewardPerShare = accRewardPerShare.add(
etacoReward.mul(1e12).div(lpSupply)
);
}
return
user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt);
}
/**
* @notice Update reward vairables for all pools
*/
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
/**
* @notice Update reward variables of the given pool to be up-to-date
* @param _pid: pool ID for which the reward variables should be updated
*/
function updatePool(uint256 _pid) public poolExists(_pid) {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 etacoReward = multiplier.mul(pool.allocPoint).div(
totalAllocPoint
);
safeETacoTransfer(devaddr, etacoReward.div(10));
pool.accRewardPerShare = pool.accRewardPerShare.add(
etacoReward.mul(1e12).div(lpSupply)
);
pool.lastRewardBlock = block.number;
}
/**
* @notice Function for updating user info
*/
function _deposit(uint256 _pid, uint256 _amount) private {
UserInfo storage user = userInfo[_pid][msg.sender];
harvest(_pid);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(poolInfo[_pid].accRewardPerShare).div(
1e12
);
emit Deposit(msg.sender, _pid, _amount);
}
/**
* @notice Deposit LP tokens to eTacoChef for eTaco allocation
* @param _pid: pool ID on which LP tokens should be deposited
* @param _amount: the amount of LP tokens that should be deposited
*/
function deposit(uint256 _pid, uint256 _amount) public poolExists(_pid) {
updatePool(_pid);
poolInfo[_pid].lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
_deposit(_pid, _amount);
}
/**
* @notice Function which send accumulated eTaco tokens to messege sender
* @param _pid: pool ID from which the accumulated eTaco tokens should be received
*/
function harvest(uint256 _pid) public poolExists(_pid) {
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
updatePool(_pid);
uint256 accRewardPerShare = poolInfo[_pid].accRewardPerShare;
uint256 pending = user.amount.mul(accRewardPerShare).div(1e12).sub(
user.rewardDebt
);
safeETacoTransfer(msg.sender, pending);
user.rewardDebt = user.amount.mul(accRewardPerShare).div(1e12);
emit Harvest(msg.sender, _pid, pending);
}
}
/**
* @notice Function which send accumulated eTaco tokens to messege sender from all pools
*/
function harvestAll() public {
uint256 length = poolInfo.length;
for (uint256 i = 0; i < length; i++) {
if (poolInfo[i].allocPoint > 0) {
harvest(i);
}
}
}
/**
* @notice Function which withdraw LP tokens to messege sender with the given amount
* @param _pid: pool ID from which the LP tokens should be withdrawn
* @param _amount: the amount of LP tokens that should be withdrawn
*/
function withdraw(uint256 _pid, uint256 _amount) public poolExists(_pid) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accRewardPerShare).div(1e12).sub(
user.rewardDebt
);
safeETacoTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
/**
* @notice Function which transfer eTaco tokens to _to with the given amount
* @param _to: transfer reciver address
* @param _amount: amount of eTaco token which should be transfer
*/
function safeETacoTransfer(address _to, uint256 _amount) internal {
if (_amount > 0) {
uint256 etacoBal = etaco.balanceOf(address(this));
if (_amount > etacoBal) {
etaco.transfer(_to, etacoBal);
} else {
etaco.transfer(_to, _amount);
}
}
}
/**
* @notice Function which take ETH, add liquidity with provider and deposit given LP's
* @param _pid: pool ID where we want deposit
* @param _amountAMin: bounds the extent to which the B/A price can go up before the transaction reverts.
Must be <= amountADesired.
* @param _amountBMin: bounds the extent to which the A/B price can go up before the transaction reverts.
Must be <= amountBDesired
* @param _minAmountOutA: the minimum amount of output A tokens that must be received
for the transaction not to revert
* @param _minAmountOutB: the minimum amount of output B tokens that must be received
for the transaction not to revert
*/
function speedStake(
uint256 _pid,
uint256 _amountAMin,
uint256 _amountBMin,
uint256 _minAmountOutA,
uint256 _minAmountOutB,
uint256 _deadline
) public payable poolExists(_pid) {
(address routerAddr, , ) = provider.apis(_apiID);
IUniswapV2Router02 router = IUniswapV2Router02(routerAddr);
delete routerAddr;
require(
address(router) != address(0),
"MasterChef: Exchange does not set yet"
);
PoolInfo storage pool = poolInfo[_pid];
uint256 lp;
updatePool(_pid);
IUniswapV2Pair lpToken = IUniswapV2Pair(address(pool.lpToken));
if (
(lpToken.token0() == router.WETH()) ||
((lpToken.token1() == router.WETH()))
) {
lp = provider.addLiquidityETHByPair{value: msg.value}(
lpToken,
address(this),
_amountAMin,
_amountBMin,
_minAmountOutA,
_deadline,
_apiID
);
} else {
lp = provider.addLiquidityByPair{value: msg.value}(
lpToken,
_amountAMin,
_amountBMin,
_minAmountOutA,
_minAmountOutB,
address(this),
_deadline,
_apiID
);
}
_deposit(_pid, lp);
}
/**
* @notice Function which migrate pool to eTacoChef. Can only be called by the migrator
*/
function setPool(
uint256 _pid,
IERC20 _lpToken,
uint256 _allocPoint,
uint256 _lastRewardBlock,
uint256 _accRewardPerShare
) external onlyMigrator {
if (poolInfo.length <= _pid) {
poolInfo.push(
PoolInfo(
IERC20(_lpToken),
_allocPoint,
_lastRewardBlock,
_accRewardPerShare
)
);
} else {
totalAllocPoint -= poolInfo[_pid].allocPoint;
poolInfo[_pid] = PoolInfo(
IERC20(_lpToken),
_allocPoint,
_lastRewardBlock,
_accRewardPerShare
);
totalAllocPoint += _allocPoint;
}
}
/**
* @notice Function which migrate user to eTacoChef
*/
function setUser(
uint256 _pid,
address _user,
uint256 _amount,
uint256 _rewardDebt
) external onlyMigrator {
require(poolInfo.length != 0, "eTacoChef: Pools must be migrated");
updatePool(_pid);
userInfo[_pid][_user] = UserInfo(_amount, _rewardDebt.mul(9).div(10));
}
function approveDummies(address _token) external onlyMigrator {
IERC20(_token).safeApprove(msg.sender, type(uint256).max);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
pragma solidity >=0.6.12 <0.9.0;
// SPDX-License-Identifier: UNLICENSED
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
interface ILiquidityProvider {
function apis(uint256) external view returns(address, address, address);
function addExchange(IUniswapV2Router02) external;
function addLiquidityETH(
address,
address,
uint256,
uint256,
uint256,
uint256,
uint256
) external payable returns (uint256);
function addLiquidityETHByPair(
IUniswapV2Pair,
address,
uint256,
uint256,
uint256,
uint256,
uint256
) external payable returns (uint256);
function addLiquidity(
address,
address,
uint256,
uint256,
uint256,
uint256,
address,
uint256,
uint256
) external payable returns (uint256);
function addLiquidityByPair(
IUniswapV2Pair,
uint256,
uint256,
uint256,
uint256,
address,
uint256,
uint256
) external payable returns (uint256);
function removeLiquidityETH(
address,
uint256,
uint256,
uint256,
uint256,
address,
uint256,
uint256,
uint8
) external returns (uint256[3] memory);
function removeLiquidityETHByPair(
IUniswapV2Pair,
uint256,
uint256,
uint256,
uint256,
address,
uint256,
uint256,
uint8
) external returns (uint256[3] memory);
function removeLiquidityETHWithPermit(
address,
uint256,
uint256,
uint256,
uint256,
address,
uint256,
uint256,
uint8,
uint8,
bytes32,
bytes32
) external returns (uint256[3] memory);
function removeLiquidity(
address,
address,
uint256,
uint256[2] memory,
uint256[2] memory,
address,
uint256,
uint256,
uint8
) external returns (uint256[3] memory);
function removeLiquidityByPair(
IUniswapV2Pair,
uint256,
uint256[2] memory,
uint256[2] memory,
address,
uint256,
uint256,
uint8
) external returns (uint256[3] memory);
function removeLiquidityWithPermit(
address,
address,
uint256,
uint256[2] memory,
uint256[2] memory,
address,
uint256,
uint256,
uint8,
uint8,
bytes32,
bytes32
) external returns (uint256[3] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
|
* @notice Update the given pool's eTaco allocation point. Can only be called by the owner/
|
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner poolExists(_pid) {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
| 1,696,164 |
[
1,
1891,
326,
864,
2845,
1807,
425,
56,
24363,
13481,
1634,
18,
4480,
1338,
506,
2566,
635,
326,
3410,
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
] |
[
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,
445,
444,
12,
203,
3639,
2254,
5034,
389,
6610,
16,
203,
3639,
2254,
5034,
389,
9853,
2148,
16,
203,
3639,
1426,
389,
1918,
1891,
203,
565,
262,
1071,
1338,
5541,
2845,
4002,
24899,
6610,
13,
288,
203,
3639,
309,
261,
67,
1918,
1891,
13,
288,
203,
5411,
8039,
1891,
16639,
5621,
203,
3639,
289,
203,
3639,
2078,
8763,
2148,
273,
2078,
8763,
2148,
18,
1717,
12,
6011,
966,
63,
67,
6610,
8009,
9853,
2148,
2934,
1289,
12,
203,
5411,
389,
9853,
2148,
203,
3639,
11272,
203,
3639,
2845,
966,
63,
67,
6610,
8009,
9853,
2148,
273,
389,
9853,
2148,
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
] |
// SPDX-License-Identifier: GPL-3.0-or-later
// Sources flattened with hardhat v2.9.3 https://hardhat.org
// File interfaces/tokenomics/IMultiplier.sol
pragma solidity ^0.8.13;
interface IMultiplier {
function getMultiplier() external view returns (uint256);
}
// File interfaces/tokenomics/IInflationManager.sol
pragma solidity ^0.8.13;
interface IInflationManager {
event TokensClaimed(address indexed pool, uint256 crvAmount, uint256 cncAmount);
/// @notice allows anyone to claim the CNC tokens for a given pool
function claimPoolRewards(address pool) external;
function multiplier() external view returns (IMultiplier);
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/token/ERC20/extensions/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File interfaces/pools/ILpToken.sol
pragma solidity ^0.8.13;
interface ILpToken is IERC20Metadata {
function mint(address account, uint256 amount) external returns (uint256);
function burn(address _owner, uint256 _amount) external returns (uint256);
}
// File interfaces/pools/IRewardManager.sol
pragma solidity ^0.8.13;
interface IRewardManager {
event ClaimedRewards(uint256 claimedCrv, uint256 claimedCvx);
struct RewardMeta {
uint256 earnedIntegral;
uint256 lastEarned;
mapping(address => uint256) accountIntegral;
mapping(address => uint256) accountShare;
}
function accountCheckpoint(address account) external;
function poolCheckpoint() external;
function addExtraReward(address reward) external returns (bool);
function addBatchExtraRewards(address[] memory rewards) external;
function totalCRVClaimed() external view returns (uint256);
function getClaimableRewards(address account)
external
view
returns (
uint256 cncRewards,
uint256 crvRewards,
uint256 cvxRewards
);
function claimEarnings() external returns (uint256);
function claimPoolEarnings() external;
}
// File interfaces/pools/IConicPool.sol
pragma solidity ^0.8.13;
interface IConicPool {
event Deposit(address account, uint256 amount);
event DepositToCurve(uint256 amunt);
event Withdraw(address account, uint256 amount);
event NewWeight(address indexed curvePool, uint256 newWeight);
event NewMaxIdleRatio(uint256 newRatio);
event TotalUnderlyingUpdated(uint256 oldTotalUnderlying, uint256 newTotalUnderlying);
event ClaimedRewards(uint256 claimedCrv, uint256 claimedCvx);
struct PoolWeight {
address poolAddress;
uint256 weight;
}
function underlying() external view returns (IERC20);
function lpToken() external view returns (ILpToken);
function rewardManager() external view returns (IRewardManager);
function depositFor(address _account, uint256 _amount) external;
function deposit(uint256 _amount) external;
function updateTotalUnderlying() external;
function rebalance() external;
function exchangeRate() external view returns (uint256);
function allCurvePools() external view returns (address[] memory);
function withdraw(uint256 _amount, uint256 _minAmount) external returns (uint256);
function updateWeights(PoolWeight[] memory poolWeights) external;
function getWeights() external view returns (PoolWeight[] memory);
function getAllocatedUnderlying() external view returns (PoolWeight[] memory);
function renewPenaltyDelay(address account) external;
}
// File interfaces/IController.sol
pragma solidity ^0.8.13;
interface IController {
event PoolAdded(address indexed pool);
event PoolRemoved(address indexed pool);
event NewCurvePoolVerifier(address indexed curvePoolVerifier);
struct WeightUpdate {
address conicPoolAddress;
IConicPool.PoolWeight[] weights;
}
function inflationManager() external view returns (address);
function setInflationManager(address manager) external;
// pool functions
function listPools() external view returns (address[] memory);
function isPool(address poolAddress) external view returns (bool);
function addPool(address poolAddress) external;
function removePool(address poolAddress) external;
function cncToken() external view returns (address);
function updateWeights(WeightUpdate memory update) external;
function updateAllWeights(WeightUpdate[] memory weights) external;
// handler functions
function convexBooster() external view returns (address);
function curveHandler() external view returns (address);
function convexHandler() external view returns (address);
function curvePoolVerifier() external view returns (address);
function setConvexBooster(address _convexBooster) external;
function setCurveHandler(address _curveHandler) external;
function setConvexHandler(address _convexHandler) external;
function setCurvePoolVerifier(address _curvePoolVerifier) external;
}
// File interfaces/tokenomics/ICNCToken.sol
pragma solidity ^0.8.13;
interface ICNCToken is IERC20 {
event MinterAdded(address minter);
event MinterRemoved(address minter);
event InitialDistributionMinted(uint256 amount);
event AirdropMinted(uint256 amount);
event AMMRewardsMinted(uint256 amount);
event TreasuryRewardsMinted(uint256 amount);
event SeedShareMinted(uint256 amount);
/// @notice mints the initial distribution amount to the distribution contract
function mintInitialDistribution(address distribution) external;
/// @notice mints the airdrop amount to the airdrop contract
function mintAirdrop(address airdropHandler) external;
/// @notice mints the amm rewards
function mintAMMRewards(address ammGauge) external;
/// @notice mints `amount` to `account`
function mint(address account, uint256 amount) external returns (uint256);
/// @notice returns a list of all authorized minters
function listMinters() external view returns (address[] memory);
/// @notice returns the ratio of inflation already minted
function inflationMintedRatio() external view returns (uint256);
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File libraries/ScaledMath.sol
pragma solidity ^0.8.13;
library ScaledMath {
uint256 internal constant DECIMALS = 18;
uint256 internal constant ONE = 10**DECIMALS;
function mulDown(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * b) / ONE;
}
function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * ONE) / b;
}
}
// File contracts/tokenomics/InflationManager.sol
pragma solidity ^0.8.13;
contract InflationManager is IInflationManager, Ownable {
using ScaledMath for uint256;
IController public controller;
ICNCToken public immutable cncToken;
IMultiplier public multiplier;
/// @dev mapping from pool address to the total amount of CRV tokens that the pool has claimed
mapping(address => uint256) internal _poolCRVClaimed;
constructor(address _cncToken) Ownable() {
cncToken = ICNCToken(_cncToken);
}
function initialize(address _multiplier, IController _controller) external onlyOwner {
require(address(multiplier) == address(0), "Multiplier already set");
require(_multiplier != address(0), "Cannot use zero address for multiplier");
require(address(_controller) != address(0), "Cannot use zero address for controller");
multiplier = IMultiplier(_multiplier);
controller = _controller;
}
/// @inheritdoc IInflationManager
/// @dev the pool needs to be registered in the address provider
function claimPoolRewards(address pool) external {
require(controller.isPool(pool), "not a pool");
require(address(multiplier) != address(0), "Multiplier not set");
uint256 previousCRVClaimed = _poolCRVClaimed[pool];
IRewardManager rewardManager = IConicPool(pool).rewardManager();
uint256 totalCRVClaimed = rewardManager.totalCRVClaimed();
uint256 claimedCRVDelta = totalCRVClaimed - previousCRVClaimed;
if (claimedCRVDelta == 0) return;
uint256 currentMultiplier = multiplier.getMultiplier();
uint256 cncToMint = claimedCRVDelta.mulDown(currentMultiplier);
cncToken.mint(address(rewardManager), cncToMint);
_poolCRVClaimed[pool] = totalCRVClaimed;
emit TokensClaimed(pool, claimedCRVDelta, cncToMint);
}
}
|
@inheritdoc IInflationManager @dev the pool needs to be registered in the address provider
|
function claimPoolRewards(address pool) external {
require(controller.isPool(pool), "not a pool");
require(address(multiplier) != address(0), "Multiplier not set");
uint256 previousCRVClaimed = _poolCRVClaimed[pool];
IRewardManager rewardManager = IConicPool(pool).rewardManager();
uint256 totalCRVClaimed = rewardManager.totalCRVClaimed();
uint256 claimedCRVDelta = totalCRVClaimed - previousCRVClaimed;
if (claimedCRVDelta == 0) return;
uint256 currentMultiplier = multiplier.getMultiplier();
uint256 cncToMint = claimedCRVDelta.mulDown(currentMultiplier);
cncToken.mint(address(rewardManager), cncToMint);
_poolCRVClaimed[pool] = totalCRVClaimed;
emit TokensClaimed(pool, claimedCRVDelta, cncToMint);
}
| 98,399 |
[
1,
36,
10093,
467,
27040,
367,
1318,
225,
326,
2845,
4260,
358,
506,
4104,
316,
326,
1758,
2893,
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,
7516,
2864,
17631,
14727,
12,
2867,
2845,
13,
3903,
288,
203,
3639,
2583,
12,
5723,
18,
291,
2864,
12,
6011,
3631,
315,
902,
279,
2845,
8863,
203,
3639,
2583,
12,
2867,
12,
20538,
13,
480,
1758,
12,
20,
3631,
315,
23365,
486,
444,
8863,
203,
203,
3639,
2254,
5034,
2416,
5093,
58,
9762,
329,
273,
389,
6011,
5093,
58,
9762,
329,
63,
6011,
15533,
203,
3639,
15908,
359,
1060,
1318,
19890,
1318,
273,
467,
442,
335,
2864,
12,
6011,
2934,
266,
2913,
1318,
5621,
203,
3639,
2254,
5034,
2078,
5093,
58,
9762,
329,
273,
19890,
1318,
18,
4963,
5093,
58,
9762,
329,
5621,
203,
3639,
2254,
5034,
7516,
329,
5093,
58,
9242,
273,
2078,
5093,
58,
9762,
329,
300,
2416,
5093,
58,
9762,
329,
31,
203,
3639,
309,
261,
14784,
329,
5093,
58,
9242,
422,
374,
13,
327,
31,
203,
203,
3639,
2254,
5034,
783,
23365,
273,
15027,
18,
588,
23365,
5621,
203,
3639,
2254,
5034,
6227,
71,
774,
49,
474,
273,
7516,
329,
5093,
58,
9242,
18,
16411,
4164,
12,
2972,
23365,
1769,
203,
3639,
6227,
71,
1345,
18,
81,
474,
12,
2867,
12,
266,
2913,
1318,
3631,
6227,
71,
774,
49,
474,
1769,
203,
203,
3639,
389,
6011,
5093,
58,
9762,
329,
63,
6011,
65,
273,
2078,
5093,
58,
9762,
329,
31,
203,
203,
3639,
3626,
13899,
9762,
329,
12,
6011,
16,
7516,
329,
5093,
58,
9242,
16,
6227,
71,
774,
49,
474,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.23;
import "./CutieERC721Metadata.sol";
import "./ERC721TokenReceiver.sol";
import "./TokenRecipientInterface.sol";
contract BlockchainCutiesToken is CutieERC721Metadata {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
// @dev This struct represents a blockchain Cutie. It was ensured that struct fits well into
// exactly two 256-bit words. The order of the members in this structure
// matters because of the Ethereum byte-packing rules.CutieERC721Metadata
// Reference: http://solidity.readthedocs.io/en/develop/miscellaneous.html
struct Cutie {
// The Cutie's genetic code is in these 256-bits. Cutie's genes never change.
uint256 genes;
// The timestamp from the block when this cutie was created.
uint40 birthTime;
// The minimum timestamp after which the cutie can start breeding
// again.
uint40 cooldownEndTime;
// The cutie's parents ID is set to 0 for gen0 cuties.
uint40 momId;
uint40 dadId;
// Set the index in the cooldown array (see below) that means
// the current cooldown duration for this Cutie. Starts at 0
// for gen0 cats, and is initialized to floor(generation/2) for others.
// Incremented by one for each successful breeding, regardless
// of being cutie mom or cutie dad.
uint16 cooldownIndex;
// The "generation number" of the cutie. Cuties minted by the contract
// for sale are called "gen0" with generation number of 0. All other cuties'
// generation number is the larger of their parents' two generation
// numbers, plus one (i.e. max(mom.generation, dad.generation) + 1)
uint16 generation;
// Some optional data used by external contracts
// Cutie struct is 2x256 bits long.
uint64 optional;
}
bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('tokenURI(uint256)'));
bytes4 internal constant INTERFACE_SIGNATURE_ERC721Enumerable =
bytes4(keccak256('totalSupply()')) ^
bytes4(keccak256('tokenByIndex(uint256)')) ^
bytes4(keccak256('tokenOfOwnerByIndex(address, uint256)'));
// @dev An mapping containing the Cutie struct for all Cuties in existence.
// The ID of each cutie is actually an index into this mapping.
// ID 0 is the parent of all generation 0 cats, and both parents to itself. It is an invalid genetic code.
mapping (uint40 => Cutie) public cuties;
// @dev Total cuties count
uint256 total;
// @dev Core game contract address
address public gameAddress;
// @dev A mapping from cutie IDs to the address that owns them. All cuties have
// some valid owner address, even gen0 cuties are created with a non-zero owner.
mapping (uint40 => address) public cutieIndexToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint256) ownershipTokenCount;
// @dev A mapping from CutieIDs to an address that has been approved to call
// transferFrom(). A Cutie can have one approved address for transfer
// at any time. A zero value means that there is no outstanding approval.
mapping (uint40 => address) public cutieIndexToApproved;
// @dev A mapping from Cuties owner (account) to an address that has been approved to call
// transferFrom() for all cuties, owned by owner.
// Only one approved address is permitted for each account for transfer
// at any time. A zero value means there is no outstanding approval.
mapping (address => mapping (address => bool)) public addressToApprovedAll;
// Modifiers to check that inputs can be safely stored with a certain number of bits
modifier canBeStoredIn40Bits(uint256 _value) {
require(_value <= 0xFFFFFFFFFF, "Value can't be stored in 40 bits");
_;
}
modifier onlyGame {
require(msg.sender == gameAddress || msg.sender == ownerAddress, "Access denied");
_;
}
constructor() public {
// Starts paused.
paused = true;
}
// @dev Accept all Ether
function() external payable {}
function setup(uint256 _total) external onlyGame whenPaused {
require(total == 0, "Contract already initialized");
total = _total;
paused = false;
}
function setGame(address _gameAddress) external onlyOwner {
gameAddress = _gameAddress;
}
// @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 pure returns (bool) {
return
interfaceID == 0x6466353c ||
interfaceID == 0x80ac58cd || // ERC721
interfaceID == INTERFACE_SIGNATURE_ERC721Metadata ||
interfaceID == INTERFACE_SIGNATURE_ERC721Enumerable ||
interfaceID == bytes4(keccak256('supportsInterface(bytes4)'));
}
// @notice Returns the total number of Cuties in existence.
// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint256) {
return total;
}
// @notice Returns the number of Cuties owned by a specific address.
// @param _owner The owner address to check.
// @dev Required for ERC-721 compliance
function balanceOf(address _owner) external view returns (uint256) {
require(_owner != 0x0, "Owner can't be zero address");
return ownershipTokenCount[_owner];
}
// @notice Returns the address currently assigned ownership of a given Cutie.
// @dev Required for ERC-721 compliance.
function ownerOf(uint256 _cutieId) external view canBeStoredIn40Bits(_cutieId) returns (address owner) {
owner = cutieIndexToOwner[uint40(_cutieId)];
require(owner != address(0), "Owner query for nonexistent token");
}
// @notice Returns the address currently assigned ownership of a given Cutie.
// @dev do not revert when cutie has no owner
function ownerOfCutie(uint256 _cutieId) external view canBeStoredIn40Bits(_cutieId) returns (address) {
return cutieIndexToOwner[uint40(_cutieId)];
}
// @notice Enumerate valid NFTs
// @dev Throws if `_index` >= `totalSupply()`.
// @param _index A counter less than `totalSupply()`
// @return The token identifier for the `_index`th NFT,
// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256) {
require(_index < total);
return _index - 1;
}
// @notice Returns the nth Cutie assigned to an address, with n specified by the
// _index argument.
// @param _owner The owner of the Cuties we are interested in.
// @param _index The zero-based index of the cutie within the owner's list of cuties.
// Must be less than balanceOf(_owner).
// @dev This method must not be called by smart contract code. It will almost
// certainly blow past the block gas limit once there are a large number of
// Cuties in existence. Exists only to allow off-chain queries of ownership.
// Optional method for ERC-721.
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 cutieId) {
require(_owner != 0x0, "Owner can't be 0x0");
uint40 count = 0;
for (uint40 i = 1; i <= totalSupply(); ++i) {
if (_isOwner(_owner, i)) {
if (count == _index) {
return i;
} else {
count++;
}
}
}
revert();
}
// @notice Transfers the ownership of an NFT from one address to another address.
// @dev Throws unless `msg.sender` is the current owner, an authorized
// operator, or the approved address for this NFT. Throws if `_from` is
// not the current owner. Throws if `_to` is the zero address. Throws if
// `_tokenId` is not a valid NFT. When transfer is complete, this function
// checks if `_to` is a smart contract (code size > 0). If so, it calls
// `onERC721Received` on `_to` and throws if the return value is not
// `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`.
// @param _from The current owner of the NFT
// @param _to The new owner
// @param _tokenId The NFT to transfer
// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes memory data) public whenNotPaused canBeStoredIn40Bits(_tokenId) {
transferFrom(_from, _to, uint40(_tokenId));
if (_isContract(_to)) {
ERC721TokenReceiver(_to).onERC721Received(_from, _tokenId, data);
}
}
// @notice Transfers the ownership of an NFT from one address to another address
// @dev This works identically to the other function with an extra data parameter,
// except this function just sets data to ""
// @param _from The current owner of the NFT
// @param _to The new owner
// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external whenNotPaused {
safeTransferFrom(_from, _to, _tokenId, "");
}
// @notice Transfer a Cutie owned by another address, for which the calling address
// has been granted transfer approval by the owner.
// @param _from The address that owns the Cutie to be transferred.
// @param _to Any address, including the caller address, can take ownership of the Cutie.
// @param _tokenId The ID of the Cutie to be transferred.
// @dev Required for ERC-721 compliance.
function transferFrom(address _from, address _to, uint256 _tokenId) public whenNotPaused canBeStoredIn40Bits(_tokenId) {
require(_to != address(0), "Wrong cutie destination");
require(_to != address(this), "Wrong cutie destination");
// Check for approval and valid ownership
require(_isApprovedOrOwner(msg.sender, uint40(_tokenId)), "Caller is not owner nor approved");
require(_isOwner(_from, uint40(_tokenId)), "Wrong cutie owner");
// Reassign ownership, clearing pending approvals and emitting Transfer event.
_transfer(_from, _to, uint40(_tokenId));
}
// @notice Transfers a Cutie to another address. When transferring to a smart
// contract, ensure that it is aware of ERC-721 (or BlockchainCuties specifically),
// otherwise the Cutie may be lost forever.
// @param _to The address of the recipient, can be a user or contract.
// @param _cutieId The ID of the Cutie to transfer.
// @dev Required for ERC-721 compliance.
function transfer(address _to, uint256 _cutieId) public whenNotPaused canBeStoredIn40Bits(_cutieId) {
require(_to != address(0), "Wrong cutie destination");
// You can only send your own cutie.
require(_isOwner(msg.sender, uint40(_cutieId)), "Caller is not a cutie owner");
// Reassign ownership, clear pending approvals, emit Transfer event.
_transfer(msg.sender, _to, uint40(_cutieId));
}
function transferBulk(address[] to, uint[] tokens) public whenNotPaused {
require(to.length == tokens.length);
for (uint i = 0; i < to.length; i++) {
transfer(to[i], tokens[i]);
}
}
function transferMany(address to, uint[] tokens) public whenNotPaused {
for (uint i = 0; i < tokens.length; i++) {
transfer(to, tokens[i]);
}
}
// @notice Grant another address the right to transfer a particular Cutie via transferFrom().
// This flow is preferred for transferring NFTs to contracts.
// @param _to The address to be granted transfer approval. Pass address(0) to clear all approvals.
// @param _cutieId The ID of the Cutie that can be transferred if this call succeeds.
// @dev Required for ERC-721 compliance.
function approve(address _to, uint256 _cutieId) public whenNotPaused canBeStoredIn40Bits(_cutieId) {
// Only cutie's owner can grant transfer approval.
require(_isOwner(msg.sender, uint40(_cutieId)), "Caller is not a cutie owner");
require(msg.sender != _to, "Approval to current owner");
// Registering approval replaces any previous approval.
_approve(uint40(_cutieId), _to);
// Emit approval event.
emit Approval(msg.sender, _to, _cutieId);
}
function delegatedApprove(address _from, address _to, uint40 _cutieId) external whenNotPaused onlyGame {
require(_isOwner(_from, _cutieId), "Wrong cutie owner");
_approve(_cutieId, _to);
}
function approveAndCall(address _spender, uint _tokenId, bytes data) external whenNotPaused returns (bool) {
approve(_spender, _tokenId);
TokenRecipientInterface(_spender).receiveApproval(msg.sender, _tokenId, this, data);
return true;
}
// @notice Enable or disable approval for a third party ("operator") to manage
// all your asset.
// @dev Emits the ApprovalForAll event
// @param _operator Address to add to the set of authorized operators.
// @param _approved True if the operators is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external {
require(_operator != msg.sender, "Approve to caller");
if (_approved) {
addressToApprovedAll[msg.sender][_operator] = true;
} else {
delete addressToApprovedAll[msg.sender][_operator];
}
emit ApprovalForAll(msg.sender, _operator, _approved);
}
// @notice Get the approved address for a single NFT
// @dev Throws if `_tokenId` is not a valid NFT
// @param _tokenId The NFT to find the approved address for
// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view canBeStoredIn40Bits(_tokenId) returns (address) {
require(_tokenId <= total, "Cutie not exists");
return cutieIndexToApproved[uint40(_tokenId)];
}
// @notice Query if an address is an authorized operator for another address
// @param _owner The address that owns the NFTs
// @param _operator The address that acts on behalf of the owner
// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return addressToApprovedAll[_owner][_operator];
}
// @dev Returns whether `spender` is allowed to manage `cutieId`.
function _isApprovedOrOwner(address spender, uint40 cutieId) internal view returns (bool) {
require(_exists(cutieId), "Cutie not exists");
address owner = cutieIndexToOwner[cutieId];
return (spender == owner || _approvedFor(spender, cutieId) || isApprovedForAll(owner, spender));
}
// @dev Checks if a given address is the current owner of a certain Cutie.
// @param _claimant the address we are validating against.
// @param _cutieId cutie id, only valid when > 0
function _isOwner(address _claimant, uint40 _cutieId) internal view returns (bool) {
return cutieIndexToOwner[_cutieId] == _claimant;
}
function _exists(uint40 _cutieId) internal view returns (bool) {
return cutieIndexToOwner[_cutieId] != address(0);
}
// @dev Marks an address as being approved for transferFrom(), overwriting any previous
// approval. Setting _approved to address(0) clears all transfer approval.
// NOTE: _approve() does NOT send the Approval event. This is done on purpose:
// _approve() and transferFrom() are used together for putting Cuties on auction.
// There is no value in spamming the log with Approval events in that case.
function _approve(uint40 _cutieId, address _approved) internal {
cutieIndexToApproved[_cutieId] = _approved;
}
// @dev Checks if a given address currently has transferApproval for a certain Cutie.
// @param _claimant the address we are confirming the cutie is approved for.
// @param _cutieId cutie id, only valid when > 0
function _approvedFor(address _claimant, uint40 _cutieId) internal view returns (bool) {
return cutieIndexToApproved[_cutieId] == _claimant;
}
// @dev Assigns ownership of a particular Cutie to an address.
function _transfer(address _from, address _to, uint40 _cutieId) internal {
// since the number of cuties is capped to 2^40
// there is no way to overflow this
ownershipTokenCount[_to]++;
// transfer ownership
cutieIndexToOwner[_cutieId] = _to;
// When creating new cuties _from is 0x0, but we cannot account that address.
if (_from != address(0)) {
ownershipTokenCount[_from]--;
// clear any previously approved ownership exchange
delete cutieIndexToApproved[_cutieId];
}
// Emit the transfer event.
emit Transfer(_from, _to, _cutieId);
}
// 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.
function _isContract(address _account) internal view returns (bool) {
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(_account) }
return size > 0;
}
// @dev For transferring a cutie owned by this contract to the specified address.
// Used to rescue lost cuties. (There is no "proper" flow where this contract
// should be the owner of any Cutie. This function exists for us to reassign
// the ownership of Cuties that users may have accidentally sent to our address.)
// @param _cutieId - ID of cutie
// @param _recipient - Address to send the cutie to
function restoreCutieToAddress(uint40 _cutieId, address _recipient) external whenNotPaused onlyOperator {
require(_isOwner(this, _cutieId));
_transfer(this, _recipient, _cutieId);
}
// @dev An method that creates a new cutie and stores it. This
// method does not check anything and should only be called when the
// input data is valid for sure. Will generate both a Birth event
// and a Transfer event.
// @param _momId The cutie ID of the mom of this cutie (zero for gen0)
// @param _dadId The cutie ID of the dad of this cutie (zero for gen0)
// @param _generation The generation number of this cutie, must be computed by caller.
// @param _genes The cutie's genetic code.
// @param _owner The initial owner of this cutie, must be non-zero (except for the unCutie, ID 0)
function createCutie(
address _owner,
uint40 _momId,
uint40 _dadId,
uint16 _generation,
uint16 _cooldownIndex,
uint256 _genes,
uint40 _birthTime
) external whenNotPaused onlyGame returns (uint40) {
Cutie memory _cutie = Cutie({
genes : _genes,
birthTime : _birthTime,
cooldownEndTime : 0,
momId : _momId,
dadId : _dadId,
cooldownIndex : _cooldownIndex,
generation : _generation,
optional : 0
});
total++;
uint256 newCutieId256 = total;
// Check if id can fit into 40 bits
require(newCutieId256 <= 0xFFFFFFFFFF);
uint40 newCutieId = uint40(newCutieId256);
cuties[newCutieId] = _cutie;
// This will assign ownership, as well as emit the Transfer event as per ERC721 draft
_transfer(0, _owner, newCutieId);
return newCutieId;
}
// @dev Recreate the cutie if it stuck on old contracts and cannot be migrated smoothly
function restoreCutie(
address owner,
uint40 id,
uint256 _genes,
uint40 _momId,
uint40 _dadId,
uint16 _generation,
uint40 _cooldownEndTime,
uint16 _cooldownIndex,
uint40 _birthTime
) external whenNotPaused onlyGame {
require(owner != address(0), "Restore to zero address");
require(total >= id, "Cutie restore is not allowed");
require(cuties[id].birthTime == 0, "Cutie overwrite is forbidden");
Cutie memory cutie = Cutie({
genes: _genes,
momId: _momId,
dadId: _dadId,
generation: _generation,
cooldownEndTime: _cooldownEndTime,
cooldownIndex: _cooldownIndex,
birthTime: _birthTime,
optional: 0
});
cuties[id] = cutie;
cutieIndexToOwner[id] = owner;
ownershipTokenCount[owner]++;
}
// @notice Returns all the relevant information about a certain cutie.
// @param _id The ID of the cutie of interest.
function getCutie(uint40 _id) external view returns (
uint256 genes,
uint40 birthTime,
uint40 cooldownEndTime,
uint40 momId,
uint40 dadId,
uint16 cooldownIndex,
uint16 generation
) {
require(_exists(_id), "Cutie not exists");
Cutie storage cutie = cuties[_id];
genes = cutie.genes;
birthTime = cutie.birthTime;
cooldownEndTime = cutie.cooldownEndTime;
momId = cutie.momId;
dadId = cutie.dadId;
cooldownIndex = cutie.cooldownIndex;
generation = cutie.generation;
}
function getGenes(uint40 _id) external view returns (uint256) {
return cuties[_id].genes;
}
function setGenes(uint40 _id, uint256 _genes) external whenNotPaused onlyGame {
cuties[_id].genes = _genes;
}
function getCooldownEndTime(uint40 _id) external view returns (uint40) {
return cuties[_id].cooldownEndTime;
}
function setCooldownEndTime(uint40 _id, uint40 _cooldownEndTime) external whenNotPaused onlyGame {
cuties[_id].cooldownEndTime = _cooldownEndTime;
}
function getCooldownIndex(uint40 _id) external view returns (uint16) {
return cuties[_id].cooldownIndex;
}
function setCooldownIndex(uint40 _id, uint16 _cooldownIndex) external whenNotPaused onlyGame {
cuties[_id].cooldownIndex = _cooldownIndex;
}
function getGeneration(uint40 _id) external view returns (uint16) {
return cuties[_id].generation;
}
function setGeneration(uint40 _id, uint16 _generation) external whenNotPaused onlyGame {
cuties[_id].generation = _generation;
}
function getOptional(uint40 _id) external view returns (uint64) {
return cuties[_id].optional;
}
function setOptional(uint40 _id, uint64 _optional) external whenNotPaused onlyGame {
cuties[_id].optional = _optional;
}
}
|
Modifiers to check that inputs can be safely stored with a certain number of bits
|
modifier canBeStoredIn40Bits(uint256 _value) {
require(_value <= 0xFFFFFFFFFF, "Value can't be stored in 40 bits");
_;
}
| 253,385 |
[
1,
11948,
358,
866,
716,
4540,
848,
506,
15303,
4041,
598,
279,
8626,
1300,
434,
4125,
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,
565,
9606,
24978,
18005,
382,
7132,
6495,
12,
11890,
5034,
389,
1132,
13,
288,
203,
3639,
2583,
24899,
1132,
1648,
374,
6356,
8998,
8998,
16,
315,
620,
848,
1404,
506,
4041,
316,
8063,
4125,
8863,
203,
3639,
389,
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
] |
pragma solidity^0.4.10;
contract Store{
struct Node{
bytes32 id;
bytes32 left;
bytes32 right;
bytes32 data;
}
struct Index{
bytes32 root;
bytes32 last;
uint size;
mapping(bytes32=>Node) nodes;
}
mapping(bytes32=>Index) index_lookup;
mapping(bytes32=>bytes32) nodes_to_index;
//event newIndex(bytes32);
function nodeExists(bytes32 index_id,bytes32 node_id) constant returns(bool){
return (nodes_to_index[node_id] == index_id);
}
function getIndex(bytes32 index_id) constant returns(bytes32,bytes32,uint){
return (index_lookup[index_id].root,index_lookup[index_id].last,index_lookup[index_id].size);
}
function getIndexId(bytes32 node_id) constant returns(bytes32){
return nodes_to_index[node_id];
}
function getNode(bytes32 node_id)constant returns(bytes32 id,bytes32 left,bytes32,bytes32){
bytes32 index_id = nodes_to_index[node_id];
Node memory current_node = index_lookup[index_id].nodes[node_id];
return(current_node.id,current_node.left,current_node.right,current_node.data);
}
function getNodesBatch(bytes32 index_id,bytes32 last_node_id)constant returns(bytes32[5][4] memory results){
Index storage index = index_lookup[index_id];
//return empty array if empty
if(index.size<1)
return(results);
//Choose node to begin fetching from
if(last_node_id == 0x0)last_node_id = index.root;
else last_node_id = index.nodes[last_node_id].right;
uint r = 0;
while(r<5 && last_node_id!=0x0){
results[0][r]= index.nodes[last_node_id].id;
results[1][r]= index.nodes[last_node_id].left;
results[2][r]= index.nodes[last_node_id].right;
results[3][r]= index.nodes[last_node_id].data;
r++;
if(index.nodes[last_node_id].right == 0x0)
break;
else last_node_id = index.nodes[last_node_id].right;
}
}
function insertNodes(bytes32 index_id,bytes32[2][5] nodes_data) {
//Nodes_data[id,data]
Index storage index = index_lookup[index_id];
bytes32 left_node;
bytes32 right_node;
bytes32 node_id;
for(uint n = 0;n<nodes_data.length;n++){
if(nodes_data[n][0] == 0x0) continue;
node_id = nodes_data[n][0];
if(n==0){
if(index.root==0x0){
index.root = node_id;
left_node = 0x0;
}
else{
left_node = index.last;
}
}
else{
left_node = nodes_data[n-1][0];
}
right_node = 0x0;
nodes_to_index[node_id] = index_id;
index.nodes[node_id] = Node(node_id,left_node,right_node,nodes_data[n][1]);
index.size++;
//update previous node
if(left_node!=0x0)
index.nodes[left_node].right = node_id;
}
index.last = node_id;
}
function removeNode(bytes32 index_id,bytes32 node_id) nodeIndexMatches(node_id,index_id) indexNotEmpty(index_id){
Index storage index = index_lookup[index_id];
bytes32 left_node = index.nodes[node_id].left;
bytes32 right_node = index.nodes[node_id].right;
//Update new root if root node
if(index.root == node_id)
index.root = right_node;
//Update left and right reference of node
if(index.root != node_id)
index.nodes[left_node].right = right_node;
if(right_node!= 0x0)
index.nodes[right_node].left = left_node;
//Update index.last if last
if(index.last == node_id)
index.last = left_node;
//Update size and delete componnts
index.size--;
delete(nodes_to_index[node_id]);
delete(index.nodes[node_id]);
}
modifier nodeIndexMatches(bytes32 node_id, bytes32 index_id){
require(index_id == nodes_to_index[node_id]);
_;
}
modifier indexNotEmpty(bytes32 index_id){
require(index_lookup[index_id].size>0);
_;
}
}
|
Update new root if root nodeUpdate left and right reference of nodeUpdate index.last if lastUpdate size and delete componnts
|
function removeNode(bytes32 index_id,bytes32 node_id) nodeIndexMatches(node_id,index_id) indexNotEmpty(index_id){
Index storage index = index_lookup[index_id];
bytes32 left_node = index.nodes[node_id].left;
bytes32 right_node = index.nodes[node_id].right;
if(index.root == node_id)
index.root = right_node;
if(index.root != node_id)
index.nodes[left_node].right = right_node;
if(right_node!= 0x0)
index.nodes[right_node].left = left_node;
if(index.last == node_id)
index.last = left_node;
index.size--;
delete(nodes_to_index[node_id]);
delete(index.nodes[node_id]);
}
| 14,076,038 |
[
1,
1891,
394,
1365,
309,
1365,
756,
1891,
2002,
471,
2145,
2114,
434,
756,
1891,
770,
18,
2722,
309,
1142,
1891,
963,
471,
1430,
532,
500,
27932,
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,
1206,
907,
12,
3890,
1578,
770,
67,
350,
16,
3890,
1578,
756,
67,
350,
13,
756,
1016,
6869,
12,
2159,
67,
350,
16,
1615,
67,
350,
13,
770,
18431,
12,
1615,
67,
350,
15329,
203,
203,
3639,
3340,
2502,
770,
273,
770,
67,
8664,
63,
1615,
67,
350,
15533,
203,
3639,
1731,
1578,
2002,
67,
2159,
273,
770,
18,
4690,
63,
2159,
67,
350,
8009,
4482,
31,
203,
3639,
1731,
1578,
2145,
67,
2159,
273,
770,
18,
4690,
63,
2159,
67,
350,
8009,
4083,
31,
203,
203,
3639,
309,
12,
1615,
18,
3085,
422,
756,
67,
350,
13,
203,
3639,
770,
18,
3085,
273,
2145,
67,
2159,
31,
203,
3639,
309,
12,
1615,
18,
3085,
480,
756,
67,
350,
13,
203,
3639,
770,
18,
4690,
63,
4482,
67,
2159,
8009,
4083,
273,
2145,
67,
2159,
31,
203,
3639,
309,
12,
4083,
67,
2159,
5,
33,
374,
92,
20,
13,
203,
3639,
770,
18,
4690,
63,
4083,
67,
2159,
8009,
4482,
273,
2002,
67,
2159,
31,
203,
3639,
309,
12,
1615,
18,
2722,
422,
756,
67,
350,
13,
203,
3639,
770,
18,
2722,
273,
2002,
67,
2159,
31,
203,
203,
3639,
770,
18,
1467,
413,
31,
203,
3639,
1430,
12,
4690,
67,
869,
67,
1615,
63,
2159,
67,
350,
19226,
203,
3639,
1430,
12,
1615,
18,
4690,
63,
2159,
67,
350,
19226,
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
] |
./full_match/4/0x88c2EF4520a6173E492aDeFa175Ba2497588Fe1f/sources/RandomNumber.sol
|
* Requests randomness from a user-provided seed/
|
function getRandomNumber(uint256 userProvidedSeed) public returns (bytes32 requestId) {
require(LINK.balanceOf(address(this)) >= fee, "Insufficient balance for request");
requestId = requestRandomness(keyHash, fee, userProvidedSeed);
emit RequestedRandomness(requestId);
return requestId;
}
| 720,551 |
[
1,
6421,
2744,
4496,
628,
279,
729,
17,
29206,
5009,
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
] |
[
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,
20581,
1854,
12,
11890,
5034,
729,
19254,
12702,
13,
1071,
1135,
261,
3890,
1578,
14459,
13,
288,
203,
3639,
2583,
12,
10554,
18,
12296,
951,
12,
2867,
12,
2211,
3719,
1545,
14036,
16,
315,
5048,
11339,
11013,
364,
590,
8863,
203,
3639,
14459,
273,
590,
8529,
4496,
12,
856,
2310,
16,
14036,
16,
729,
19254,
12702,
1769,
203,
3639,
3626,
25829,
8529,
4496,
12,
2293,
548,
1769,
203,
3639,
327,
14459,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/ECDSAUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721URIStorageUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721BurnableUpgradeable.sol";
import "./BaseCollection.sol";
contract TokenCollection is
BaseCollection,
ERC721URIStorageUpgradeable,
ERC721BurnableUpgradeable
{
event RedeemableCreated(uint256 indexed redeemableId);
event TokenRedeemed(
address indexed collector,
uint256 indexed redeemableId,
uint256 quantity
);
struct Redeemable {
string tokenURI;
uint256 price;
uint256 maxAmount;
uint256 maxPerWallet;
uint256 maxPerMint;
uint256 redeemedCount;
bytes32 merkleRoot;
bool active;
uint256 nonce;
}
using CountersUpgradeable for CountersUpgradeable.Counter;
using SafeMathUpgradeable for uint256;
using MerkleProofUpgradeable for bytes32[];
using ECDSAUpgradeable for bytes32;
CountersUpgradeable.Counter private _tokenIdCounter;
CountersUpgradeable.Counter private _redeemablesCounter;
mapping(uint256 => Redeemable) private _redeemables;
mapping(uint256 => mapping(address => uint256)) _redeemedByWallet;
modifier onlyRedeemable(
uint256 redeemableId,
uint256 numberOfTokens,
bytes calldata signature
) {
Redeemable memory redeemable = _redeemables[redeemableId];
require(redeemable.active, "Not valid: 1");
require(
redeemable.price.mul(numberOfTokens) <= msg.value,
"Value incorrect"
);
require(
_redeemedByWallet[redeemableId][_msgSender()].add(numberOfTokens) <=
redeemable.maxPerWallet,
"Exceeded max: 1"
);
require(
redeemable.redeemedCount.add(numberOfTokens) <=
redeemable.maxAmount,
"Exceeded max: 2"
);
require(
keccak256(abi.encodePacked(redeemableId.add(redeemable.nonce)))
.toEthSignedMessageHash()
.recover(signature) == owner(),
"Not valid: 2"
);
_;
}
function initialize(
string memory name_,
string memory symbol_,
address treasury_,
address trustedForwarder_
) public override initializer {
__BaseCollection_init(name_, symbol_, treasury_, trustedForwarder_);
__ERC721URIStorage_init();
__ERC721Burnable_init();
}
function mint(address to, string memory uri) public onlyOwner {
_mint(to, uri);
}
function createRedeemable(
string memory uri,
uint256 price,
uint256 maxAmount,
uint256 maxPerWallet,
uint256 maxPerMint
) public onlyOwner {
uint256 redeemableId = _redeemablesCounter.current();
_redeemablesCounter.increment();
_redeemables[redeemableId] = Redeemable({
tokenURI: uri,
price: price,
maxAmount: maxAmount,
maxPerWallet: maxPerWallet,
maxPerMint: maxPerMint,
redeemedCount: 0,
merkleRoot: "",
active: true,
nonce: 0
});
emit RedeemableCreated(redeemableId);
}
function setMerkleRoot(uint256 redeemableId, bytes32 newRoot)
public
onlyOwner
{
require(_redeemables[redeemableId].active, "Invalid Redeemable");
_redeemables[redeemableId].merkleRoot = newRoot;
}
function invalidate(uint256 redeemableId) public onlyOwner {
require(_redeemables[redeemableId].active, "Invalid Redeemable");
_redeemables[redeemableId].nonce = _redeemables[redeemableId].nonce.add(
1
);
}
function revoke(uint256 redeemableId) public onlyOwner {
require(_redeemables[redeemableId].active, "Invalid Redeemable");
_redeemables[redeemableId].active = false;
}
function redeem(
uint256 redeemableId,
uint256 numberOfTokens,
bytes calldata signature
) public payable onlyRedeemable(redeemableId, numberOfTokens, signature) {
Redeemable memory redeemable = _redeemables[redeemableId];
require(redeemable.merkleRoot == "", "Not valid: 3");
_redeem(redeemableId, numberOfTokens);
}
function redeem(
uint256 redeemableId,
uint256 numberOfTokens,
bytes calldata signature,
bytes32[] calldata proof
) public payable onlyRedeemable(redeemableId, numberOfTokens, signature) {
Redeemable memory redeemable = _redeemables[redeemableId];
require(redeemable.merkleRoot != "", "Not valid: 3");
require(
MerkleProofUpgradeable.verify(
proof,
redeemable.merkleRoot,
keccak256(abi.encodePacked(_msgSender()))
),
"Not valid: 4"
);
_redeem(redeemableId, numberOfTokens);
}
function totalRedeemables() external view returns (uint256) {
return _redeemablesCounter.current();
}
function redeemableByIndex(uint256 index)
external
view
returns (
string memory uri,
uint256 price,
uint256 maxAmount,
uint256 maxPerWallet,
uint256 maxPerMint,
uint256 redeemedCount,
bytes32 merkleRoot,
bool active,
uint256 nonce
)
{
Redeemable memory redeemable = _redeemables[index];
return (
redeemable.tokenURI,
redeemable.price,
redeemable.maxAmount,
redeemable.maxPerWallet,
redeemable.maxPerMint,
redeemable.redeemedCount,
redeemable.merkleRoot,
redeemable.active,
redeemable.nonce
);
}
function _redeem(uint256 redeemableId, uint256 numberOfTokens) internal {
Redeemable memory redeemable = _redeemables[redeemableId];
if (msg.value > 0) {
_totalRevenue = _totalRevenue.add(msg.value);
_niftyKit.addFees(msg.value);
}
_redeemables[redeemableId].redeemedCount = redeemable.redeemedCount.add(
numberOfTokens
);
_redeemedByWallet[redeemableId][_msgSender()] = _redeemedByWallet[
redeemableId
][_msgSender()].add(numberOfTokens);
for (uint256 i = 0; i < numberOfTokens; i++) {
_mint(_msgSender(), redeemable.tokenURI);
}
emit TokenRedeemed(_msgSender(), redeemableId, numberOfTokens);
}
function _mint(address to, string memory uri) internal {
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, tokenId);
_setTokenURI(tokenId, uri);
}
// The following functions are overrides required by Solidity.
function _msgSender()
internal
view
virtual
override(BaseCollection, ContextUpgradeable)
returns (address sender)
{
return BaseCollection._msgSender();
}
function _msgData()
internal
view
virtual
override(BaseCollection, ContextUpgradeable)
returns (bytes calldata)
{
return BaseCollection._msgData();
}
function _burn(uint256 tokenId)
internal
override(ERC721Upgradeable, ERC721URIStorageUpgradeable)
{
ERC721URIStorageUpgradeable._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721Upgradeable, ERC721URIStorageUpgradeable)
returns (string memory)
{
return ERC721URIStorageUpgradeable.tokenURI(tokenId);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal override(BaseCollection, ERC721Upgradeable) {
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(BaseCollection, ERC721Upgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// 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 SafeMathUpgradeable {
/**
* @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/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 MerkleProofUpgradeable {
/**
* @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 = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
return computedHash;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721URIStorage.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorageUpgradeable is Initializable, ERC721Upgradeable {
function __ERC721URIStorage_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721URIStorage_init_unchained();
}
function __ERC721URIStorage_init_unchained() internal onlyInitializing {
}
using StringsUpgradeable for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @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 override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Burnable.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "../../../utils/ContextUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable {
function __ERC721Burnable_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Burnable_init_unchained();
}
function __ERC721Burnable_init_unchained() internal onlyInitializing {
}
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/metatx/ERC2771ContextUpgradeable.sol";
import "./interfaces/IBaseCollection.sol";
import "./interfaces/INiftyKit.sol";
abstract contract BaseCollection is
ERC721Upgradeable,
ERC721EnumerableUpgradeable,
ERC2771ContextUpgradeable,
OwnableUpgradeable,
IBaseCollection
{
using AddressUpgradeable for address;
using SafeMathUpgradeable for uint256;
INiftyKit internal _niftyKit;
address internal _treasury;
uint256 internal _totalRevenue;
function __BaseCollection_init(
string memory name_,
string memory symbol_,
address treasury_,
address trustedForwarder_
) internal onlyInitializing {
__ERC721_init(name_, symbol_);
__ERC721Enumerable_init();
__ERC2771Context_init_unchained(trustedForwarder_);
__Ownable_init_unchained();
_niftyKit = INiftyKit(_msgSender());
_treasury = treasury_;
}
function withdraw() public {
require(address(this).balance > 0, "0 balance");
uint256 balance = address(this).balance;
uint256 fees = _niftyKit.getFees(address(this));
AddressUpgradeable.sendValue(payable(_treasury), balance.sub(fees));
AddressUpgradeable.sendValue(payable(address(_niftyKit)), fees);
_niftyKit.addFeesClaimed(fees);
}
function setTreasury(address newTreasury) public onlyOwner {
_treasury = newTreasury;
}
function treasury() external view returns (address) {
return _treasury;
}
function totalRevenue() external view returns (uint256) {
return _totalRevenue;
}
// The following functions are overrides required by Solidity.
function _msgSender()
internal
view
virtual
override(ERC2771ContextUpgradeable, ContextUpgradeable)
returns (address sender)
{
return ERC2771ContextUpgradeable._msgSender();
}
function _msgData()
internal
view
virtual
override(ERC2771ContextUpgradeable, ContextUpgradeable)
returns (bytes calldata)
{
return ERC2771ContextUpgradeable._msgData();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
)
internal
virtual
override(ERC721Upgradeable, ERC721EnumerableUpgradeable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC721Upgradeable, ERC721EnumerableUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function transferOwnership(address newOwner)
public
override(IBaseCollection, OwnableUpgradeable)
{
return OwnableUpgradeable.transferOwnership(newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721Upgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "./extensions/IERC721MetadataUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../ERC721Upgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Enumerable_init_unchained();
}
function __ERC721Enumerable_init_unchained() internal onlyInitializing {
}
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721Upgradeable.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
uint256[46] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (metatx/ERC2771Context.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Context variant with ERC2771 support.
*/
abstract contract ERC2771ContextUpgradeable is Initializable, ContextUpgradeable {
address private _trustedForwarder;
function __ERC2771Context_init(address trustedForwarder) internal onlyInitializing {
__Context_init_unchained();
__ERC2771Context_init_unchained(trustedForwarder);
}
function __ERC2771Context_init_unchained(address trustedForwarder) internal onlyInitializing {
_trustedForwarder = trustedForwarder;
}
function isTrustedForwarder(address forwarder) public view virtual returns (bool) {
return forwarder == _trustedForwarder;
}
function _msgSender() internal view virtual override returns (address sender) {
if (isTrustedForwarder(msg.sender)) {
// The assembly code is more direct than the Solidity version using `abi.decode`.
assembly {
sender := shr(96, calldataload(sub(calldatasize(), 20)))
}
} else {
return super._msgSender();
}
}
function _msgData() internal view virtual override returns (bytes calldata) {
if (isTrustedForwarder(msg.sender)) {
return msg.data[:msg.data.length - 20];
} else {
return super._msgData();
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
interface IBaseCollection {
/**
* @dev Contract upgradeable initializer
*/
function initialize(
string memory,
string memory,
address,
address
) external;
/**
* @dev part of Ownable
*/
function transferOwnership(address) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
interface INiftyKit {
/**
* @dev Emitted when collection is created
*/
event CollectionCreated(address indexed collectionAddress);
/**
* @dev Returns the commission amount.
*/
function commission(uint256 amount) external view returns (uint256);
/**
* @dev Add fees from Collection
*/
function addFees(uint256 amount) external;
/**
* @dev Add fees claimed by the Collection
*/
function addFeesClaimed(uint256 amount) external;
/**
* @dev Get fees accrued by the account
*/
function getFees(address account) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
|
The following functions are overrides required by Solidity.
|
function _msgSender()
internal
view
virtual
override(BaseCollection, ContextUpgradeable)
returns (address sender)
{
return BaseCollection._msgSender();
}
| 1,322,846 |
[
1,
1986,
3751,
4186,
854,
9515,
1931,
635,
348,
7953,
560,
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
] |
[
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,
389,
3576,
12021,
1435,
203,
3639,
2713,
203,
3639,
1476,
203,
3639,
5024,
203,
3639,
3849,
12,
2171,
2532,
16,
1772,
10784,
429,
13,
203,
3639,
1135,
261,
2867,
5793,
13,
203,
565,
288,
203,
3639,
327,
3360,
2532,
6315,
3576,
12021,
5621,
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
] |
./partial_match/1/0x03eD525f0397427ebA0cF3BfD0854fB410f5Ebb3/sources/NOEPEPE.sol
|
lib/openzeppelin-contracts/contracts/utils/Context.sol OpenZeppelin Contracts v4.4.0 (utils/Context.sol) pragma solidity ^0.8.0; */* @dev Provides information about the current execution context, including the sender of the transaction and its data. While these are generally available via msg.sender and msg.data, they should not be accessed in such a direct manner, since when dealing with meta-transactions the account sending and paying for execution may not be the actual sender (as far as an application is concerned). This contract is only required for intermediate, library-like contracts./
|
abstract contract Context {
THERE IS NO PEPE. He isn't real.
pragma solidity =0.8.10 >=0.8.10 >=0.8.0 <0.9.0;
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
| 4,404,300 |
[
1,
2941,
19,
3190,
94,
881,
84,
292,
267,
17,
16351,
87,
19,
16351,
87,
19,
5471,
19,
1042,
18,
18281,
3502,
62,
881,
84,
292,
267,
30131,
331,
24,
18,
24,
18,
20,
261,
5471,
19,
1042,
18,
18281,
13,
10878,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
342,
225,
28805,
1779,
2973,
326,
783,
4588,
819,
16,
6508,
326,
5793,
434,
326,
2492,
471,
2097,
501,
18,
21572,
4259,
854,
19190,
2319,
3970,
1234,
18,
15330,
471,
1234,
18,
892,
16,
2898,
1410,
486,
506,
15539,
316,
4123,
279,
2657,
21296,
16,
3241,
1347,
21964,
598,
2191,
17,
20376,
326,
2236,
5431,
471,
8843,
310,
364,
4588,
2026,
486,
506,
326,
3214,
5793,
261,
345,
10247,
487,
392,
2521,
353,
356,
2750,
11748,
2934,
1220,
6835,
353,
1338,
1931,
364,
12110,
16,
5313,
17,
5625,
20092,
18,
19,
2,
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,
1,
1,
0,
0,
0,
0,
0,
0,
0
] |
[
1,
17801,
6835,
1772,
288,
203,
19905,
41,
4437,
3741,
16628,
1423,
18,
8264,
5177,
1404,
2863,
18,
203,
203,
683,
9454,
18035,
560,
273,
20,
18,
28,
18,
2163,
1545,
20,
18,
28,
18,
2163,
1545,
20,
18,
28,
18,
20,
411,
20,
18,
29,
18,
20,
31,
203,
565,
445,
389,
3576,
12021,
1435,
2713,
1476,
5024,
1135,
261,
2867,
13,
288,
203,
3639,
327,
1234,
18,
15330,
31,
203,
565,
289,
203,
203,
565,
445,
389,
3576,
751,
1435,
2713,
1476,
5024,
1135,
261,
3890,
745,
892,
13,
288,
203,
3639,
327,
1234,
18,
892,
31,
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
] |
pragma solidity ^0.5.16;
// Inheritance
import "./Owned.sol";
import "./MixinResolver.sol";
import "./MixinSystemSettings.sol";
import "./interfaces/IExchanger.sol";
// Libraries
import "./SafeDecimalMath.sol";
// Internal references
import "./interfaces/ISystemStatus.sol";
import "./interfaces/IERC20.sol";
import "./interfaces/IExchangeState.sol";
import "./interfaces/IExchangeRates.sol";
import "./interfaces/IExchangeCircuitBreaker.sol";
import "./interfaces/ISynthetix.sol";
import "./interfaces/IFeePool.sol";
import "./interfaces/IDelegateApprovals.sol";
import "./interfaces/IIssuer.sol";
import "./interfaces/ITradingRewards.sol";
import "./interfaces/IVirtualSynth.sol";
import "./Proxyable.sol";
// Used to have strongly-typed access to internal mutative functions in Synthetix
interface ISynthetixInternal {
function emitExchangeTracking(
bytes32 trackingCode,
bytes32 toCurrencyKey,
uint256 toAmount,
uint256 fee
) external;
function emitSynthExchange(
address account,
bytes32 fromCurrencyKey,
uint fromAmount,
bytes32 toCurrencyKey,
uint toAmount,
address toAddress
) external;
function emitAtomicSynthExchange(
address account,
bytes32 fromCurrencyKey,
uint fromAmount,
bytes32 toCurrencyKey,
uint toAmount,
address toAddress
) external;
function emitExchangeReclaim(
address account,
bytes32 currencyKey,
uint amount
) external;
function emitExchangeRebate(
address account,
bytes32 currencyKey,
uint amount
) external;
}
interface IExchangerInternalDebtCache {
function updateCachedSynthDebtsWithRates(bytes32[] calldata currencyKeys, uint[] calldata currencyRates) external;
function updateCachedSynthDebts(bytes32[] calldata currencyKeys) external;
}
// https://docs.synthetix.io/contracts/source/contracts/exchanger
contract Exchanger is Owned, MixinSystemSettings, IExchanger {
using SafeMath for uint;
using SafeDecimalMath for uint;
bytes32 public constant CONTRACT_NAME = "Exchanger";
bytes32 internal constant sUSD = "sUSD";
/* ========== ADDRESS RESOLVER CONFIGURATION ========== */
bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus";
bytes32 private constant CONTRACT_EXCHANGESTATE = "ExchangeState";
bytes32 private constant CONTRACT_EXRATES = "ExchangeRates";
bytes32 private constant CONTRACT_SYNTHETIX = "Synthetix";
bytes32 private constant CONTRACT_FEEPOOL = "FeePool";
bytes32 private constant CONTRACT_TRADING_REWARDS = "TradingRewards";
bytes32 private constant CONTRACT_DELEGATEAPPROVALS = "DelegateApprovals";
bytes32 private constant CONTRACT_ISSUER = "Issuer";
bytes32 private constant CONTRACT_DEBTCACHE = "DebtCache";
bytes32 private constant CONTRACT_CIRCUIT_BREAKER = "ExchangeCircuitBreaker";
constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {}
/* ========== VIEWS ========== */
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
bytes32[] memory existingAddresses = MixinSystemSettings.resolverAddressesRequired();
bytes32[] memory newAddresses = new bytes32[](10);
newAddresses[0] = CONTRACT_SYSTEMSTATUS;
newAddresses[1] = CONTRACT_EXCHANGESTATE;
newAddresses[2] = CONTRACT_EXRATES;
newAddresses[3] = CONTRACT_SYNTHETIX;
newAddresses[4] = CONTRACT_FEEPOOL;
newAddresses[5] = CONTRACT_TRADING_REWARDS;
newAddresses[6] = CONTRACT_DELEGATEAPPROVALS;
newAddresses[7] = CONTRACT_ISSUER;
newAddresses[8] = CONTRACT_DEBTCACHE;
newAddresses[9] = CONTRACT_CIRCUIT_BREAKER;
addresses = combineArrays(existingAddresses, newAddresses);
}
function systemStatus() internal view returns (ISystemStatus) {
return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS));
}
function exchangeState() internal view returns (IExchangeState) {
return IExchangeState(requireAndGetAddress(CONTRACT_EXCHANGESTATE));
}
function exchangeRates() internal view returns (IExchangeRates) {
return IExchangeRates(requireAndGetAddress(CONTRACT_EXRATES));
}
function exchangeCircuitBreaker() internal view returns (IExchangeCircuitBreaker) {
return IExchangeCircuitBreaker(requireAndGetAddress(CONTRACT_CIRCUIT_BREAKER));
}
function synthetix() internal view returns (ISynthetix) {
return ISynthetix(requireAndGetAddress(CONTRACT_SYNTHETIX));
}
function feePool() internal view returns (IFeePool) {
return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL));
}
function tradingRewards() internal view returns (ITradingRewards) {
return ITradingRewards(requireAndGetAddress(CONTRACT_TRADING_REWARDS));
}
function delegateApprovals() internal view returns (IDelegateApprovals) {
return IDelegateApprovals(requireAndGetAddress(CONTRACT_DELEGATEAPPROVALS));
}
function issuer() internal view returns (IIssuer) {
return IIssuer(requireAndGetAddress(CONTRACT_ISSUER));
}
function debtCache() internal view returns (IExchangerInternalDebtCache) {
return IExchangerInternalDebtCache(requireAndGetAddress(CONTRACT_DEBTCACHE));
}
function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) public view returns (uint) {
return secsLeftInWaitingPeriodForExchange(exchangeState().getMaxTimestamp(account, currencyKey));
}
function waitingPeriodSecs() external view returns (uint) {
return getWaitingPeriodSecs();
}
function tradingRewardsEnabled() external view returns (bool) {
return getTradingRewardsEnabled();
}
function priceDeviationThresholdFactor() external view returns (uint) {
return getPriceDeviationThresholdFactor();
}
function lastExchangeRate(bytes32 currencyKey) external view returns (uint) {
return exchangeCircuitBreaker().lastExchangeRate(currencyKey);
}
function settlementOwing(address account, bytes32 currencyKey)
public
view
returns (
uint reclaimAmount,
uint rebateAmount,
uint numEntries
)
{
(reclaimAmount, rebateAmount, numEntries, ) = _settlementOwing(account, currencyKey);
}
// Internal function to aggregate each individual rebate and reclaim entry for a synth
function _settlementOwing(address account, bytes32 currencyKey)
internal
view
returns (
uint reclaimAmount,
uint rebateAmount,
uint numEntries,
IExchanger.ExchangeEntrySettlement[] memory
)
{
// Need to sum up all reclaim and rebate amounts for the user and the currency key
numEntries = exchangeState().getLengthOfEntries(account, currencyKey);
// For each unsettled exchange
IExchanger.ExchangeEntrySettlement[] memory settlements = new IExchanger.ExchangeEntrySettlement[](numEntries);
for (uint i = 0; i < numEntries; i++) {
uint reclaim;
uint rebate;
// fetch the entry from storage
IExchangeState.ExchangeEntry memory exchangeEntry = _getExchangeEntry(account, currencyKey, i);
// determine the last round ids for src and dest pairs when period ended or latest if not over
(uint srcRoundIdAtPeriodEnd, uint destRoundIdAtPeriodEnd) = getRoundIdsAtPeriodEnd(exchangeEntry);
// given these round ids, determine what effective value they should have received
(uint destinationAmount, , ) =
exchangeRates().effectiveValueAndRatesAtRound(
exchangeEntry.src,
exchangeEntry.amount,
exchangeEntry.dest,
srcRoundIdAtPeriodEnd,
destRoundIdAtPeriodEnd
);
// and deduct the fee from this amount using the exchangeFeeRate from storage
uint amountShouldHaveReceived = _deductFeesFromAmount(destinationAmount, exchangeEntry.exchangeFeeRate);
// SIP-65 settlements where the amount at end of waiting period is beyond the threshold, then
// settle with no reclaim or rebate
bool sip65condition =
exchangeCircuitBreaker().isDeviationAboveThreshold(exchangeEntry.amountReceived, amountShouldHaveReceived);
if (!sip65condition) {
if (exchangeEntry.amountReceived > amountShouldHaveReceived) {
// if they received more than they should have, add to the reclaim tally
reclaim = exchangeEntry.amountReceived.sub(amountShouldHaveReceived);
reclaimAmount = reclaimAmount.add(reclaim);
} else if (amountShouldHaveReceived > exchangeEntry.amountReceived) {
// if less, add to the rebate tally
rebate = amountShouldHaveReceived.sub(exchangeEntry.amountReceived);
rebateAmount = rebateAmount.add(rebate);
}
}
settlements[i] = IExchanger.ExchangeEntrySettlement({
src: exchangeEntry.src,
amount: exchangeEntry.amount,
dest: exchangeEntry.dest,
reclaim: reclaim,
rebate: rebate,
srcRoundIdAtPeriodEnd: srcRoundIdAtPeriodEnd,
destRoundIdAtPeriodEnd: destRoundIdAtPeriodEnd,
timestamp: exchangeEntry.timestamp
});
}
return (reclaimAmount, rebateAmount, numEntries, settlements);
}
function _getExchangeEntry(
address account,
bytes32 currencyKey,
uint index
) internal view returns (IExchangeState.ExchangeEntry memory) {
(
bytes32 src,
uint amount,
bytes32 dest,
uint amountReceived,
uint exchangeFeeRate,
uint timestamp,
uint roundIdForSrc,
uint roundIdForDest
) = exchangeState().getEntryAt(account, currencyKey, index);
return
IExchangeState.ExchangeEntry({
src: src,
amount: amount,
dest: dest,
amountReceived: amountReceived,
exchangeFeeRate: exchangeFeeRate,
timestamp: timestamp,
roundIdForSrc: roundIdForSrc,
roundIdForDest: roundIdForDest
});
}
function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool) {
if (maxSecsLeftInWaitingPeriod(account, currencyKey) != 0) {
return true;
}
(uint reclaimAmount, , , ) = _settlementOwing(account, currencyKey);
return reclaimAmount > 0;
}
/* ========== SETTERS ========== */
function calculateAmountAfterSettlement(
address from,
bytes32 currencyKey,
uint amount,
uint refunded
) public view returns (uint amountAfterSettlement) {
amountAfterSettlement = amount;
// balance of a synth will show an amount after settlement
uint balanceOfSourceAfterSettlement = IERC20(address(issuer().synths(currencyKey))).balanceOf(from);
// when there isn't enough supply (either due to reclamation settlement or because the number is too high)
if (amountAfterSettlement > balanceOfSourceAfterSettlement) {
// then the amount to exchange is reduced to their remaining supply
amountAfterSettlement = balanceOfSourceAfterSettlement;
}
if (refunded > 0) {
amountAfterSettlement = amountAfterSettlement.add(refunded);
}
}
function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool) {
(, bool invalid) = exchangeCircuitBreaker().rateWithInvalid(currencyKey);
return invalid;
}
/* ========== MUTATIVE FUNCTIONS ========== */
function exchange(
address exchangeForAddress,
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
bool virtualSynth,
address rewardAddress,
bytes32 trackingCode
) external onlySynthetixorSynth returns (uint amountReceived, IVirtualSynth vSynth) {
uint fee;
if (from != exchangeForAddress) {
require(delegateApprovals().canExchangeFor(exchangeForAddress, from), "Not approved to act on behalf");
}
(amountReceived, fee, vSynth) = _exchange(
exchangeForAddress,
sourceCurrencyKey,
sourceAmount,
destinationCurrencyKey,
destinationAddress,
virtualSynth
);
_processTradingRewards(fee, rewardAddress);
if (trackingCode != bytes32(0)) {
_emitTrackingEvent(trackingCode, destinationCurrencyKey, amountReceived, fee);
}
}
function exchangeAtomically(
address,
bytes32,
uint,
bytes32,
address,
bytes32,
uint
) external returns (uint) {
_notImplemented();
}
function _emitTrackingEvent(
bytes32 trackingCode,
bytes32 toCurrencyKey,
uint256 toAmount,
uint256 fee
) internal {
ISynthetixInternal(address(synthetix())).emitExchangeTracking(trackingCode, toCurrencyKey, toAmount, fee);
}
function _processTradingRewards(uint fee, address rewardAddress) internal {
if (fee > 0 && rewardAddress != address(0) && getTradingRewardsEnabled()) {
tradingRewards().recordExchangeFeeForAccount(fee, rewardAddress);
}
}
function _updateSNXIssuedDebtOnExchange(bytes32[2] memory currencyKeys, uint[2] memory currencyRates) internal {
bool includesSUSD = currencyKeys[0] == sUSD || currencyKeys[1] == sUSD;
uint numKeys = includesSUSD ? 2 : 3;
bytes32[] memory keys = new bytes32[](numKeys);
keys[0] = currencyKeys[0];
keys[1] = currencyKeys[1];
uint[] memory rates = new uint[](numKeys);
rates[0] = currencyRates[0];
rates[1] = currencyRates[1];
if (!includesSUSD) {
keys[2] = sUSD; // And we'll also update sUSD to account for any fees if it wasn't one of the exchanged currencies
rates[2] = SafeDecimalMath.unit();
}
// Note that exchanges can't invalidate the debt cache, since if a rate is invalid,
// the exchange will have failed already.
debtCache().updateCachedSynthDebtsWithRates(keys, rates);
}
function _settleAndCalcSourceAmountRemaining(
uint sourceAmount,
address from,
bytes32 sourceCurrencyKey
) internal returns (uint sourceAmountAfterSettlement) {
(, uint refunded, uint numEntriesSettled) = _internalSettle(from, sourceCurrencyKey, false);
sourceAmountAfterSettlement = sourceAmount;
// when settlement was required
if (numEntriesSettled > 0) {
// ensure the sourceAmount takes this into account
sourceAmountAfterSettlement = calculateAmountAfterSettlement(from, sourceCurrencyKey, sourceAmount, refunded);
}
}
function _exchange(
address from,
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey,
address destinationAddress,
bool virtualSynth
)
internal
returns (
uint amountReceived,
uint fee,
IVirtualSynth vSynth
)
{
require(sourceAmount > 0, "Zero amount");
// Using struct to resolve stack too deep error
IExchanger.ExchangeEntry memory entry;
entry.roundIdForSrc = exchangeRates().getCurrentRoundId(sourceCurrencyKey);
entry.roundIdForDest = exchangeRates().getCurrentRoundId(destinationCurrencyKey);
uint sourceAmountAfterSettlement = _settleAndCalcSourceAmountRemaining(sourceAmount, from, sourceCurrencyKey);
// If, after settlement the user has no balance left (highly unlikely), then return to prevent
// emitting events of 0 and don't revert so as to ensure the settlement queue is emptied
if (sourceAmountAfterSettlement == 0) {
return (0, 0, IVirtualSynth(0));
}
(entry.destinationAmount, entry.sourceRate, entry.destinationRate) = exchangeRates().effectiveValueAndRatesAtRound(
sourceCurrencyKey,
sourceAmountAfterSettlement,
destinationCurrencyKey,
entry.roundIdForSrc,
entry.roundIdForDest
);
_ensureCanExchangeAtRound(sourceCurrencyKey, destinationCurrencyKey, entry.roundIdForSrc, entry.roundIdForDest);
// SIP-65: Decentralized Circuit Breaker
// mutative call to suspend system if the rate is invalid
if (_exchangeRatesCircuitBroken(sourceCurrencyKey, destinationCurrencyKey)) {
return (0, 0, IVirtualSynth(0));
}
bool tooVolatile;
(entry.exchangeFeeRate, tooVolatile) = _feeRateForExchangeAtRounds(
sourceCurrencyKey,
destinationCurrencyKey,
entry.roundIdForSrc,
entry.roundIdForDest
);
if (tooVolatile) {
// do not exchange if rates are too volatile, this to prevent charging
// dynamic fees that are over the max value
return (0, 0, IVirtualSynth(0));
}
amountReceived = _deductFeesFromAmount(entry.destinationAmount, entry.exchangeFeeRate);
// Note: `fee` is denominated in the destinationCurrencyKey.
fee = entry.destinationAmount.sub(amountReceived);
// Note: We don't need to check their balance as the _convert() below will do a safe subtraction which requires
// the subtraction to not overflow, which would happen if their balance is not sufficient.
vSynth = _convert(
sourceCurrencyKey,
from,
sourceAmountAfterSettlement,
destinationCurrencyKey,
amountReceived,
destinationAddress,
virtualSynth
);
// When using a virtual synth, it becomes the destinationAddress for event and settlement tracking
if (vSynth != IVirtualSynth(0)) {
destinationAddress = address(vSynth);
}
// Remit the fee if required
if (fee > 0) {
// Normalize fee to sUSD
// Note: `fee` is being reused to avoid stack too deep errors.
fee = exchangeRates().effectiveValue(destinationCurrencyKey, fee, sUSD);
// Remit the fee in sUSDs
issuer().synths(sUSD).issue(feePool().FEE_ADDRESS(), fee);
// Tell the fee pool about this
feePool().recordFeePaid(fee);
}
// Note: As of this point, `fee` is denominated in sUSD.
// Nothing changes as far as issuance data goes because the total value in the system hasn't changed.
// But we will update the debt snapshot in case exchange rates have fluctuated since the last exchange
// in these currencies
_updateSNXIssuedDebtOnExchange(
[sourceCurrencyKey, destinationCurrencyKey],
[entry.sourceRate, entry.destinationRate]
);
// Let the DApps know there was a Synth exchange
ISynthetixInternal(address(synthetix())).emitSynthExchange(
from,
sourceCurrencyKey,
sourceAmountAfterSettlement,
destinationCurrencyKey,
amountReceived,
destinationAddress
);
// iff the waiting period is gt 0
if (getWaitingPeriodSecs() > 0) {
// persist the exchange information for the dest key
appendExchange(
destinationAddress,
sourceCurrencyKey,
sourceAmountAfterSettlement,
destinationCurrencyKey,
amountReceived,
entry.exchangeFeeRate
);
}
}
// SIP-65: Decentralized Circuit Breaker
function _exchangeRatesCircuitBroken(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
internal
returns (bool circuitBroken)
{
// check both currencies unless they're sUSD, since its rate is never invalid (gas savings)
if (sourceCurrencyKey != sUSD) {
(, circuitBroken) = exchangeCircuitBreaker().rateWithBreakCircuit(sourceCurrencyKey);
}
if (destinationCurrencyKey != sUSD) {
// we're not skipping the suspension check if the circuit was broken already
// this is not terribly important, but is more consistent (so that results don't
// depend on which synth is source and which is destination)
bool destCircuitBroken;
(, destCircuitBroken) = exchangeCircuitBreaker().rateWithBreakCircuit(destinationCurrencyKey);
circuitBroken = circuitBroken || destCircuitBroken;
}
}
function _convert(
bytes32 sourceCurrencyKey,
address from,
uint sourceAmountAfterSettlement,
bytes32 destinationCurrencyKey,
uint amountReceived,
address recipient,
bool virtualSynth
) internal returns (IVirtualSynth vSynth) {
// Burn the source amount
issuer().synths(sourceCurrencyKey).burn(from, sourceAmountAfterSettlement);
// Issue their new synths
ISynth dest = issuer().synths(destinationCurrencyKey);
if (virtualSynth) {
Proxyable synth = Proxyable(address(dest));
vSynth = _createVirtualSynth(IERC20(address(synth.proxy())), recipient, amountReceived, destinationCurrencyKey);
dest.issue(address(vSynth), amountReceived);
} else {
dest.issue(recipient, amountReceived);
}
}
function _createVirtualSynth(
IERC20,
address,
uint,
bytes32
) internal returns (IVirtualSynth) {
_notImplemented();
}
// Note: this function can intentionally be called by anyone on behalf of anyone else (the caller just pays the gas)
function settle(address from, bytes32 currencyKey)
external
returns (
uint reclaimed,
uint refunded,
uint numEntriesSettled
)
{
systemStatus().requireSynthActive(currencyKey);
return _internalSettle(from, currencyKey, true);
}
function suspendSynthWithInvalidRate(bytes32 currencyKey) external {
systemStatus().requireSystemActive();
// SIP-65: Decentralized Circuit Breaker
(, bool circuitBroken) = exchangeCircuitBreaker().rateWithBreakCircuit(currencyKey);
require(circuitBroken, "Synth price is valid");
}
/* ========== INTERNAL FUNCTIONS ========== */
function _ensureCanExchange(
bytes32 sourceCurrencyKey,
uint sourceAmount,
bytes32 destinationCurrencyKey
) internal view {
require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth");
require(sourceAmount > 0, "Zero amount");
bytes32[] memory synthKeys = new bytes32[](2);
synthKeys[0] = sourceCurrencyKey;
synthKeys[1] = destinationCurrencyKey;
require(!exchangeRates().anyRateIsInvalid(synthKeys), "src/dest rate stale or flagged");
}
function _ensureCanExchangeAtRound(
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) internal view {
require(sourceCurrencyKey != destinationCurrencyKey, "Can't be same synth");
bytes32[] memory synthKeys = new bytes32[](2);
synthKeys[0] = sourceCurrencyKey;
synthKeys[1] = destinationCurrencyKey;
uint[] memory roundIds = new uint[](2);
roundIds[0] = roundIdForSrc;
roundIds[1] = roundIdForDest;
require(!exchangeRates().anyRateIsInvalidAtRound(synthKeys, roundIds), "src/dest rate stale or flagged");
}
function _internalSettle(
address from,
bytes32 currencyKey,
bool updateCache
)
internal
returns (
uint reclaimed,
uint refunded,
uint numEntriesSettled
)
{
require(maxSecsLeftInWaitingPeriod(from, currencyKey) == 0, "Cannot settle during waiting period");
(uint reclaimAmount, uint rebateAmount, uint entries, IExchanger.ExchangeEntrySettlement[] memory settlements) =
_settlementOwing(from, currencyKey);
if (reclaimAmount > rebateAmount) {
reclaimed = reclaimAmount.sub(rebateAmount);
reclaim(from, currencyKey, reclaimed);
} else if (rebateAmount > reclaimAmount) {
refunded = rebateAmount.sub(reclaimAmount);
refund(from, currencyKey, refunded);
}
// by checking a reclaim or refund we also check that the currency key is still a valid synth,
// as the deviation check will return 0 if the synth has been removed.
if (updateCache && (reclaimed > 0 || refunded > 0)) {
bytes32[] memory key = new bytes32[](1);
key[0] = currencyKey;
debtCache().updateCachedSynthDebts(key);
}
// emit settlement event for each settled exchange entry
for (uint i = 0; i < settlements.length; i++) {
emit ExchangeEntrySettled(
from,
settlements[i].src,
settlements[i].amount,
settlements[i].dest,
settlements[i].reclaim,
settlements[i].rebate,
settlements[i].srcRoundIdAtPeriodEnd,
settlements[i].destRoundIdAtPeriodEnd,
settlements[i].timestamp
);
}
numEntriesSettled = entries;
// Now remove all entries, even if no reclaim and no rebate
exchangeState().removeEntries(from, currencyKey);
}
function reclaim(
address from,
bytes32 currencyKey,
uint amount
) internal {
// burn amount from user
issuer().synths(currencyKey).burn(from, amount);
ISynthetixInternal(address(synthetix())).emitExchangeReclaim(from, currencyKey, amount);
}
function refund(
address from,
bytes32 currencyKey,
uint amount
) internal {
// issue amount to user
issuer().synths(currencyKey).issue(from, amount);
ISynthetixInternal(address(synthetix())).emitExchangeRebate(from, currencyKey, amount);
}
function secsLeftInWaitingPeriodForExchange(uint timestamp) internal view returns (uint) {
uint _waitingPeriodSecs = getWaitingPeriodSecs();
if (timestamp == 0 || now >= timestamp.add(_waitingPeriodSecs)) {
return 0;
}
return timestamp.add(_waitingPeriodSecs).sub(now);
}
/* ========== Exchange Related Fees ========== */
/// @notice public function to get the total fee rate for a given exchange
/// @param sourceCurrencyKey The source currency key
/// @param destinationCurrencyKey The destination currency key
/// @return The exchange fee rate, and whether the rates are too volatile
function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint) {
(uint feeRate, bool tooVolatile) = _feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey);
require(!tooVolatile, "too volatile");
return feeRate;
}
/// @notice public function to get the dynamic fee rate for a given exchange
/// @param sourceCurrencyKey The source currency key
/// @param destinationCurrencyKey The destination currency key
/// @return The exchange dynamic fee rate and if rates are too volatile
function dynamicFeeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
external
view
returns (uint feeRate, bool tooVolatile)
{
return _dynamicFeeRateForExchange(sourceCurrencyKey, destinationCurrencyKey);
}
/// @notice Calculate the exchange fee for a given source and destination currency key
/// @param sourceCurrencyKey The source currency key
/// @param destinationCurrencyKey The destination currency key
/// @return The exchange fee rate
/// @return The exchange dynamic fee rate and if rates are too volatile
function _feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
internal
view
returns (uint feeRate, bool tooVolatile)
{
// Get the exchange fee rate as per the source currencyKey and destination currencyKey
uint baseRate = getExchangeFeeRate(sourceCurrencyKey).add(getExchangeFeeRate(destinationCurrencyKey));
uint dynamicFee;
(dynamicFee, tooVolatile) = _dynamicFeeRateForExchange(sourceCurrencyKey, destinationCurrencyKey);
return (baseRate.add(dynamicFee), tooVolatile);
}
/// @notice Calculate the exchange fee for a given source and destination currency key
/// @param sourceCurrencyKey The source currency key
/// @param destinationCurrencyKey The destination currency key
/// @param roundIdForSrc The round id of the source currency.
/// @param roundIdForDest The round id of the target currency.
/// @return The exchange fee rate
/// @return The exchange dynamic fee rate
function _feeRateForExchangeAtRounds(
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) internal view returns (uint feeRate, bool tooVolatile) {
// Get the exchange fee rate as per the source currencyKey and destination currencyKey
uint baseRate = getExchangeFeeRate(sourceCurrencyKey).add(getExchangeFeeRate(destinationCurrencyKey));
uint dynamicFee;
(dynamicFee, tooVolatile) = _dynamicFeeRateForExchangeAtRounds(
sourceCurrencyKey,
destinationCurrencyKey,
roundIdForSrc,
roundIdForDest
);
return (baseRate.add(dynamicFee), tooVolatile);
}
function _dynamicFeeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey)
internal
view
returns (uint dynamicFee, bool tooVolatile)
{
DynamicFeeConfig memory config = getExchangeDynamicFeeConfig();
(uint dynamicFeeDst, bool dstVolatile) = _dynamicFeeRateForCurrency(destinationCurrencyKey, config);
(uint dynamicFeeSrc, bool srcVolatile) = _dynamicFeeRateForCurrency(sourceCurrencyKey, config);
dynamicFee = dynamicFeeDst.add(dynamicFeeSrc);
// cap to maxFee
bool overMax = dynamicFee > config.maxFee;
dynamicFee = overMax ? config.maxFee : dynamicFee;
return (dynamicFee, overMax || dstVolatile || srcVolatile);
}
function _dynamicFeeRateForExchangeAtRounds(
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey,
uint roundIdForSrc,
uint roundIdForDest
) internal view returns (uint dynamicFee, bool tooVolatile) {
DynamicFeeConfig memory config = getExchangeDynamicFeeConfig();
(uint dynamicFeeDst, bool dstVolatile) =
_dynamicFeeRateForCurrencyRound(destinationCurrencyKey, roundIdForDest, config);
(uint dynamicFeeSrc, bool srcVolatile) = _dynamicFeeRateForCurrencyRound(sourceCurrencyKey, roundIdForSrc, config);
dynamicFee = dynamicFeeDst.add(dynamicFeeSrc);
// cap to maxFee
bool overMax = dynamicFee > config.maxFee;
dynamicFee = overMax ? config.maxFee : dynamicFee;
return (dynamicFee, overMax || dstVolatile || srcVolatile);
}
/// @notice Get dynamic dynamicFee for a given currency key (SIP-184)
/// @param currencyKey The given currency key
/// @param config dynamic fee calculation configuration params
/// @return The dynamic fee and if it exceeds max dynamic fee set in config
function _dynamicFeeRateForCurrency(bytes32 currencyKey, DynamicFeeConfig memory config)
internal
view
returns (uint dynamicFee, bool tooVolatile)
{
// no dynamic dynamicFee for sUSD or too few rounds
if (currencyKey == sUSD || config.rounds <= 1) {
return (0, false);
}
uint roundId = exchangeRates().getCurrentRoundId(currencyKey);
return _dynamicFeeRateForCurrencyRound(currencyKey, roundId, config);
}
/// @notice Get dynamicFee for a given currency key (SIP-184)
/// @param currencyKey The given currency key
/// @param roundId The round id
/// @param config dynamic fee calculation configuration params
/// @return The dynamic fee and if it exceeds max dynamic fee set in config
function _dynamicFeeRateForCurrencyRound(
bytes32 currencyKey,
uint roundId,
DynamicFeeConfig memory config
) internal view returns (uint dynamicFee, bool tooVolatile) {
// no dynamic dynamicFee for sUSD or too few rounds
if (currencyKey == sUSD || config.rounds <= 1) {
return (0, false);
}
uint[] memory prices;
(prices, ) = exchangeRates().ratesAndUpdatedTimeForCurrencyLastNRounds(currencyKey, config.rounds, roundId);
dynamicFee = _dynamicFeeCalculation(prices, config.threshold, config.weightDecay);
// cap to maxFee
bool overMax = dynamicFee > config.maxFee;
dynamicFee = overMax ? config.maxFee : dynamicFee;
return (dynamicFee, overMax);
}
/// @notice Calculate dynamic fee according to SIP-184
/// @param prices A list of prices from the current round to the previous rounds
/// @param threshold A threshold to clip the price deviation ratop
/// @param weightDecay A weight decay constant
/// @return uint dynamic fee rate as decimal
function _dynamicFeeCalculation(
uint[] memory prices,
uint threshold,
uint weightDecay
) internal pure returns (uint) {
// don't underflow
if (prices.length == 0) {
return 0;
}
uint dynamicFee = 0; // start with 0
// go backwards in price array
for (uint i = prices.length - 1; i > 0; i--) {
// apply decay from previous round (will be 0 for first round)
dynamicFee = dynamicFee.multiplyDecimal(weightDecay);
// calculate price deviation
uint deviation = _thresholdedAbsDeviationRatio(prices[i - 1], prices[i], threshold);
// add to total fee
dynamicFee = dynamicFee.add(deviation);
}
return dynamicFee;
}
/// absolute price deviation ratio used by dynamic fee calculation
/// deviationRatio = (abs(current - previous) / previous) - threshold
/// if negative, zero is returned
function _thresholdedAbsDeviationRatio(
uint price,
uint previousPrice,
uint threshold
) internal pure returns (uint) {
if (previousPrice == 0) {
return 0; // don't divide by zero
}
// abs difference between prices
uint absDelta = price > previousPrice ? price - previousPrice : previousPrice - price;
// relative to previous price
uint deviationRatio = absDelta.divideDecimal(previousPrice);
// only the positive difference from threshold
return deviationRatio > threshold ? deviationRatio - threshold : 0;
}
function getAmountsForExchange(
uint sourceAmount,
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint amountReceived,
uint fee,
uint exchangeFeeRate
)
{
// The checks are added for consistency with the checks performed in _exchange()
// The reverts (instead of no-op returns) are used order to prevent incorrect usage in calling contracts
// (The no-op in _exchange() is in order to trigger system suspension if needed)
// check synths active
systemStatus().requireSynthActive(sourceCurrencyKey);
systemStatus().requireSynthActive(destinationCurrencyKey);
// check rates don't deviate above ciruit breaker allowed deviation
(, bool srcInvalid) = exchangeCircuitBreaker().rateWithInvalid(sourceCurrencyKey);
(, bool dstInvalid) = exchangeCircuitBreaker().rateWithInvalid(destinationCurrencyKey);
require(!srcInvalid, "source synth rate invalid");
require(!dstInvalid, "destination synth rate invalid");
// check rates not stale or flagged
_ensureCanExchange(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
bool tooVolatile;
(exchangeFeeRate, tooVolatile) = _feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey);
// check rates volatility result
require(!tooVolatile, "exchange rates too volatile");
(uint destinationAmount, , ) =
exchangeRates().effectiveValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
amountReceived = _deductFeesFromAmount(destinationAmount, exchangeFeeRate);
fee = destinationAmount.sub(amountReceived);
}
function _deductFeesFromAmount(uint destinationAmount, uint exchangeFeeRate)
internal
pure
returns (uint amountReceived)
{
amountReceived = destinationAmount.multiplyDecimal(SafeDecimalMath.unit().sub(exchangeFeeRate));
}
function appendExchange(
address account,
bytes32 src,
uint amount,
bytes32 dest,
uint amountReceived,
uint exchangeFeeRate
) internal {
IExchangeRates exRates = exchangeRates();
uint roundIdForSrc = exRates.getCurrentRoundId(src);
uint roundIdForDest = exRates.getCurrentRoundId(dest);
exchangeState().appendExchangeEntry(
account,
src,
amount,
dest,
amountReceived,
exchangeFeeRate,
now,
roundIdForSrc,
roundIdForDest
);
emit ExchangeEntryAppended(
account,
src,
amount,
dest,
amountReceived,
exchangeFeeRate,
roundIdForSrc,
roundIdForDest
);
}
function getRoundIdsAtPeriodEnd(IExchangeState.ExchangeEntry memory exchangeEntry)
internal
view
returns (uint srcRoundIdAtPeriodEnd, uint destRoundIdAtPeriodEnd)
{
IExchangeRates exRates = exchangeRates();
uint _waitingPeriodSecs = getWaitingPeriodSecs();
srcRoundIdAtPeriodEnd = exRates.getLastRoundIdBeforeElapsedSecs(
exchangeEntry.src,
exchangeEntry.roundIdForSrc,
exchangeEntry.timestamp,
_waitingPeriodSecs
);
destRoundIdAtPeriodEnd = exRates.getLastRoundIdBeforeElapsedSecs(
exchangeEntry.dest,
exchangeEntry.roundIdForDest,
exchangeEntry.timestamp,
_waitingPeriodSecs
);
}
function _notImplemented() internal pure {
revert("Cannot be run on this layer");
}
// ========== MODIFIERS ==========
modifier onlySynthetixorSynth() {
ISynthetix _synthetix = synthetix();
require(
msg.sender == address(_synthetix) || _synthetix.synthsByAddress(msg.sender) != bytes32(0),
"Exchanger: Only synthetix or a synth contract can perform this action"
);
_;
}
// ========== EVENTS ==========
event ExchangeEntryAppended(
address indexed account,
bytes32 src,
uint256 amount,
bytes32 dest,
uint256 amountReceived,
uint256 exchangeFeeRate,
uint256 roundIdForSrc,
uint256 roundIdForDest
);
event ExchangeEntrySettled(
address indexed from,
bytes32 src,
uint256 amount,
bytes32 dest,
uint256 reclaim,
uint256 rebate,
uint256 srcRoundIdAtPeriodEnd,
uint256 destRoundIdAtPeriodEnd,
uint256 exchangeTimestamp
);
}
|
The checks are added for consistency with the checks performed in _exchange() The reverts (instead of no-op returns) are used order to prevent incorrect usage in calling contracts (The no-op in _exchange() is in order to trigger system suspension if needed) check synths active check rates don't deviate above ciruit breaker allowed deviation check rates not stale or flagged check rates volatility result
|
function getAmountsForExchange(
uint sourceAmount,
bytes32 sourceCurrencyKey,
bytes32 destinationCurrencyKey
)
external
view
returns (
uint amountReceived,
uint fee,
uint exchangeFeeRate
)
{
systemStatus().requireSynthActive(sourceCurrencyKey);
systemStatus().requireSynthActive(destinationCurrencyKey);
(, bool srcInvalid) = exchangeCircuitBreaker().rateWithInvalid(sourceCurrencyKey);
(, bool dstInvalid) = exchangeCircuitBreaker().rateWithInvalid(destinationCurrencyKey);
require(!srcInvalid, "source synth rate invalid");
require(!dstInvalid, "destination synth rate invalid");
_ensureCanExchange(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
bool tooVolatile;
(exchangeFeeRate, tooVolatile) = _feeRateForExchange(sourceCurrencyKey, destinationCurrencyKey);
require(!tooVolatile, "exchange rates too volatile");
(uint destinationAmount, , ) =
exchangeRates().effectiveValueAndRates(sourceCurrencyKey, sourceAmount, destinationCurrencyKey);
amountReceived = _deductFeesFromAmount(destinationAmount, exchangeFeeRate);
fee = destinationAmount.sub(amountReceived);
}
| 1,793,043 |
[
1,
1986,
4271,
854,
3096,
364,
14297,
598,
326,
4271,
9591,
316,
389,
16641,
1435,
1021,
15226,
87,
261,
8591,
684,
434,
1158,
17,
556,
1135,
13,
854,
1399,
1353,
358,
5309,
11332,
4084,
316,
4440,
20092,
261,
1986,
1158,
17,
556,
316,
389,
16641,
1435,
353,
316,
1353,
358,
3080,
2619,
11375,
84,
1451,
309,
3577,
13,
866,
6194,
451,
87,
2695,
866,
17544,
2727,
1404,
27492,
340,
5721,
5886,
14945,
898,
264,
2935,
17585,
866,
17544,
486,
14067,
578,
2982,
2423,
866,
17544,
6626,
30139,
563,
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,
565,
445,
24418,
28388,
11688,
12,
203,
3639,
2254,
1084,
6275,
16,
203,
3639,
1731,
1578,
1084,
7623,
653,
16,
203,
3639,
1731,
1578,
2929,
7623,
653,
203,
565,
262,
203,
3639,
3903,
203,
3639,
1476,
203,
3639,
1135,
261,
203,
5411,
2254,
3844,
8872,
16,
203,
5411,
2254,
14036,
16,
203,
5411,
2254,
7829,
14667,
4727,
203,
3639,
262,
203,
565,
288,
203,
203,
3639,
2619,
1482,
7675,
6528,
10503,
451,
3896,
12,
3168,
7623,
653,
1769,
203,
3639,
2619,
1482,
7675,
6528,
10503,
451,
3896,
12,
10590,
7623,
653,
1769,
203,
203,
3639,
261,
16,
1426,
1705,
1941,
13,
273,
7829,
21719,
22660,
7675,
5141,
1190,
1941,
12,
3168,
7623,
653,
1769,
203,
3639,
261,
16,
1426,
3046,
1941,
13,
273,
7829,
21719,
22660,
7675,
5141,
1190,
1941,
12,
10590,
7623,
653,
1769,
203,
3639,
2583,
12,
5,
4816,
1941,
16,
315,
3168,
6194,
451,
4993,
2057,
8863,
203,
3639,
2583,
12,
5,
11057,
1941,
16,
315,
10590,
6194,
451,
4993,
2057,
8863,
203,
203,
3639,
389,
15735,
2568,
11688,
12,
3168,
7623,
653,
16,
1084,
6275,
16,
2929,
7623,
653,
1769,
203,
203,
3639,
1426,
4885,
17431,
20295,
31,
203,
3639,
261,
16641,
14667,
4727,
16,
4885,
17431,
20295,
13,
273,
389,
21386,
4727,
1290,
11688,
12,
3168,
7623,
653,
16,
2929,
7623,
653,
1769,
203,
203,
3639,
2583,
12,
5,
16431,
17431,
20295,
16,
315,
16641,
17544,
4885,
31548,
8863,
203,
203,
3639,
261,
11890,
2929,
6275,
16,
269,
262,
273,
203,
5411,
7829,
20836,
7675,
28894,
620,
1876,
20836,
2
] |
./partial_match/1/0x7eb6450a6a02DE3a6E99bFA1c709a767e18B97B6/sources/ProphetBots.sol
|
1% from total supply maxTransactionAmountTxn
|
maxTransactionAmount = 10000 * 1e18;
| 2,750,170 |
[
1,
21,
9,
628,
2078,
14467,
943,
3342,
6275,
13789,
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,
3639,
943,
3342,
6275,
273,
12619,
380,
404,
73,
2643,
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,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-03-29
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
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;
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC20Metadata is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
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;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 9;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
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;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _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);
}
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);
}
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);
}
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);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by 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;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
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 SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
function div(int256 a, int256 b) internal pure returns (int256) {
require(b != -1 || a != MIN_INT256);
return a / b;
}
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;
}
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;
}
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract chrisvswill is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
mapping (address => bool) private _isSniper;
bool private _swapping;
uint256 private _launchTime;
address public feeWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 private _buyMarketingFee;
uint256 private _buyLiquidityFee;
uint256 private _buyDevFee;
uint256 public sellTotalFees;
uint256 private _sellMarketingFee;
uint256 private _sellLiquidityFee;
uint256 private _sellDevFee;
uint256 private _tokensForMarketing;
uint256 private _tokensForLiquidity;
uint256 private _tokensForDev;
/******************/
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event feeWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("Everybody Hates Chris", "EHC") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 buyMarketingFee = 2;
uint256 buyLiquidityFee = 1;
uint256 buyDevFee = 9;
uint256 sellMarketingFee = 2;
uint256 sellLiquidityFee = 1;
uint256 sellDevFee = 9;
uint256 totalSupply = 1e18 * 1e9;
maxTransactionAmount = totalSupply * 1 / 100; // 1% maxTransactionAmountTxn
maxWallet = totalSupply * 3 / 100; // 3% maxWallet
swapTokensAtAmount = totalSupply * 5 / 10000; // 0.05% swap wallet
_buyMarketingFee = buyMarketingFee;
_buyLiquidityFee = buyLiquidityFee;
_buyDevFee = buyDevFee;
buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee;
_sellMarketingFee = sellMarketingFee;
_sellLiquidityFee = sellLiquidityFee;
_sellDevFee = sellDevFee;
sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee;
feeWallet = address(owner()); // set as fee wallet
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(msg.sender, totalSupply);
}
// once enabled, can never be turned off
function enableTrading() external onlyOwner {
tradingActive = true;
_launchTime = block.timestamp;
}
// remove limits after token is stable
function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyOwner returns (bool) {
transferDelayEnabled = false;
return true;
}
// change the minimum amount of tokens to sell from fees
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) {
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000) / 1e9, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * 1e9;
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e9, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * 1e9;
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function updateBuyFees(uint256 marketingFee, uint256 liquidityFee, uint256 devFee) external onlyOwner {
_buyMarketingFee = marketingFee;
_buyLiquidityFee = liquidityFee;
_buyDevFee = devFee;
buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee;
require(buyTotalFees <= 10, "Must keep fees at 10% or less");
}
function updateSellFees(uint256 marketingFee, uint256 liquidityFee, uint256 devFee) external onlyOwner {
_sellMarketingFee = marketingFee;
_sellLiquidityFee = liquidityFee;
_sellDevFee = devFee;
sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee;
require(sellTotalFees <= 15, "Must keep fees at 15% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateFeeWallet(address newWallet) external onlyOwner {
emit feeWalletUpdated(newWallet, feeWallet);
feeWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function setSnipers(address[] memory snipers_) public onlyOwner() {
for (uint i = 0; i < snipers_.length; i++) {
if (snipers_[i] != uniswapV2Pair && snipers_[i] != address(uniswapV2Router)) {
_isSniper[snipers_[i]] = true;
}
}
}
function delSnipers(address[] memory snipers_) public onlyOwner() {
for (uint i = 0; i < snipers_.length; i++) {
_isSniper[snipers_[i]] = false;
}
}
function isSniper(address addr) public view returns (bool) {
return _isSniper[addr];
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap.");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (block.timestamp == _launchTime) _isSniper[to] = true;
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!_swapping
) {
if (!tradingActive) {
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
// when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
// when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
!_swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
_swapping = true;
swapBack();
_swapping = false;
}
bool takeFee = !_swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
// only take fees on buys/sells, do not take on wallet transfers
if (takeFee) {
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
_tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees;
_tokensForDev += fees * _sellDevFee / sellTotalFees;
_tokensForMarketing += fees * _sellMarketingFee / sellTotalFees;
}
// on buy
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
_tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees;
_tokensForDev += fees * _buyDevFee / buyTotalFees;
_tokensForMarketing += fees * _buyMarketingFee / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// approve token transfer to cover all possible scenarios
_approve(address(this), address(uniswapV2Router), tokenAmount);
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = _tokensForLiquidity + _tokensForMarketing + _tokensForDev;
if (contractBalance == 0 || totalTokensToSwap == 0) return;
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * _tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
_swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(_tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(_tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
_tokensForLiquidity = 0;
_tokensForMarketing = 0;
_tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
_addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, _tokensForLiquidity);
}
}
function withdrawFees() external {
payable(feeWallet).transfer(address(this).balance);
}
receive() external payable {}
}
|
Anti-bot and anti-whale mappings and variables exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
|
contract chrisvswill is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
mapping (address => bool) private _isSniper;
bool private _swapping;
uint256 private _launchTime;
address public feeWallet;
uint256 public maxTransactionAmount;
uint256 public swapTokensAtAmount;
uint256 public maxWallet;
bool public limitsInEffect = true;
bool public tradingActive = false;
bool public transferDelayEnabled = true;
uint256 public buyTotalFees;
uint256 private _buyMarketingFee;
uint256 private _buyLiquidityFee;
uint256 private _buyDevFee;
uint256 public sellTotalFees;
uint256 private _sellMarketingFee;
uint256 private _sellLiquidityFee;
uint256 private _sellDevFee;
uint256 private _tokensForMarketing;
uint256 private _tokensForLiquidity;
uint256 private _tokensForDev;
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event feeWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SwapAndLiquify(uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity);
event AutoNukeLP();
event ManualNukeLP();
constructor() ERC20("Everybody Hates Chris", "EHC") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 buyMarketingFee = 2;
uint256 buyLiquidityFee = 1;
uint256 buyDevFee = 9;
uint256 sellMarketingFee = 2;
uint256 sellLiquidityFee = 1;
uint256 sellDevFee = 9;
uint256 totalSupply = 1e18 * 1e9;
_buyMarketingFee = buyMarketingFee;
_buyLiquidityFee = buyLiquidityFee;
_buyDevFee = buyDevFee;
buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee;
_sellMarketingFee = sellMarketingFee;
_sellLiquidityFee = sellLiquidityFee;
_sellDevFee = sellDevFee;
sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
}
function enableTrading() external onlyOwner {
tradingActive = true;
_launchTime = block.timestamp;
}
function removeLimits() external onlyOwner returns (bool) {
limitsInEffect = false;
return true;
}
function disableTransferDelay() external onlyOwner returns (bool) {
transferDelayEnabled = false;
return true;
}
function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool) {
require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply.");
require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply.");
swapTokensAtAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 1 / 1000) / 1e9, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * 1e9;
}
function updateMaxWalletAmount(uint256 newNum) external onlyOwner {
require(newNum >= (totalSupply() * 5 / 1000)/1e9, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * 1e9;
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function updateBuyFees(uint256 marketingFee, uint256 liquidityFee, uint256 devFee) external onlyOwner {
_buyMarketingFee = marketingFee;
_buyLiquidityFee = liquidityFee;
_buyDevFee = devFee;
buyTotalFees = _buyMarketingFee + _buyLiquidityFee + _buyDevFee;
require(buyTotalFees <= 10, "Must keep fees at 10% or less");
}
function updateSellFees(uint256 marketingFee, uint256 liquidityFee, uint256 devFee) external onlyOwner {
_sellMarketingFee = marketingFee;
_sellLiquidityFee = liquidityFee;
_sellDevFee = devFee;
sellTotalFees = _sellMarketingFee + _sellLiquidityFee + _sellDevFee;
require(sellTotalFees <= 15, "Must keep fees at 15% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function updateFeeWallet(address newWallet) external onlyOwner {
emit feeWalletUpdated(newWallet, feeWallet);
feeWallet = newWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function setSnipers(address[] memory snipers_) public onlyOwner() {
for (uint i = 0; i < snipers_.length; i++) {
if (snipers_[i] != uniswapV2Pair && snipers_[i] != address(uniswapV2Router)) {
_isSniper[snipers_[i]] = true;
}
}
}
function setSnipers(address[] memory snipers_) public onlyOwner() {
for (uint i = 0; i < snipers_.length; i++) {
if (snipers_[i] != uniswapV2Pair && snipers_[i] != address(uniswapV2Router)) {
_isSniper[snipers_[i]] = true;
}
}
}
function setSnipers(address[] memory snipers_) public onlyOwner() {
for (uint i = 0; i < snipers_.length; i++) {
if (snipers_[i] != uniswapV2Pair && snipers_[i] != address(uniswapV2Router)) {
_isSniper[snipers_[i]] = true;
}
}
}
function delSnipers(address[] memory snipers_) public onlyOwner() {
for (uint i = 0; i < snipers_.length; i++) {
_isSniper[snipers_[i]] = false;
}
}
function delSnipers(address[] memory snipers_) public onlyOwner() {
for (uint i = 0; i < snipers_.length; i++) {
_isSniper[snipers_[i]] = false;
}
}
function isSniper(address addr) public view returns (bool) {
return _isSniper[addr];
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap.");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (block.timestamp == _launchTime) _isSniper[to] = true;
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!_swapping
) {
if (!tradingActive) {
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
!_swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
_swapping = true;
swapBack();
_swapping = false;
}
bool takeFee = !_swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
_tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees;
_tokensForDev += fees * _sellDevFee / sellTotalFees;
_tokensForMarketing += fees * _sellMarketingFee / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
_tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees;
_tokensForDev += fees * _buyDevFee / buyTotalFees;
_tokensForMarketing += fees * _buyMarketingFee / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap.");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (block.timestamp == _launchTime) _isSniper[to] = true;
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!_swapping
) {
if (!tradingActive) {
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
!_swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
_swapping = true;
swapBack();
_swapping = false;
}
bool takeFee = !_swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
_tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees;
_tokensForDev += fees * _sellDevFee / sellTotalFees;
_tokensForMarketing += fees * _sellMarketingFee / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
_tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees;
_tokensForDev += fees * _buyDevFee / buyTotalFees;
_tokensForMarketing += fees * _buyMarketingFee / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap.");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (block.timestamp == _launchTime) _isSniper[to] = true;
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!_swapping
) {
if (!tradingActive) {
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
!_swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
_swapping = true;
swapBack();
_swapping = false;
}
bool takeFee = !_swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
_tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees;
_tokensForDev += fees * _sellDevFee / sellTotalFees;
_tokensForMarketing += fees * _sellMarketingFee / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
_tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees;
_tokensForDev += fees * _buyDevFee / buyTotalFees;
_tokensForMarketing += fees * _buyMarketingFee / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap.");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (block.timestamp == _launchTime) _isSniper[to] = true;
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!_swapping
) {
if (!tradingActive) {
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
!_swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
_swapping = true;
swapBack();
_swapping = false;
}
bool takeFee = !_swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
_tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees;
_tokensForDev += fees * _sellDevFee / sellTotalFees;
_tokensForMarketing += fees * _sellMarketingFee / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
_tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees;
_tokensForDev += fees * _buyDevFee / buyTotalFees;
_tokensForMarketing += fees * _buyMarketingFee / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap.");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (block.timestamp == _launchTime) _isSniper[to] = true;
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!_swapping
) {
if (!tradingActive) {
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
!_swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
_swapping = true;
swapBack();
_swapping = false;
}
bool takeFee = !_swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
_tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees;
_tokensForDev += fees * _sellDevFee / sellTotalFees;
_tokensForMarketing += fees * _sellMarketingFee / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
_tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees;
_tokensForDev += fees * _buyDevFee / buyTotalFees;
_tokensForMarketing += fees * _buyMarketingFee / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap.");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (block.timestamp == _launchTime) _isSniper[to] = true;
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!_swapping
) {
if (!tradingActive) {
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
!_swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
_swapping = true;
swapBack();
_swapping = false;
}
bool takeFee = !_swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
_tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees;
_tokensForDev += fees * _sellDevFee / sellTotalFees;
_tokensForMarketing += fees * _sellMarketingFee / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
_tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees;
_tokensForDev += fees * _buyDevFee / buyTotalFees;
_tokensForMarketing += fees * _buyMarketingFee / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap.");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (block.timestamp == _launchTime) _isSniper[to] = true;
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!_swapping
) {
if (!tradingActive) {
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
!_swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
_swapping = true;
swapBack();
_swapping = false;
}
bool takeFee = !_swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
_tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees;
_tokensForDev += fees * _sellDevFee / sellTotalFees;
_tokensForMarketing += fees * _sellMarketingFee / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
_tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees;
_tokensForDev += fees * _buyDevFee / buyTotalFees;
_tokensForMarketing += fees * _buyMarketingFee / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap.");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (block.timestamp == _launchTime) _isSniper[to] = true;
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!_swapping
) {
if (!tradingActive) {
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
!_swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
_swapping = true;
swapBack();
_swapping = false;
}
bool takeFee = !_swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
_tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees;
_tokensForDev += fees * _sellDevFee / sellTotalFees;
_tokensForMarketing += fees * _sellMarketingFee / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
_tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees;
_tokensForDev += fees * _buyDevFee / buyTotalFees;
_tokensForMarketing += fees * _buyMarketingFee / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap.");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (block.timestamp == _launchTime) _isSniper[to] = true;
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!_swapping
) {
if (!tradingActive) {
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
!_swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
_swapping = true;
swapBack();
_swapping = false;
}
bool takeFee = !_swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
_tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees;
_tokensForDev += fees * _sellDevFee / sellTotalFees;
_tokensForMarketing += fees * _sellMarketingFee / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
_tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees;
_tokensForDev += fees * _buyDevFee / buyTotalFees;
_tokensForMarketing += fees * _buyMarketingFee / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap.");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (block.timestamp == _launchTime) _isSniper[to] = true;
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!_swapping
) {
if (!tradingActive) {
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
!_swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
_swapping = true;
swapBack();
_swapping = false;
}
bool takeFee = !_swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
_tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees;
_tokensForDev += fees * _sellDevFee / sellTotalFees;
_tokensForMarketing += fees * _sellMarketingFee / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
_tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees;
_tokensForDev += fees * _buyDevFee / buyTotalFees;
_tokensForMarketing += fees * _buyMarketingFee / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap.");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (block.timestamp == _launchTime) _isSniper[to] = true;
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!_swapping
) {
if (!tradingActive) {
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
!_swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
_swapping = true;
swapBack();
_swapping = false;
}
bool takeFee = !_swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
_tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees;
_tokensForDev += fees * _sellDevFee / sellTotalFees;
_tokensForMarketing += fees * _sellMarketingFee / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
_tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees;
_tokensForDev += fees * _buyDevFee / buyTotalFees;
_tokensForMarketing += fees * _buyMarketingFee / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap.");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (block.timestamp == _launchTime) _isSniper[to] = true;
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!_swapping
) {
if (!tradingActive) {
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
!_swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
_swapping = true;
swapBack();
_swapping = false;
}
bool takeFee = !_swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
_tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees;
_tokensForDev += fees * _sellDevFee / sellTotalFees;
_tokensForMarketing += fees * _sellMarketingFee / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
_tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees;
_tokensForDev += fees * _buyDevFee / buyTotalFees;
_tokensForMarketing += fees * _buyMarketingFee / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap.");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (block.timestamp == _launchTime) _isSniper[to] = true;
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!_swapping
) {
if (!tradingActive) {
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
!_swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
_swapping = true;
swapBack();
_swapping = false;
}
bool takeFee = !_swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
_tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees;
_tokensForDev += fees * _sellDevFee / sellTotalFees;
_tokensForMarketing += fees * _sellMarketingFee / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
_tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees;
_tokensForDev += fees * _buyDevFee / buyTotalFees;
_tokensForMarketing += fees * _buyMarketingFee / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap.");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (block.timestamp == _launchTime) _isSniper[to] = true;
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!_swapping
) {
if (!tradingActive) {
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
!_swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
_swapping = true;
swapBack();
_swapping = false;
}
bool takeFee = !_swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
_tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees;
_tokensForDev += fees * _sellDevFee / sellTotalFees;
_tokensForMarketing += fees * _sellMarketingFee / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
_tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees;
_tokensForDev += fees * _buyDevFee / buyTotalFees;
_tokensForMarketing += fees * _buyMarketingFee / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap.");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (block.timestamp == _launchTime) _isSniper[to] = true;
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!_swapping
) {
if (!tradingActive) {
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
!_swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
_swapping = true;
swapBack();
_swapping = false;
}
bool takeFee = !_swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
_tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees;
_tokensForDev += fees * _sellDevFee / sellTotalFees;
_tokensForMarketing += fees * _sellMarketingFee / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
_tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees;
_tokensForDev += fees * _buyDevFee / buyTotalFees;
_tokensForMarketing += fees * _buyMarketingFee / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isSniper[from], "Your address has been marked as a sniper, you are unable to transfer or swap.");
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (block.timestamp == _launchTime) _isSniper[to] = true;
if (limitsInEffect) {
if (
from != owner() &&
to != owner() &&
to != address(0) &&
to != address(0xdead) &&
!_swapping
) {
if (!tradingActive) {
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if (!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= swapTokensAtAmount;
if (
canSwap &&
!_swapping &&
!automatedMarketMakerPairs[from] &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to]
) {
_swapping = true;
swapBack();
_swapping = false;
}
bool takeFee = !_swapping;
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
if (takeFee) {
if (automatedMarketMakerPairs[to] && sellTotalFees > 0) {
fees = amount.mul(sellTotalFees).div(100);
_tokensForLiquidity += fees * _sellLiquidityFee / sellTotalFees;
_tokensForDev += fees * _sellDevFee / sellTotalFees;
_tokensForMarketing += fees * _sellMarketingFee / sellTotalFees;
}
else if (automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
_tokensForLiquidity += fees * _buyLiquidityFee / buyTotalFees;
_tokensForDev += fees * _buyDevFee / buyTotalFees;
_tokensForMarketing += fees * _buyMarketingFee / buyTotalFees;
}
if (fees > 0) {
super._transfer(from, address(this), fees);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function _swapTokensForEth(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
path,
address(this),
block.timestamp
);
}
function _addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
owner(),
block.timestamp
);
}
uniswapV2Router.addLiquidityETH{value: ethAmount}(
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = _tokensForLiquidity + _tokensForMarketing + _tokensForDev;
if (contractBalance == 0 || totalTokensToSwap == 0) return;
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
_swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(_tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(_tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
_tokensForLiquidity = 0;
_tokensForMarketing = 0;
_tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
_addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, _tokensForLiquidity);
}
}
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = _tokensForLiquidity + _tokensForMarketing + _tokensForDev;
if (contractBalance == 0 || totalTokensToSwap == 0) return;
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
_swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(_tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(_tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
_tokensForLiquidity = 0;
_tokensForMarketing = 0;
_tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
_addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, _tokensForLiquidity);
}
}
uint256 liquidityTokens = contractBalance * _tokensForLiquidity / totalTokensToSwap / 2;
function swapBack() private {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = _tokensForLiquidity + _tokensForMarketing + _tokensForDev;
if (contractBalance == 0 || totalTokensToSwap == 0) return;
if (contractBalance > swapTokensAtAmount * 20) {
contractBalance = swapTokensAtAmount * 20;
}
uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
_swapTokensForEth(amountToSwapForETH);
uint256 ethBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = ethBalance.mul(_tokensForMarketing).div(totalTokensToSwap);
uint256 ethForDev = ethBalance.mul(_tokensForDev).div(totalTokensToSwap);
uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev;
_tokensForLiquidity = 0;
_tokensForMarketing = 0;
_tokensForDev = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
_addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, _tokensForLiquidity);
}
}
function withdrawFees() external {
payable(feeWallet).transfer(address(this).balance);
}
receive() external payable {}
}
| 15,204,609 |
[
1,
14925,
77,
17,
4819,
471,
30959,
17,
3350,
5349,
7990,
471,
3152,
431,
17704,
1317,
628,
1656,
281,
471,
943,
2492,
3844,
1707,
6138,
716,
279,
5859,
13667,
312,
6388,
5574,
18,
5502,
7412,
358,
4259,
6138,
3377,
506,
3221,
358,
279,
4207,
7412,
3844,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
16351,
4513,
291,
90,
5328,
737,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
640,
291,
91,
438,
58,
22,
8259,
31,
203,
565,
1758,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
203,
565,
2874,
261,
2867,
516,
1426,
13,
3238,
389,
291,
10461,
77,
457,
31,
203,
565,
1426,
3238,
389,
22270,
1382,
31,
203,
565,
2254,
5034,
3238,
389,
20738,
950,
31,
203,
203,
565,
1758,
1071,
14036,
16936,
31,
203,
377,
203,
565,
2254,
5034,
1071,
943,
3342,
6275,
31,
203,
565,
2254,
5034,
1071,
7720,
5157,
861,
6275,
31,
203,
565,
2254,
5034,
1071,
943,
16936,
31,
203,
540,
203,
565,
1426,
1071,
8181,
382,
12477,
273,
638,
31,
203,
565,
1426,
1071,
1284,
7459,
3896,
273,
629,
31,
203,
377,
203,
565,
1426,
1071,
7412,
6763,
1526,
273,
638,
31,
203,
203,
565,
2254,
5034,
1071,
30143,
5269,
2954,
281,
31,
203,
565,
2254,
5034,
3238,
389,
70,
9835,
3882,
21747,
14667,
31,
203,
565,
2254,
5034,
3238,
389,
70,
9835,
48,
18988,
24237,
14667,
31,
203,
565,
2254,
5034,
3238,
389,
70,
9835,
8870,
14667,
31,
203,
377,
203,
565,
2254,
5034,
1071,
357,
80,
5269,
2954,
281,
31,
203,
565,
2254,
5034,
3238,
389,
87,
1165,
3882,
21747,
14667,
31,
203,
565,
2254,
5034,
3238,
389,
87,
1165,
48,
18988,
24237,
14667,
31,
203,
565,
2254,
5034,
3238,
389,
87,
2
] |
./full_match/1/0x6eF43B4d5541Bb4420a3A6Ab416d5BcCEf9199C1/sources/contracts/ERC1967Administration.sol
|
* @dev Changes the admin of the proxy. Emits an {AdminChanged} event./
|
function changeAdmin(address newAdmin) public onlyAdmin {
emit AdminChanged(admin(), newAdmin);
_setAdmin(newAdmin);
}
uint256[50] private __gap;
| 8,498,471 |
[
1,
7173,
326,
3981,
434,
326,
2889,
18,
7377,
1282,
392,
288,
4446,
5033,
97,
871,
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,
565,
445,
2549,
4446,
12,
2867,
394,
4446,
13,
1071,
1338,
4446,
288,
203,
3639,
3626,
7807,
5033,
12,
3666,
9334,
394,
4446,
1769,
203,
3639,
389,
542,
4446,
12,
2704,
4446,
1769,
203,
565,
289,
203,
565,
2254,
5034,
63,
3361,
65,
3238,
1001,
14048,
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
] |
./full_match/1/0xbFFB88e0c0C6a54413AF1A643b4742CEDF175f2e/sources/Users/famousbirthdays/Sites/staking-contracts/contracts/ClavellArtShares.sol
|
gets the dividends of an address that aren't in the toBePaid mappingif excluded from staking or some error return 0
|
function _getDividendsOf(address _addr) private view returns (uint256) {
uint256 fullPayout = profitPerShare * sharePoints[_addr];
if(fullPayout<=alreadyPaidShares[_addr]) return 0;
return (fullPayout - alreadyPaidShares[_addr])/DistributionMultiplier;
}
| 4,970,490 |
[
1,
14665,
326,
3739,
350,
5839,
434,
392,
1758,
716,
11526,
1404,
316,
326,
21333,
16507,
350,
2874,
430,
8845,
628,
384,
6159,
578,
2690,
555,
327,
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
] |
[
1,
1,
1,
1,
1,
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,
389,
588,
7244,
350,
5839,
951,
12,
2867,
389,
4793,
13,
3238,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
1983,
52,
2012,
273,
450,
7216,
2173,
9535,
380,
7433,
5636,
63,
67,
4793,
15533,
203,
3639,
309,
12,
2854,
52,
2012,
32,
33,
17583,
16507,
350,
24051,
63,
67,
4793,
5717,
327,
374,
31,
203,
3639,
327,
261,
2854,
52,
2012,
300,
1818,
16507,
350,
24051,
63,
67,
4793,
5717,
19,
9003,
23365,
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
] |
./full_match/3/0xdaFaAa577297Cd49BdC7590fBC9954112e43ca82/sources/contracts/Exchange.sol
|
function setAddressStable(address _stablecoin) public { stablecoin = _stablecoin; } function setAddressNative(address _native) public { nativeToken = _native; }
|
contract ExchangePool is Ownable {
address private _owner;
PriceConsumerV3 PCV_price = new PriceConsumerV3();
uint256 public price ;
address public stablecoin = 0x0D5DD5A20eDab53A624efDb32589131375F8abEb;
address public nativeToken = 0xf83F1e213A3bfB880EB5A2696555759E622a0AeD;
Stablecoin stc = Stablecoin(stablecoin);
NativeToken ntk = NativeToken(nativeToken);
constructor() public{
_owner = owner();
}
function getPriceNow() public view returns(uint256){
return price;
}
function thePrice() internal view returns(uint256){
return PCV_price.getLatestPrice();
}
function setThePrice() internal {
price = thePrice();
}
function mintStable_burnNative(address _minner, uint256 _amout) public returns(bool){
uint256 amout = _amout * 10**18;
uint256 amoutNative = ntk.balanceOf(_minner);
uint256 fee = amout/1000 * 5;
uint256 rAmount = amout + fee;
require(amoutNative >= rAmount , "Not enough money");
ntk._burn(_minner,rAmount);
stc._mint(_minner, amout * price);
stc._mint(_owner,fee);
return true;
}
function mintNative_burnStable(address _minner, uint256 _amout) public returns(bool){
uint256 amout = _amout * 10**18;
uint256 amoutNative = stc.balanceOf(_minner);
uint256 fee = amout / 1000 * 5;
uint256 rAmount = amout + fee;
require(amoutNative >= rAmount , "Not enough money");
stc._burn(_minner,rAmount);
ntk._mint(_minner, amout / price);
ntk._mint(_owner,fee);
return true;
}
}
| 8,254,372 |
[
1,
915,
444,
1887,
30915,
12,
2867,
389,
15021,
12645,
13,
1071,
288,
377,
14114,
12645,
273,
389,
15021,
12645,
31,
289,
445,
444,
1887,
9220,
12,
2867,
389,
13635,
13,
1071,
288,
377,
6448,
1345,
273,
389,
13635,
31,
289,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
16351,
18903,
2864,
353,
14223,
6914,
288,
203,
565,
1758,
3238,
389,
8443,
31,
203,
565,
20137,
5869,
58,
23,
453,
22007,
67,
8694,
273,
394,
20137,
5869,
58,
23,
5621,
203,
565,
2254,
5034,
1071,
6205,
274,
203,
565,
1758,
1071,
14114,
12645,
273,
374,
92,
20,
40,
25,
5698,
25,
37,
3462,
73,
40,
378,
8643,
37,
26,
3247,
10241,
4331,
1578,
25,
6675,
3437,
3437,
5877,
42,
28,
378,
41,
70,
31,
7010,
565,
1758,
1071,
6448,
1345,
273,
374,
5841,
10261,
42,
21,
73,
22,
3437,
37,
23,
17156,
38,
28,
3672,
29258,
25,
37,
5558,
10525,
2539,
25,
5877,
29,
41,
26,
3787,
69,
20,
37,
73,
40,
31,
203,
377,
203,
377,
203,
377,
203,
565,
934,
429,
12645,
384,
71,
273,
934,
429,
12645,
12,
15021,
12645,
1769,
203,
565,
16717,
1345,
9513,
79,
273,
16717,
1345,
12,
13635,
1345,
1769,
203,
377,
203,
565,
3885,
1435,
1071,
95,
203,
3639,
389,
8443,
273,
3410,
5621,
203,
565,
289,
203,
377,
203,
565,
445,
25930,
8674,
1435,
1071,
1476,
1135,
12,
11890,
5034,
15329,
203,
3639,
327,
6205,
31,
203,
565,
289,
203,
377,
203,
377,
203,
565,
445,
326,
5147,
1435,
2713,
1476,
1135,
12,
11890,
5034,
15329,
203,
3639,
327,
453,
22007,
67,
8694,
18,
588,
18650,
5147,
5621,
203,
565,
289,
203,
377,
203,
565,
445,
444,
1986,
5147,
1435,
2713,
288,
203,
3639,
6205,
273,
326,
5147,
5621,
203,
565,
289,
203,
377,
203,
565,
445,
312,
474,
30915,
67,
70,
321,
9220,
2
] |
pragma solidity ^0.4.24;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title 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 Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title TMTGOwnable
*
* @dev Due to ownable change in zeppelin, the authorities in TMTGOwnable include hiddenOwner,
* superOwner, owner, centerBanker, and operator.
* Each authority has different roles.
*/
contract TMTGOwnable {
address public owner;
address public centralBanker;
address public superOwner;
address public hiddenOwner;
enum Role { owner, centralBanker, superOwner, hiddenOwner }
mapping(address => bool) public operators;
event TMTG_RoleTransferred(
Role indexed ownerType,
address indexed previousOwner,
address indexed newOwner
);
event TMTG_SetOperator(address indexed operator);
event TMTG_DeletedOperator(address indexed operator);
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier onlyOwnerOrOperator() {
require(msg.sender == owner || operators[msg.sender]);
_;
}
modifier onlyNotBankOwner(){
require(msg.sender != centralBanker);
_;
}
modifier onlyBankOwner(){
require(msg.sender == centralBanker);
_;
}
modifier onlySuperOwner() {
require(msg.sender == superOwner);
_;
}
modifier onlyhiddenOwner(){
require(msg.sender == hiddenOwner);
_;
}
constructor() public {
owner = msg.sender;
centralBanker = msg.sender;
superOwner = msg.sender;
hiddenOwner = msg.sender;
}
/**
* @dev Set the address to operator
* @param _operator has the ability to pause transaction, has the ability to blacklisting & unblacklisting.
*/
function setOperator(address _operator) external onlySuperOwner {
operators[_operator] = true;
emit TMTG_SetOperator(_operator);
}
/**
* @dev Remove the address from operator
* @param _operator has the ability to pause transaction, has the ability to blacklisting & unblacklisting.
*/
function delOperator(address _operator) external onlySuperOwner {
operators[_operator] = false;
emit TMTG_DeletedOperator(_operator);
}
/**
* @dev It is possible to hand over owner’s authority. Only superowner is available.
* @param newOwner
*/
function transferOwnership(address newOwner) public onlySuperOwner {
emit TMTG_RoleTransferred(Role.owner, owner, newOwner);
owner = newOwner;
}
/**
* @dev It is possible to hand over centerBanker’s authority. Only superowner is available.
* @param newBanker centerBanker is a kind of a central bank, transaction is impossible.
* The amount of money to deposit is determined in accordance with cash reserve ratio and the amount of currency in circulation
* To withdraw money out of a wallet and give it to owner, audit is inevitable
*/
function transferBankOwnership(address newBanker) public onlySuperOwner {
emit TMTG_RoleTransferred(Role.centralBanker, centralBanker, newBanker);
centralBanker = newBanker;
}
/**
* @dev It is possible to hand over superOwner’s authority. Only hiddenowner is available.
* @param newSuperOwner SuperOwner manages all authorities except for hiddenOwner and superOwner
*/
function transferSuperOwnership(address newSuperOwner) public onlyhiddenOwner {
emit TMTG_RoleTransferred(Role.superOwner, superOwner, newSuperOwner);
superOwner = newSuperOwner;
}
/**
* @dev It is possible to hand over hiddenOwner’s authority. Only hiddenowner is available
* @param newhiddenOwner NewhiddenOwner and hiddenOwner don’t have many functions,
* but they can set and remove authorities of superOwner and hiddenOwner.
*/
function changeHiddenOwner(address newhiddenOwner) public onlyhiddenOwner {
emit TMTG_RoleTransferred(Role.hiddenOwner, hiddenOwner, newhiddenOwner);
hiddenOwner = newhiddenOwner;
}
}
/**
* @title TMTGPausable
*
* @dev It is used to stop trading in emergency situation
*/
contract TMTGPausable is TMTGOwnable {
event TMTG_Pause();
event TMTG_Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev Block trading. Only owner and operator are available.
*/
function pause() onlyOwnerOrOperator whenNotPaused public {
paused = true;
emit TMTG_Pause();
}
/**
* @dev Unlock limit for trading. Owner and operator are available and this function can be operated in paused mode.
*/
function unpause() onlyOwnerOrOperator whenPaused public {
paused = false;
emit TMTG_Unpause();
}
}
/**
* @title TMTGBlacklist
*
* @dev Block trading of the suspicious account address.
*/
contract TMTGBlacklist is TMTGOwnable {
mapping(address => bool) blacklisted;
event TMTG_Blacklisted(address indexed blacklist);
event TMTG_Whitelisted(address indexed whitelist);
modifier whenPermitted(address node) {
require(!blacklisted[node]);
_;
}
/**
* @dev Check a certain node is in a blacklist
* @param node Check whether the user at a certain node is in a blacklist
*/
function isPermitted(address node) public view returns (bool) {
return !blacklisted[node];
}
/**
* @dev Process blacklisting
* @param node Process blacklisting. Put the user in the blacklist.
*/
function blacklist(address node) public onlyOwnerOrOperator {
blacklisted[node] = true;
emit TMTG_Blacklisted(node);
}
/**
* @dev Process unBlacklisting.
* @param node Remove the user from the blacklist.
*/
function unblacklist(address node) public onlyOwnerOrOperator {
blacklisted[node] = false;
emit TMTG_Whitelisted(node);
}
}
/**
* @title HasNoEther
*/
contract HasNoEther is TMTGOwnable {
/**
* @dev Constructor that rejects incoming Ether
* The `payable` flag is added so we can access `msg.value` without compiler warning. If we
* leave out payable, then Solidity will allow inheriting contracts to implement a payable
* constructor. By doing it this way we prevent a payable constructor from working. Alternatively
* we could use assembly to access msg.value.
*/
constructor() public payable {
require(msg.value == 0);
}
/**
* @dev Disallows direct send by settings a default function without the `payable` flag.
*/
function() external {
}
/**
* @dev Transfer all Ether held by the contract to the owner.
*/
function reclaimEther() external onlyOwner {
owner.transfer(address(this).balance);
}
}
/**
* @title TMTGBaseToken - Major functions such as authority setting on tockenlock are registered.
*/
contract TMTGBaseToken is StandardToken, TMTGPausable, TMTGBlacklist, HasNoEther {
uint256 public openingTime;
struct investor {
uint256 _sentAmount;
uint256 _initialAmount;
uint256 _limit;
}
mapping(address => investor) public searchInvestor;
mapping(address => bool) public superInvestor;
mapping(address => bool) public CEx;
mapping(address => bool) public investorList;
event TMTG_SetCEx(address indexed CEx);
event TMTG_DeleteCEx(address indexed CEx);
event TMTG_SetSuperInvestor(address indexed SuperInvestor);
event TMTG_DeleteSuperInvestor(address indexed SuperInvestor);
event TMTG_SetInvestor(address indexed investor);
event TMTG_DeleteInvestor(address indexed investor);
event TMTG_Stash(uint256 _value);
event TMTG_Unstash(uint256 _value);
event TMTG_TransferFrom(address indexed owner, address indexed spender, address indexed to, uint256 value);
event TMTG_Burn(address indexed burner, uint256 value);
/**
* @dev Register the address as a cex address
* @param _CEx Register the address as a cex address
*/
function setCEx(address _CEx) external onlySuperOwner {
CEx[_CEx] = true;
emit TMTG_SetCEx(_CEx);
}
/**
* @dev Remove authorities of the address used in Exchange
* @param _CEx Remove authorities of the address used in Exchange
*/
function delCEx(address _CEx) external onlySuperOwner {
CEx[_CEx] = false;
emit TMTG_DeleteCEx(_CEx);
}
/**
* @dev Register the address as a superinvestor address
* @param _super Register the address as a superinvestor address
*/
function setSuperInvestor(address _super) external onlySuperOwner {
superInvestor[_super] = true;
emit TMTG_SetSuperInvestor(_super);
}
/**
* @param _super Remove authorities of the address as a superinvestor
*/
function delSuperInvestor(address _super) external onlySuperOwner {
superInvestor[_super] = false;
emit TMTG_DeleteSuperInvestor(_super);
}
/**
* @param _addr Remove authorities of the address as a investor .
*/
function delInvestor(address _addr) onlySuperOwner public {
investorList[_addr] = false;
searchInvestor[_addr] = investor(0,0,0);
emit TMTG_DeleteInvestor(_addr);
}
function setOpeningTime() onlyOwner public returns(bool) {
openingTime = block.timestamp;
}
/**
* @dev After one month, the amount will be 1, which means 10% of the coins can be used.
* After 7 months, 70% of the amount can be used.
*/
function getLimitPeriod() external view returns (uint256) {
uint256 presentTime = block.timestamp;
uint256 timeValue = presentTime.sub(openingTime);
uint256 result = timeValue.div(31 days);
return result;
}
/**
* @dev Check the latest limit
* @param who Check the latest limit.
* Return the limit value of the user at the present moment. After 3 months, _result value will be 30% of initialAmount
*/
function _timelimitCal(address who) internal view returns (uint256) {
uint256 presentTime = block.timestamp;
uint256 timeValue = presentTime.sub(openingTime);
uint256 _result = timeValue.div(31 days);
return _result.mul(searchInvestor[who]._limit);
}
/**
* @dev In case of investor transfer, values will be limited by timelock
* @param _to address to send
* @param _value tmtg's amount
*/
function _transferInvestor(address _to, uint256 _value) internal returns (bool ret) {
uint256 addedValue = searchInvestor[msg.sender]._sentAmount.add(_value);
require(_timelimitCal(msg.sender) >= addedValue);
searchInvestor[msg.sender]._sentAmount = addedValue;
ret = super.transfer(_to, _value);
if (!ret) {
searchInvestor[msg.sender]._sentAmount = searchInvestor[msg.sender]._sentAmount.sub(_value);
}
}
/**
* @dev When the transfer function is run,
* there are two different types; transfer from superinvestors to investor and to non-investors.
* In the latter case, the non-investors will be investor and 10% of the initial amount will be allocated.
* And when investor operates the transfer function, the values will be limited by timelock.
* @param _to address to send
* @param _value tmtg's amount
*/
function transfer(address _to, uint256 _value) public
whenPermitted(msg.sender) whenPermitted(_to) whenNotPaused onlyNotBankOwner
returns (bool) {
if(investorList[msg.sender]) {
return _transferInvestor(_to, _value);
} else {
if (superInvestor[msg.sender]) {
require(_to != owner);
require(!superInvestor[_to]);
require(!CEx[_to]);
if(!investorList[_to]){
investorList[_to] = true;
searchInvestor[_to] = investor(0, _value, _value.div(10));
emit TMTG_SetInvestor(_to);
}
}
return super.transfer(_to, _value);
}
}
/**
* @dev If investor is from in transforFrom, values will be limited by timelock
* @param _from send amount from this address
* @param _to address to send
* @param _value tmtg's amount
*/
function _transferFromInvestor(address _from, address _to, uint256 _value)
public returns(bool ret) {
uint256 addedValue = searchInvestor[_from]._sentAmount.add(_value);
require(_timelimitCal(_from) >= addedValue);
searchInvestor[_from]._sentAmount = addedValue;
ret = super.transferFrom(_from, _to, _value);
if (!ret) {
searchInvestor[_from]._sentAmount = searchInvestor[_from]._sentAmount.sub(_value);
}else {
emit TMTG_TransferFrom(_from, msg.sender, _to, _value);
}
}
/**
* @dev If from is superinvestor in transforFrom, the function can’t be used because of limit in Approve.
* And if from is investor, the amount of coins to send is limited by timelock.
* @param _from send amount from this address
* @param _to address to send
* @param _value tmtg's amount
*/
function transferFrom(address _from, address _to, uint256 _value)
public whenNotPaused whenPermitted(_from) whenPermitted(_to) whenPermitted(msg.sender)
returns (bool ret)
{
if(investorList[_from]) {
return _transferFromInvestor(_from, _to, _value);
} else {
ret = super.transferFrom(_from, _to, _value);
emit TMTG_TransferFrom(_from, msg.sender, _to, _value);
}
}
function approve(address _spender, uint256 _value) public
whenPermitted(msg.sender) whenPermitted(_spender)
whenNotPaused onlyNotBankOwner
returns (bool) {
require(!superInvestor[msg.sender]);
return super.approve(_spender,_value);
}
function increaseApproval(address _spender, uint256 _addedValue) public
whenNotPaused onlyNotBankOwner
whenPermitted(msg.sender) whenPermitted(_spender)
returns (bool) {
require(!superInvestor[msg.sender]);
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint256 _subtractedValue) public
whenNotPaused onlyNotBankOwner
whenPermitted(msg.sender) whenPermitted(_spender)
returns (bool) {
require(!superInvestor[msg.sender]);
return super.decreaseApproval(_spender, _subtractedValue);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Transfer(_who, address(0), _value);
emit TMTG_Burn(_who, _value);
}
function burn(uint256 _value) onlyOwner public returns (bool) {
_burn(msg.sender, _value);
return true;
}
function burnFrom(address _from, uint256 _value) onlyOwner public returns (bool) {
require(_value <= allowed[_from][msg.sender]);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
_burn(_from, _value);
return true;
}
/**
* @dev onlyOwner is available and the amount of coins can be deposited in centerBanker.
* @param _value tmtg's amount
*/
function stash(uint256 _value) public onlyOwner {
require(balances[owner] >= _value);
super.transfer(centralBanker, _value);
emit TMTG_Stash(_value);
}
/**
* @dev Only centerBanker is available and withdrawal of the amount of coins to owner is possible. But audit is inevitable.
* @param _value tmtg's amount
*/
function unstash(uint256 _value) public onlyBankOwner {
require(balances[centralBanker] >= _value);
super.transfer(owner, _value);
emit TMTG_Unstash(_value);
}
function reclaimToken() external onlyOwner {
transfer(owner, balanceOf(this));
}
function destory() onlyhiddenOwner public {
selfdestruct(superOwner);
}
function refreshInvestor(address _investor, address _to, uint _amount) onlyOwner public {
require(investorList[_investor]);
require(_to != address(0));
require(_amount <= balances[_investor]);
super.transferFrom(_investor, _to, _amount);
}
}
contract TMTG is TMTGBaseToken {
string public constant name = "The Midas Touch Gold";
string public constant symbol = "TMTG";
uint8 public constant decimals = 18;
uint256 public constant INITIAL_SUPPLY = 1e10 * (10 ** uint256(decimals));
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
openingTime = block.timestamp;
emit Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
}
|
* @dev onlyOwner is available and the amount of coins can be deposited in centerBanker. @param _value tmtg's amount/
|
function stash(uint256 _value) public onlyOwner {
require(balances[owner] >= _value);
super.transfer(centralBanker, _value);
emit TMTG_Stash(_value);
}
| 2,522,306 |
[
1,
3700,
5541,
353,
2319,
471,
326,
3844,
434,
276,
9896,
848,
506,
443,
1724,
329,
316,
4617,
16040,
264,
18,
225,
389,
1132,
268,
1010,
75,
1807,
3844,
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,
565,
445,
23017,
12,
11890,
5034,
389,
1132,
13,
1071,
1338,
5541,
288,
203,
3639,
2583,
12,
70,
26488,
63,
8443,
65,
1545,
389,
1132,
1769,
203,
540,
203,
3639,
2240,
18,
13866,
12,
71,
12839,
16040,
264,
16,
389,
1132,
1769,
203,
540,
203,
3639,
3626,
399,
6152,
43,
67,
510,
961,
24899,
1132,
1769,
540,
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
] |
pragma solidity 0.5.13;
import "@daostack/infra/contracts/votingMachines/IntVoteInterface.sol";
import "@daostack/infra/contracts/votingMachines/VotingMachineCallbacksInterface.sol";
import "./UniversalScheme.sol";
import "../votingMachines/VotingMachineCallbacks.sol";
/**
* @title A scheme for proposing and rewarding contributions to an organization
* @dev An agent can ask an organization to recognize a contribution and reward
* him with token, reputation, ether or any combination.
*/
contract ContributionReward is
UniversalScheme,
VotingMachineCallbacks,
ProposalExecuteInterface
{
using SafeMath for uint256;
event NewContributionProposal(
address indexed _avatar,
bytes32 indexed _proposalId,
address indexed _intVoteInterface,
string _descriptionHash,
uint256[5] _rewards,
IERC20 _externalToken,
address _beneficiary
);
event ProposalExecuted(
address indexed _avatar,
bytes32 indexed _proposalId,
int256 _param
);
event RedeemEther(
address indexed _avatar,
bytes32 indexed _proposalId,
address indexed _beneficiary,
uint256 _amount
);
event RedeemExternalToken(
address indexed _avatar,
bytes32 indexed _proposalId,
address indexed _beneficiary,
uint256 _amount
);
// A struct holding the data for a contribution proposal
struct ContributionProposal {
uint256 ethReward;
IERC20 externalToken;
uint256 externalTokenReward;
address payable beneficiary;
uint256 periodLength;
uint256 numberOfPeriods;
uint256 executionTime;
uint256[4] redeemedPeriods;
}
// A mapping from the organization (Avatar) address to the saved data of the organization:
mapping(address => mapping(bytes32 => ContributionProposal)) public organizationsProposals;
// A mapping from hashes to parameters (use to store a particular configuration on the controller)
struct Parameters {
bytes32 voteApproveParams;
IntVoteInterface intVote;
}
// A mapping from hashes to parameters (use to store a particular configuration on the controller)
mapping(bytes32 => Parameters) public parameters;
/**
* @dev execution of proposals, can only be called by the voting machine in which the vote is held.
* @param _proposalId the ID of the voting in the voting machine
* @param _param a parameter of the voting result, 1 yes and 2 is no.
*/
function executeProposal(bytes32 _proposalId, int256 _param)
external
onlyVotingMachine(_proposalId)
returns (bool)
{
ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId];
require(
organizationsProposals[address(proposal.avatar)][_proposalId]
.executionTime == 0
);
require(
organizationsProposals[address(proposal.avatar)][_proposalId]
.beneficiary != address(0)
);
// Check if vote was successful:
if (_param == 1) {
// solhint-disable-next-line not-rely-on-time
organizationsProposals[address(proposal.avatar)][_proposalId]
.executionTime = now;
}
emit ProposalExecuted(address(proposal.avatar), _proposalId, _param);
return true;
}
/**
* @dev hash the parameters, save them if necessary, and return the hash value
*/
function setParameters(
bytes32 _voteApproveParams,
IntVoteInterface _intVote
) public returns (bytes32) {
bytes32 paramsHash = getParametersHash(_voteApproveParams, _intVote);
parameters[paramsHash].voteApproveParams = _voteApproveParams;
parameters[paramsHash].intVote = _intVote;
return paramsHash;
}
/**
* @dev Submit a proposal for a reward for a contribution:
* @param _avatar Avatar of the organization that the contribution was made for
* @param _descriptionHash A hash of the proposal's description
* @param _rewards rewards array:
* rewards[0] - Amount of tokens requested per period
* rewards[1] - Amount of ETH requested per period
* rewards[2] - Amount of external tokens requested per period
* rewards[3] - Period length - if set to zero it allows immediate redeeming after execution.
* rewards[4] - Number of periods
* @param _beneficiary Who gets the rewards
*/
function proposeContributionReward(
Avatar _avatar,
string memory _descriptionHash,
int256,
uint256[5] memory _rewards,
IERC20 _externalToken,
address payable _beneficiary
) public returns (bytes32) {
validateProposalParams( _rewards);
Parameters memory controllerParams
= parameters[getParametersFromController(_avatar)];
bytes32 contributionId = controllerParams.intVote.propose(
2,
controllerParams.voteApproveParams,
msg.sender,
address(_avatar)
);
address payable beneficiary = _beneficiary;
if (beneficiary == address(0)) {
beneficiary = msg.sender;
}
ContributionProposal memory proposal = ContributionProposal({
ethReward: _rewards[1],
externalToken: _externalToken,
externalTokenReward: _rewards[2],
beneficiary: beneficiary,
periodLength: _rewards[3],
numberOfPeriods: _rewards[4],
executionTime: 0,
redeemedPeriods: [uint256(0), uint256(0), uint256(0), uint256(0)]
});
organizationsProposals[address(_avatar)][contributionId] = proposal;
emit NewContributionProposal(
address(_avatar),
contributionId,
address(controllerParams.intVote),
_descriptionHash,
_rewards,
_externalToken,
beneficiary
);
proposalsInfo[address(
controllerParams.intVote
)][contributionId] = ProposalInfo({
blockNumber: block.number,
avatar: _avatar
});
return contributionId;
}
/**
* @dev RedeemEther reward for proposal
* @param _proposalId the ID of the voting in the voting machine
* @param _avatar address of the controller
* @return amount ether redeemed amount
*/
function redeemEther(bytes32 _proposalId, Avatar _avatar)
public
returns (uint256 amount)
{
ContributionProposal memory _proposal = organizationsProposals[address(
_avatar
)][_proposalId];
ContributionProposal storage proposal = organizationsProposals[address(
_avatar
)][_proposalId];
require(proposal.executionTime != 0);
uint256 periodsToPay = getPeriodsToPay(
_proposalId,
address(_avatar),
2
);
//set proposal rewards to zero to prevent reentrancy attack.
proposal.ethReward = 0;
amount = periodsToPay.mul(_proposal.ethReward);
if (amount > 0) {
require(
Controller(_avatar.owner()).sendEther(
amount,
_proposal.beneficiary,
_avatar
)
);
proposal.redeemedPeriods[2] = proposal.redeemedPeriods[2].add(
periodsToPay
);
emit RedeemEther(
address(_avatar),
_proposalId,
_proposal.beneficiary,
amount
);
}
//restore proposal reward.
proposal.ethReward = _proposal.ethReward;
}
/**
* @dev RedeemNativeToken reward for proposal
* @param _proposalId the ID of the voting in the voting machine
* @param _avatar address of the controller
* @return amount the external token redeemed amount
*/
function redeemExternalToken(bytes32 _proposalId, Avatar _avatar)
public
returns (uint256 amount)
{
ContributionProposal memory _proposal = organizationsProposals[address(
_avatar
)][_proposalId];
ContributionProposal storage proposal = organizationsProposals[address(
_avatar
)][_proposalId];
require(proposal.executionTime != 0);
uint256 periodsToPay = getPeriodsToPay(
_proposalId,
address(_avatar),
3
);
//set proposal rewards to zero to prevent reentrancy attack.
proposal.externalTokenReward = 0;
if (
proposal.externalToken != IERC20(0) &&
_proposal.externalTokenReward > 0
) {
amount = periodsToPay.mul(_proposal.externalTokenReward);
if (amount > 0) {
require(
Controller(_avatar.owner()).externalTokenTransfer(
_proposal.externalToken,
_proposal.beneficiary,
amount,
_avatar
)
);
proposal.redeemedPeriods[3] = proposal.redeemedPeriods[3].add(
periodsToPay
);
emit RedeemExternalToken(
address(_avatar),
_proposalId,
_proposal.beneficiary,
amount
);
}
}
//restore proposal reward.
proposal.externalTokenReward = _proposal.externalTokenReward;
}
/**
* @dev redeem rewards for proposal
* @param _proposalId the ID of the voting in the voting machine
* @param _avatar address of the controller
* @param _whatToRedeem whatToRedeem array:
* whatToRedeem[0] - reputation
* whatToRedeem[1] - nativeTokenReward
* whatToRedeem[2] - Ether
* whatToRedeem[3] - ExternalToken
* @return result boolean array for each redeem type.
*/
function redeem(
bytes32 _proposalId,
Avatar _avatar,
bool[4] memory _whatToRedeem
)
public
returns (
uint256 etherReward,
uint256 externalTokenReward
)
{
if (_whatToRedeem[2]) {
etherReward = redeemEther(_proposalId, _avatar);
}
if (_whatToRedeem[3]) {
externalTokenReward = redeemExternalToken(_proposalId, _avatar);
}
}
/**
* @dev getPeriodsToPay return the periods left to be paid for reputation,nativeToken,ether or externalToken.
* The function ignore the reward amount to be paid (which can be zero).
* @param _proposalId the ID of the voting in the voting machine
* @param _avatar address of the controller
* @param _redeemType - the type of the reward :
* 0 - reputation
* 1 - nativeTokenReward
* 2 - Ether
* 3 - ExternalToken
* @return periods left to be paid.
*/
function getPeriodsToPay(
bytes32 _proposalId,
address _avatar,
uint256 _redeemType
) public view returns (uint256) {
require(_redeemType <= 3, "should be in the redeemedPeriods range");
ContributionProposal memory _proposal
= organizationsProposals[_avatar][_proposalId];
if (_proposal.executionTime == 0) return 0;
uint256 periodsFromExecution;
if (_proposal.periodLength > 0) {
// solhint-disable-next-line not-rely-on-time
periodsFromExecution =
(now.sub(_proposal.executionTime)) /
(_proposal.periodLength);
}
uint256 periodsToPay;
if (
(_proposal.periodLength == 0) ||
(periodsFromExecution >= _proposal.numberOfPeriods)
) {
periodsToPay = _proposal.numberOfPeriods.sub(
_proposal.redeemedPeriods[_redeemType]
);
} else {
periodsToPay = periodsFromExecution.sub(
_proposal.redeemedPeriods[_redeemType]
);
}
return periodsToPay;
}
/**
* @dev getRedeemedPeriods return the already redeemed periods for reputation, nativeToken, ether or externalToken.
* @param _proposalId the ID of the voting in the voting machine
* @param _avatar address of the controller
* @param _redeemType - the type of the reward :
* 0 - reputation
* 1 - nativeTokenReward
* 2 - Ether
* 3 - ExternalToken
* @return redeemed period.
*/
function getRedeemedPeriods(
bytes32 _proposalId,
address _avatar,
uint256 _redeemType
) public view returns (uint256) {
return
organizationsProposals[_avatar][_proposalId]
.redeemedPeriods[_redeemType];
}
function getProposalEthReward(bytes32 _proposalId, address _avatar)
public
view
returns (uint256)
{
return organizationsProposals[_avatar][_proposalId].ethReward;
}
function getProposalExternalTokenReward(
bytes32 _proposalId,
address _avatar
) public view returns (uint256) {
return organizationsProposals[_avatar][_proposalId].externalTokenReward;
}
function getProposalExternalToken(bytes32 _proposalId, address _avatar)
public
view
returns (address)
{
return
address(organizationsProposals[_avatar][_proposalId].externalToken);
}
function getProposalExecutionTime(bytes32 _proposalId, address _avatar)
public
view
returns (uint256)
{
return organizationsProposals[_avatar][_proposalId].executionTime;
}
/**
* @dev return a hash of the given parameters
* @param _voteApproveParams parameters for the voting machine used to approve a contribution
* @param _intVote the voting machine used to approve a contribution
* @return a hash of the parameters
*/
function getParametersHash(
bytes32 _voteApproveParams,
IntVoteInterface _intVote
) public pure returns (bytes32) {
return (keccak256(abi.encodePacked(_voteApproveParams, _intVote)));
}
/**
* @dev validateProposalParams validate proposal's rewards parameters.
* The function check for potential overflow upon proposal's redeem.
* The function reverts if the params are not valid.
* @param _rewards rewards array:
* rewards[0] - Amount of tokens requested per period
* rewards[1] - Amount of ETH requested per period
* rewards[2] - Amount of external tokens requested per period
* rewards[3] - Period length - if set to zero it allows immediate redeeming after execution.
* rewards[4] - Number of periods
*/
function validateProposalParams(
uint256[5] memory _rewards
) private pure {
//changed for sngls dao
require(_rewards[0] == 0, "SGT token functionality is blocked.");
require(
((_rewards[3] > 0) || (_rewards[4] == 1)),
"periodLength equal 0 require numberOfPeriods to be 1"
);
if (_rewards[4] > 0) {
// This is the only case of overflow not detected by the check below
//check that numberOfPeriods * tokenReward will not overflow
require(
(_rewards[4] * _rewards[0]) / _rewards[4] == _rewards[0],
"numberOfPeriods * tokenReward will overflow"
);
//check that numberOfPeriods * ethReward will not overflow
require(
(_rewards[4] * _rewards[1]) / _rewards[4] == _rewards[1],
"numberOfPeriods * ethReward will overflow"
);
//check that numberOfPeriods * texternalTokenReward will not overflow
require(
(_rewards[4] * _rewards[2]) / _rewards[4] == _rewards[2],
"numberOfPeriods * texternalTokenReward will overflow"
);
}
}
}
|
* @dev execution of proposals, can only be called by the voting machine in which the vote is held. @param _proposalId the ID of the voting in the voting machine @param _param a parameter of the voting result, 1 yes and 2 is no./ Check if vote was successful: solhint-disable-next-line not-rely-on-time
|
function executeProposal(bytes32 _proposalId, int256 _param)
external
onlyVotingMachine(_proposalId)
returns (bool)
{
ProposalInfo memory proposal = proposalsInfo[msg.sender][_proposalId];
require(
organizationsProposals[address(proposal.avatar)][_proposalId]
.executionTime == 0
);
require(
organizationsProposals[address(proposal.avatar)][_proposalId]
.beneficiary != address(0)
);
if (_param == 1) {
organizationsProposals[address(proposal.avatar)][_proposalId]
.executionTime = now;
}
emit ProposalExecuted(address(proposal.avatar), _proposalId, _param);
return true;
}
| 12,873,247 |
[
1,
16414,
434,
450,
22536,
16,
848,
1338,
506,
2566,
635,
326,
331,
17128,
5228,
316,
1492,
326,
12501,
353,
15770,
18,
225,
389,
685,
8016,
548,
326,
1599,
434,
326,
331,
17128,
316,
326,
331,
17128,
5228,
225,
389,
891,
279,
1569,
434,
326,
331,
17128,
563,
16,
404,
12465,
471,
576,
353,
1158,
18,
19,
2073,
309,
12501,
1703,
6873,
30,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
486,
17,
266,
715,
17,
265,
17,
957,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
1836,
14592,
12,
3890,
1578,
389,
685,
8016,
548,
16,
509,
5034,
389,
891,
13,
203,
3639,
3903,
203,
3639,
1338,
58,
17128,
6981,
24899,
685,
8016,
548,
13,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
19945,
966,
3778,
14708,
273,
450,
22536,
966,
63,
3576,
18,
15330,
6362,
67,
685,
8016,
548,
15533,
203,
3639,
2583,
12,
203,
5411,
20929,
626,
22536,
63,
2867,
12,
685,
8016,
18,
19660,
13,
6362,
67,
685,
8016,
548,
65,
203,
7734,
263,
16414,
950,
422,
374,
203,
3639,
11272,
203,
3639,
2583,
12,
203,
5411,
20929,
626,
22536,
63,
2867,
12,
685,
8016,
18,
19660,
13,
6362,
67,
685,
8016,
548,
65,
203,
7734,
263,
70,
4009,
74,
14463,
814,
480,
1758,
12,
20,
13,
203,
3639,
11272,
203,
3639,
309,
261,
67,
891,
422,
404,
13,
288,
203,
5411,
20929,
626,
22536,
63,
2867,
12,
685,
8016,
18,
19660,
13,
6362,
67,
685,
8016,
548,
65,
203,
7734,
263,
16414,
950,
273,
2037,
31,
203,
3639,
289,
203,
3639,
3626,
19945,
23839,
12,
2867,
12,
685,
8016,
18,
19660,
3631,
389,
685,
8016,
548,
16,
389,
891,
1769,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
/**
* @title SushiSwap Double Incentive.
* @dev Decentralized Exchange.
*/
import { TokenInterface } from "../../common/interfaces.sol";
import { Helpers } from "./helpers.sol";
import { Events } from "./events.sol";
abstract contract SushipswapIncentiveResolver is Helpers, Events {
/**
* @dev deposit LP token to masterChef
* @notice deposit LP token to masterChef
* @param token1 token1 of LP token
* @param token2 token2 of LP token
* @param amount amount of LP token
* @param getId ID to retrieve amount
* @param setId ID stores Pool ID
* @param data the metadata struct
*/
function deposit(
address token1,
address token2,
uint256 amount,
uint256 getId,
uint256 setId,
Metadata memory data
)
external
payable
returns (string memory _eventName, bytes memory _eventParam)
{
token1 = changeEthAddrToWethAddr(token1);
token2 = changeEthAddrToWethAddr(token2);
amount = getUint(getId, amount);
if (
data.poolId == uint256(-1) ||
data.version == 0 ||
data.lpToken == address(0)
) {
data = _getPoolId(token1, token2);
}
setUint(setId, data.poolId);
require(data.poolId != uint256(-1), "pool-does-not-exist");
TokenInterface lpToken = TokenInterface(data.lpToken);
lpToken.approve(address(masterChef), amount);
_deposit(data, amount);
_eventName = "LogDeposit(address,address,uint256,uint256,uint256)";
_eventParam = abi.encode(
token1,
token2,
data.poolId,
data.version,
amount
);
}
/**
* @dev withdraw LP token from masterChef
* @notice withdraw LP token from masterChef
* @param token1 token1 of LP token
* @param token2 token2 of LP token
* @param amount amount of LP token
* @param getId ID to retrieve amount
* @param setId ID stores Pool ID
* @param data the metadata struct
*/
function withdraw(
address token1,
address token2,
uint256 amount,
uint256 getId,
uint256 setId,
Metadata memory data
)
external
payable
returns (string memory _eventName, bytes memory _eventParam)
{
token1 = changeEthAddrToWethAddr(token1);
token2 = changeEthAddrToWethAddr(token2);
amount = getUint(getId, amount);
if (data.poolId == uint256(-1) || data.version == 0) {
data = _getPoolId(token1, token2);
}
setUint(setId, amount);
require(data.poolId != uint256(-1), "pool-does-not-exist");
_withdraw(data, amount);
_eventName = "LogDeposit(address,address,uint256,uint256,uint256)";
_eventParam = abi.encode(
token1,
token2,
data.poolId,
data.version,
amount
);
}
/**
* @dev harvest from masterChef
* @notice harvest from masterChef
* @param token1 token1 deposited of LP token
* @param token2 token2 deposited LP token
* @param setId ID stores Pool ID
* @param data the metadata struct
*/
function harvest(
address token1,
address token2,
uint256 setId,
Metadata memory data
)
external
payable
returns (string memory _eventName, bytes memory _eventParam)
{
token1 = changeEthAddrToWethAddr(token1);
token2 = changeEthAddrToWethAddr(token2);
if (data.poolId == uint256(-1) || data.version == 0) {
data = _getPoolId(token1, token2);
}
setUint(setId, data.poolId);
require(data.poolId != uint256(-1), "pool-does-not-exist");
(, uint256 rewardsAmount) = _getUserInfo(data);
if (data.version == 2) _harvest(data);
else _withdraw(data, 0);
_eventName = "LogDeposit(address,address,uint256,uint256,uint256)";
_eventParam = abi.encode(
token1,
token2,
data.poolId,
data.version,
rewardsAmount
);
}
/**
* @dev withdraw LP token and harvest from masterChef
* @notice withdraw LP token and harvest from masterChef
* @param token1 token1 of LP token
* @param token2 token2 of LP token
* @param amount amount of LP token
* @param getId ID to retrieve amount
* @param setId ID stores Pool ID
* @param data the metadata struct
*/
function withdrawAndHarvest(
address token1,
address token2,
uint256 amount,
uint256 getId,
uint256 setId,
Metadata memory data
)
external
payable
returns (string memory _eventName, bytes memory _eventParam)
{
token1 = changeEthAddrToWethAddr(token1);
token2 = changeEthAddrToWethAddr(token2);
amount = getUint(getId, amount);
if (data.poolId == uint256(-1) || data.version == 0) {
data = _getPoolId(token1, token2);
}
setUint(setId, data.poolId);
require(data.poolId != uint256(-1), "pool-does-not-exist");
(, uint256 rewardsAmount) = _getUserInfo(data);
_withdrawAndHarvest(data, amount);
_eventName = "LogWithdrawAndHarvest(address,address,uint256,uint256,uint256,uint256)";
_eventParam = abi.encode(
token1,
token2,
data.poolId,
data.version,
amount,
rewardsAmount
);
}
/**
* @dev emergency withdraw from masterChef
* @notice emergency withdraw from masterChef
* @param token1 token1 deposited of LP token
* @param token2 token2 deposited LP token
* @param setId ID stores Pool ID
* @param data the metadata struct
*/
function emergencyWithdraw(
address token1,
address token2,
uint256 setId,
Metadata memory data
)
external
payable
returns (string memory _eventName, bytes memory _eventParam)
{
token1 = changeEthAddrToWethAddr(token1);
token2 = changeEthAddrToWethAddr(token2);
if (data.poolId == uint256(-1) || data.version == 0) {
data = _getPoolId(token1, token2);
}
uint256 currentBal = _balance(token1, token2);
require(data.poolId != uint256(-1), "pool-does-not-exist");
(uint256 lpAmount, uint256 rewardsAmount) = _getUserInfo(data);
_emergencyWithdraw(data);
uint256 finalBal = _balance(token1, token2);
setUint(setId, uint256(currentBal - finalBal));
_eventName = "LogEmergencyWithdraw(address,address,uint256,uint256,uint256,uint256)";
_eventParam = abi.encode(
token1,
token2,
data.poolId,
data.version,
lpAmount,
rewardsAmount
);
}
}
contract ConnectV2SushiswapIncentive is SushipswapIncentiveResolver {
string public constant name = "SushipswapIncentive-v1.1";
}
|
* @dev harvest from masterChef @notice harvest from masterChef @param token1 token1 deposited of LP token @param token2 token2 deposited LP token @param setId ID stores Pool ID @param data the metadata struct/
|
function harvest(
address token1,
address token2,
uint256 setId,
Metadata memory data
)
external
payable
returns (string memory _eventName, bytes memory _eventParam)
{
token1 = changeEthAddrToWethAddr(token1);
token2 = changeEthAddrToWethAddr(token2);
if (data.poolId == uint256(-1) || data.version == 0) {
data = _getPoolId(token1, token2);
}
setUint(setId, data.poolId);
require(data.poolId != uint256(-1), "pool-does-not-exist");
(, uint256 rewardsAmount) = _getUserInfo(data);
if (data.version == 2) _harvest(data);
else _withdraw(data, 0);
_eventName = "LogDeposit(address,address,uint256,uint256,uint256)";
_eventParam = abi.encode(
token1,
token2,
data.poolId,
data.version,
rewardsAmount
);
}
| 944,591 |
[
1,
30250,
26923,
628,
4171,
39,
580,
74,
225,
17895,
26923,
628,
4171,
39,
580,
74,
225,
1147,
21,
1147,
21,
443,
1724,
329,
434,
511,
52,
1147,
225,
1147,
22,
1147,
22,
443,
1724,
329,
511,
52,
1147,
225,
10446,
1599,
9064,
8828,
1599,
225,
501,
326,
1982,
1958,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
202,
915,
17895,
26923,
12,
203,
202,
202,
2867,
1147,
21,
16,
203,
202,
202,
2867,
1147,
22,
16,
203,
202,
202,
11890,
5034,
10446,
16,
203,
202,
202,
2277,
3778,
501,
203,
202,
13,
203,
202,
202,
9375,
203,
202,
202,
10239,
429,
203,
202,
202,
6154,
261,
1080,
3778,
389,
2575,
461,
16,
1731,
3778,
389,
2575,
786,
13,
203,
202,
95,
203,
202,
202,
2316,
21,
273,
2549,
41,
451,
3178,
774,
59,
546,
3178,
12,
2316,
21,
1769,
203,
202,
202,
2316,
22,
273,
2549,
41,
451,
3178,
774,
59,
546,
3178,
12,
2316,
22,
1769,
203,
202,
202,
430,
261,
892,
18,
6011,
548,
422,
2254,
5034,
19236,
21,
13,
747,
501,
18,
1589,
422,
374,
13,
288,
203,
1082,
202,
892,
273,
389,
588,
25136,
12,
2316,
21,
16,
1147,
22,
1769,
203,
202,
202,
97,
203,
202,
202,
542,
5487,
12,
542,
548,
16,
501,
18,
6011,
548,
1769,
203,
202,
202,
6528,
12,
892,
18,
6011,
548,
480,
2254,
5034,
19236,
21,
3631,
315,
6011,
17,
20657,
17,
902,
17,
7398,
8863,
203,
202,
202,
12,
16,
2254,
5034,
283,
6397,
6275,
13,
273,
389,
588,
21015,
12,
892,
1769,
203,
202,
202,
430,
261,
892,
18,
1589,
422,
576,
13,
389,
30250,
26923,
12,
892,
1769,
203,
202,
202,
12107,
389,
1918,
9446,
12,
892,
16,
374,
1769,
203,
202,
202,
67,
2575,
461,
273,
315,
1343,
758,
1724,
12,
2867,
16,
2867,
16,
11890,
5034,
16,
11890,
5034,
16,
11890,
5034,
2225,
31,
203,
2
] |
./partial_match/5/0x6D1Ba393ED7e26F4934746B3e82202F0eDf9563D/sources/contracts/mixins/NFTMarketAuction.sol
|
If an auction is already in progress then the NFT would be in escrow and the modifier would have failed
|
function createAuction(
address token,
uint256 id,
uint256 duration,
uint256 extensionDuration,
uint256 startingPrice
) public onlyNFTOwnerAndApproved(token, id) onlyValidAuctionConfig(duration, extensionDuration, startingPrice) {
uint256 auctionId = tokenToIdToAuctionId[token][id];
if (auctionId != 0) {
Auction memory auction = auctionIdToAuction[auctionId];
require(auction.seller != msg.sender, "NFTMarketAuction: Auction has already been created");
delete auctionIdToAuction[auctionId];
}
auctionId = nextAuctionId++;
tokenToIdToAuctionId[token][id] = auctionId;
auctionIdToAuction[auctionId] = Auction(
token,
id,
msg.sender,
duration,
extensionDuration,
0,
address(0),
startingPrice
);
emit AuctionCreated(auctionId);
}
| 16,848,371 |
[
1,
2047,
392,
279,
4062,
353,
1818,
316,
4007,
1508,
326,
423,
4464,
4102,
506,
316,
2904,
492,
471,
326,
9606,
4102,
1240,
2535,
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,
225,
445,
752,
37,
4062,
12,
203,
565,
1758,
1147,
16,
203,
565,
2254,
5034,
612,
16,
203,
565,
2254,
5034,
3734,
16,
203,
565,
2254,
5034,
2710,
5326,
16,
203,
565,
2254,
5034,
5023,
5147,
203,
225,
262,
1071,
1338,
50,
4464,
5541,
1876,
31639,
12,
2316,
16,
612,
13,
1338,
1556,
37,
4062,
809,
12,
8760,
16,
2710,
5326,
16,
5023,
5147,
13,
288,
203,
565,
2254,
5034,
279,
4062,
548,
273,
1147,
774,
28803,
37,
4062,
548,
63,
2316,
6362,
350,
15533,
203,
565,
309,
261,
69,
4062,
548,
480,
374,
13,
288,
203,
1377,
432,
4062,
3778,
279,
4062,
273,
279,
4062,
28803,
37,
4062,
63,
69,
4062,
548,
15533,
203,
1377,
2583,
12,
69,
4062,
18,
1786,
749,
480,
1234,
18,
15330,
16,
315,
50,
4464,
3882,
278,
37,
4062,
30,
432,
4062,
711,
1818,
2118,
2522,
8863,
203,
1377,
1430,
279,
4062,
28803,
37,
4062,
63,
69,
4062,
548,
15533,
203,
565,
289,
203,
203,
565,
279,
4062,
548,
273,
1024,
37,
4062,
548,
9904,
31,
203,
565,
1147,
774,
28803,
37,
4062,
548,
63,
2316,
6362,
350,
65,
273,
279,
4062,
548,
31,
203,
565,
279,
4062,
28803,
37,
4062,
63,
69,
4062,
548,
65,
273,
432,
4062,
12,
203,
1377,
1147,
16,
203,
1377,
612,
16,
203,
1377,
1234,
18,
15330,
16,
203,
1377,
3734,
16,
203,
1377,
2710,
5326,
16,
203,
1377,
374,
16,
203,
1377,
1758,
12,
20,
3631,
203,
1377,
5023,
5147,
203,
565,
11272,
203,
203,
565,
3626,
432,
4062,
6119,
12,
2
] |
pragma solidity ^0.4.24;
// Deployed at 0x06af8345c1266ee172ee66a31e2be65bf9aa7b46 on Ropsten!
contract SecretEventOrg{
address public organizer; // Address of organizer
string public encryption_key; // Linnia encryption_key of event organizer
struct Member { // Member infromation type
address addr;
uint provenance;
address initiator;
uint referrals_remaining;
string public_key;
}
struct SecretEvent { // Event information
string eventName;
string describe;
uint capacity;
uint deposit;
uint start_time;
uint duration;
uint totalAttending; // Total member who are attending event
string location; // = "SECRET : Will be disclosed to members";
string details; // = "SECRET : Will be disclosed to members";
}
address[] public innerCircle; // Address of members
uint numEvents = 0; // Total events successful so far
uint MAX_REFERRALS = 5;
mapping (address => Member) memberInfo; // Mapping from member address to member information
mapping (address => address) referralInfo; // Refered friend to member mapping
mapping (bytes32 => SecretEvent) public eventInfo; // Information on events created by this organizer
bytes32 public currentEventHash;
// Constructor
constructor(string public_key) public {
organizer = msg.sender;
encryption_key = public_key;
memberInfo[organizer] = Member(organizer, 0, 0, MAX_REFERRALS, public_key);
}
// Organizer only
modifier _onlyOrganizer(address _caller) {
require(_caller == organizer, "Unauthorized request, organizer only");
_;
}
// Member only
modifier _onlyMember(address _caller) {
require(_caller == memberInfo[_caller].addr, "Members only");
_;
}
// Check if current event expired
modifier _eventNotExpired(bytes32 id) {
require(eventInfo[id].start_time != 0 && now < eventInfo[id].start_time, "can't create a new event");
_;
}
// Check if maximum event capacity reached
modifier _maxEventCap(bytes32 id) {
require(eventInfo[id].capacity > 0, "Maximum capacity reached");
_;
}
// Check if member is allowed to refer more friends
modifier _referralsAllowed(address caller) {
require(memberInfo[caller].referrals_remaining > 0, "Cant refer more people");
_;
}
// Check if friend is already referred by other member
modifier _notAlreadyReferred(address addr) {
require(referralInfo[addr] == 0, "Someone already referred your friend");
_;
}
// Check if friend is already referred by other member
modifier _alreadyReferred(address addr) {
require(referralInfo[addr] != 0, "Referral by a Member is required");
_;
}
modifier _eventDoesntExists(bytes32 id) {
require(eventInfo[id].start_time == 0, "Event already exists, cant add");
_;
}
modifier _ifDepositEnough(bytes32 id, uint val) {
require(val >= eventInfo[id].deposit, "Not enough money" );
_;
}
// Member refers a friend
function referFriend(address _addr) public _onlyMember(msg.sender) _referralsAllowed(msg.sender) _notAlreadyReferred(_addr) {
referralInfo[_addr] = msg.sender;
memberInfo[msg.sender].referrals_remaining--;
}
// Referred friend applies for membership
function applyMembership(string public_key) public payable _alreadyReferred(msg.sender) {
memberInfo[msg.sender] = Member(msg.sender, memberInfo[referralInfo[msg.sender]].provenance+1, referralInfo[msg.sender], MAX_REFERRALS, public_key);
referralInfo[msg.sender] = 0;
innerCircle.push(msg.sender);
}
// Add Event
function addEvent(bytes32 id, string name, string describe, uint capacity, uint deposit, uint start_time, uint duration) public _onlyOrganizer(msg.sender) _eventDoesntExists(id){
eventInfo[id] = SecretEvent(name, describe, capacity, deposit, now+start_time, duration, 0, "SECRET: revealed to members", "SECRET: revealed to members");
numEvents++;
currentEventHash = id;
}
// Attend Event
function attendEvent(bytes32 id) public payable _onlyMember(msg.sender) _eventNotExpired(id) _maxEventCap(id) _ifDepositEnough(id, msg.value){
if (msg.value > eventInfo[id].deposit){
uint balance = msg.value - eventInfo[id].deposit;
msg.sender.transfer(balance);
}
eventInfo[id].totalAttending++;
}
// Returns event info
function getEventInfo(bytes32 _recordHash) public view returns(string eventName, string describe, uint capacity, uint deposit, uint start_time, uint duration, uint totalAttending){
return (eventInfo[_recordHash].eventName, eventInfo[_recordHash].describe, eventInfo[_recordHash].capacity, eventInfo[_recordHash].deposit, eventInfo[_recordHash].start_time, eventInfo[_recordHash].duration, eventInfo[_recordHash].totalAttending);
}
// Returns member info
function getMemberInfo(address _addr) public view returns(uint provenance, address initiator, uint referrals_remaining, string public_key){
return (memberInfo[_addr].provenance, memberInfo[_addr].initiator, memberInfo[_addr].referrals_remaining, memberInfo[_addr].public_key);
}
// Checks if address was referred.
function checkIfReferred(address addr) public view returns(bool) {
return referralInfo[addr] != 0;
}
// Checks if address is a member.
function checkIfMember(address addr) public view returns(bool) {
return memberInfo[addr].addr != 0;
}
// organizer adds members
function addMember(address newMember, string memberPublicKey) public _onlyOrganizer(msg.sender) {
memberInfo[newMember] = Member(newMember, 1, organizer, MAX_REFERRALS, memberPublicKey);
innerCircle.push(newMember);
}
}
|
Checks if address is a member.
|
function checkIfMember(address addr) public view returns(bool) {
return memberInfo[addr].addr != 0;
}
| 5,413,114 |
[
1,
4081,
309,
1758,
353,
279,
3140,
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
] |
[
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,
565,
445,
19130,
4419,
12,
2867,
3091,
13,
1071,
1476,
1135,
12,
6430,
13,
288,
203,
3639,
327,
3140,
966,
63,
4793,
8009,
4793,
480,
374,
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,
-100,
-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.4;
import "./token/Token.sol";
contract KDOTicket is Token(0, "KDO Coin", 0, "KDO") {
struct Ticket {
uint256 balance;
string tType;
uint createdAt;
uint expireAt;
address contractor;
bool hasReviewed;
}
struct Contractor {
uint256 balance;
mapping (uint => uint) reviews;
uint256 nbCredittedTickets;
uint256 debittedBalance;
}
address public businessOwner;
// Commission regarding the review average, the index is about the rating value
// the value is the commission in %
uint8[5] public commissions;
mapping (address => Ticket) public activeTickets;
// A contractor is a person who can consume ticketTypes and be credited for
mapping (address => Contractor) public contractors;
event CreditEvt(address ticket, address contractor, string tType, uint256 date);
event DebitEvt(address contractor, uint256 amount, uint256 commission, uint256 date);
event ReviewEvt(address reviewer, address contractor, uint rate, uint256 date);
event CommissionsChangeEvt(uint8[5] commissions, uint256 date);
mapping (uint256 => string) public ticketTypes;
// 150000 Gwei
uint256 constant public MIN_TICKET_BASE_VALUE = 150000000000000;
uint256 public ticketBaseValue;
constructor(uint8[5] _commissions, address _businessOwner) public {
ticketBaseValue = MIN_TICKET_BASE_VALUE;
commissions = _commissions;
businessOwner = _businessOwner;
}
// Only listed tickets
modifier onlyExistingTicket(uint256 _amount) {
require(bytes(ticketTypes[_amount]).length > 0);
_;
}
// Update the ticket base value
// a ticket value is the amount of ether allowed to the ticket in order to
// be used
function updateTicketBaseValue(uint256 _value) public
onlyContractOwner()
{
// Cant put a value below the minimal value
require(_value >= MIN_TICKET_BASE_VALUE);
ticketBaseValue = _value;
}
// Update the commissions
function updateCommissions(uint8[5] _c) public
onlyContractOwner()
{
commissions = _c;
emit CommissionsChangeEvt(_c, now);
}
// Add a new ticket type
// Can update an old ticket type, for instance :
// ticketTypes[99] = "bronze"
// addTicketType(99, "wood")
// ticketTypes[99] = "wood"
// ticket 99 has been updated from "bronze" to "wood"
function addTicketType(uint256 _amount, string _key) public
onlyContractOwner()
{
ticketTypes[_amount] = _key;
}
// Allocates a ticket to an address and create tokens (accordingly to the value of the allocated ticket)
function allocateNewTicket(address _to, uint256 _amount)
public
payable
onlyExistingTicket(_amount)
returns (bool success)
{
uint256 costInWei = costOfTicket(_amount); // costs 0.3% of the amount (represented in wei, so its indeed 0.3% of ether value)
require(msg.value == costInWei);
activeTickets[_to] = Ticket({
balance: _amount,
tType: ticketTypes[_amount],
createdAt: now,
expireAt: now + 2 * 365 days,
contractor: 0x0,
hasReviewed: false
});
// Give minimal WEI value to a ticket
_to.transfer(ticketBaseValue);
// Price of the ticket transfered to the business owner address
businessOwner.transfer(costInWei - ticketBaseValue);
totalSupply += _amount;
circulatingSupply += _amount;
return true;
}
// Checks if an address can handle the ticket type
function isTicketValid(address _ticketAddr)
public
view
returns (bool valid)
{
if (activeTickets[_ticketAddr].contractor == 0x0 && now < activeTickets[_ticketAddr].expireAt) {
return true;
}
return false;
}
// A ticket credit the contractor balance. Sets its balance to 0 and adds the value to the contractor balance
// It triggers Consume event for logs
function creditContractor(address _contractor)
public
returns (bool success)
{
require(isTicketValid(msg.sender));
uint256 value = activeTickets[msg.sender].balance;
activeTickets[msg.sender].balance = 0;
contractors[_contractor].balance += value;
contractors[_contractor].nbCredittedTickets += 1;
activeTickets[msg.sender].contractor = _contractor;
emit CreditEvt(msg.sender, _contractor, activeTickets[msg.sender].tType, now);
return true;
}
// Publish a review and rate the ticket's contractor (only consumed tickets can
// perform this action)
function publishReview(uint _reviewRate) public {
// Only ticket that hasn't published any review and that has been consumed
require(!activeTickets[msg.sender].hasReviewed && activeTickets[msg.sender].contractor != 0x0);
// Only between 0 and 5
require(_reviewRate >= 0 && _reviewRate <= 5);
// Add the review to the contractor of the ticket
contractors[activeTickets[msg.sender].contractor].reviews[_reviewRate] += 1;
activeTickets[msg.sender].hasReviewed = true;
emit ReviewEvt(msg.sender, activeTickets[msg.sender].contractor, _reviewRate, now);
}
// Calculate the average rating of a contractor
function reviewAverageOfContractor(address _address) public view returns (uint avg) {
// Percentage threshold
uint decreaseThreshold = 60;
// Apply a penalty of -1 for reviews = 0
int totReviews = int(contractors[_address].reviews[0]) * -1;
uint nbReviews = contractors[_address].reviews[0];
// TODO consider the number of reviews
for (uint i = 1; i <= 5; i++) {
totReviews += int(contractors[_address].reviews[i] * i);
nbReviews += contractors[_address].reviews[i];
}
if (nbReviews == 0) {
return 250;
}
// Too much penalties leads to 0, then force it to be 0, the average
// can't be negative
if (totReviews < 0) {
totReviews = 0;
}
uint percReviewsTickets = (nbReviews * 100 / contractors[_address].nbCredittedTickets);
avg = (uint(totReviews) * 100) / nbReviews;
if (percReviewsTickets >= decreaseThreshold) {
return avg;
}
// A rate < 60% on the number of reviews will decrease the rating average of
// the difference between the threshold and the % of reviews
// for instance a percent reviews of 50% will decrease the rating average
// of 10% (60% - 50%)
// This is to avoid abuse of the system, without this mecanism a contractor
// could stay with a average of 500 (the max) regardless of the number
// of ticket he used.
uint decreasePercent = decreaseThreshold - percReviewsTickets;
return avg - (avg / decreasePercent);
}
// Returns the commission for the contractor
function commissionForContractor(address _address) public view returns (uint8 c) {
return commissionForReviewAverageOf(reviewAverageOfContractor(_address));
}
// Returns the info of a ticket
function infoOfTicket(address _address) public view returns (uint256 balance, string tType, bool isValid, uint createdAt, uint expireAt, address contractor, bool hasReviewed) {
return (activeTickets[_address].balance, activeTickets[_address].tType, isTicketValid(_address), activeTickets[_address].createdAt, activeTickets[_address].expireAt, activeTickets[_address].contractor, activeTickets[_address].hasReviewed);
}
// Returns the contractor info
function infoOfContractor(address _address) public view returns(uint256 balance, uint256 debittedBalance, uint256 nbReviews, uint256 nbCredittedTickets, uint256 avg) {
for (uint i = 0; i <= 5; i++) {
nbReviews += contractors[_address].reviews[i];
}
return (contractors[_address].balance, contractors[_address].debittedBalance, nbReviews, contractors[_address].nbCredittedTickets, reviewAverageOfContractor(_address));
}
// Returns the balance of a contractor
function balanceOfContractor(address _address) public view returns (uint256 balance) {
return contractors[_address].balance;
}
// Detroy tokens from contractor balance.
// It triggers Debit event
function debit(uint256 _amount) public {
// Safe math and nobody can debit more than her balance
require(_amount <= contractors[msg.sender].balance && _amount <= circulatingSupply);
circulatingSupply -= _amount;
contractors[msg.sender].debittedBalance += contractors[msg.sender].balance;
contractors[msg.sender].balance -= _amount;
emit DebitEvt(msg.sender, _amount, commissionForContractor(msg.sender), now);
}
// Returns the cost of a ticket regarding its amount
// Returned value is represented in Wei
function costOfTicket(uint256 _amount) public view returns(uint256 cost) {
return (_amount * (0.003 * 1000000000000000000)) + ticketBaseValue;
}
// Calculate the commission regarding the rating (review average)
// Example with a commissions = [30, 30, 30, 25, 20]
// [0,3[ = 30% (DefaultCommission)
// [3,4[ = 25%
// [4,5[ = 20%
// A rating average of 3.8 = 25% of commission
function commissionForReviewAverageOf(uint _avg) public view returns (uint8 c) {
if (_avg >= 500) {
return commissions[4];
}
for (uint i = 0; i < 5; i++) {
if (_avg <= i * 100 || _avg < (i + 1) * 100) {
return commissions[i];
}
}
// Default commission when there is something wrong
return commissions[0];
}
}
|
Detroy tokens from contractor balance. It triggers Debit event Safe math and nobody can debit more than her balance
|
function debit(uint256 _amount) public {
require(_amount <= contractors[msg.sender].balance && _amount <= circulatingSupply);
circulatingSupply -= _amount;
contractors[msg.sender].debittedBalance += contractors[msg.sender].balance;
contractors[msg.sender].balance -= _amount;
emit DebitEvt(msg.sender, _amount, commissionForContractor(msg.sender), now);
}
| 14,111,606 |
[
1,
4986,
3800,
2430,
628,
6835,
280,
11013,
18,
2597,
11752,
1505,
3682,
871,
14060,
4233,
471,
290,
947,
973,
848,
443,
3682,
1898,
2353,
22336,
11013,
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,
443,
3682,
12,
11890,
5034,
389,
8949,
13,
1071,
288,
203,
3639,
2583,
24899,
8949,
1648,
6835,
1383,
63,
3576,
18,
15330,
8009,
12296,
597,
389,
8949,
1648,
5886,
1934,
1776,
3088,
1283,
1769,
203,
203,
3639,
5886,
1934,
1776,
3088,
1283,
3947,
389,
8949,
31,
203,
203,
3639,
6835,
1383,
63,
3576,
18,
15330,
8009,
323,
3682,
2344,
13937,
1011,
6835,
1383,
63,
3576,
18,
15330,
8009,
12296,
31,
203,
3639,
6835,
1383,
63,
3576,
18,
15330,
8009,
12296,
3947,
389,
8949,
31,
203,
203,
3639,
3626,
1505,
3682,
30990,
12,
3576,
18,
15330,
16,
389,
8949,
16,
1543,
19710,
1290,
8924,
280,
12,
3576,
18,
15330,
3631,
2037,
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
] |
pragma solidity 0.4.16;
library CommonLibrary {
struct Data {
mapping (uint => Node) nodes;
mapping (string => uint) nodesID;
mapping (string => uint16) nodeGroups;
uint16 nodeGroupID;
uint nodeID;
uint ownerNotationId;
uint addNodeAddressId;
}
struct Node {
string nodeName;
address producer;
address node;
uint256 date;
bool starmidConfirmed;
address[] outsourceConfirmed;
uint16[] nodeGroup;
uint8 producersPercent;
uint16 nodeSocialMedia;
}
function addNodeGroup(Data storage self, string _newNodeGroup) returns(bool _result, uint16 _id) {
if (self.nodeGroups[_newNodeGroup] == 0) {
_id = self.nodeGroupID += 1;
self.nodeGroups[_newNodeGroup] = self.nodeGroupID;
_result = true;
}
}
function addNode(
Data storage self,
string _newNode,
uint8 _producersPercent
) returns (bool _result, uint _id) {
if (self.nodesID[_newNode] < 1 && _producersPercent < 100) {
_id = self.nodeID += 1;
require(self.nodeID < 1000000000000);
self.nodes[self.nodeID].nodeName = _newNode;
self.nodes[self.nodeID].producer = msg.sender;
self.nodes[self.nodeID].date = block.timestamp;
self.nodes[self.nodeID].starmidConfirmed = false;
self.nodes[self.nodeID].producersPercent = _producersPercent;
self.nodesID[_newNode] = self.nodeID;
_result = true;
}
else _result = false;
}
function editNode(
Data storage self,
uint _nodeID,
address _nodeAddress,
bool _isNewProducer,
address _newProducer,
uint8 _newProducersPercent,
bool _starmidConfirmed
) returns (bool) {
if (_isNewProducer == true) {
self.nodes[_nodeID].node = _nodeAddress;
self.nodes[_nodeID].producer = _newProducer;
self.nodes[_nodeID].producersPercent = _newProducersPercent;
self.nodes[_nodeID].starmidConfirmed = _starmidConfirmed;
return true;
}
else {
self.nodes[_nodeID].node = _nodeAddress;
self.nodes[_nodeID].starmidConfirmed = _starmidConfirmed;
return true;
}
}
function addNodeAddress(Data storage self, uint _nodeID, address _nodeAddress) returns(bool _result, uint _id) {
if (msg.sender == self.nodes[_nodeID].producer) {
if (self.nodes[_nodeID].node == 0) {
self.nodes[_nodeID].node = _nodeAddress;
_id = self.addNodeAddressId += 1;//for event count
_result = true;
}
else _result = false;
}
else _result = false;
}
//-----------------------------------------Starmid Exchange functions
function stockMinSellPrice(StarCoinLibrary.Data storage self, uint _buyPrice, uint _node) constant returns (uint _minSellPrice) {
_minSellPrice = _buyPrice + 1;
for (uint i = 0; i < self.stockSellOrderPrices[_node].length; i++) {
if(self.stockSellOrderPrices[_node][i] < _minSellPrice) _minSellPrice = self.stockSellOrderPrices[_node][i];
}
}
function stockMaxBuyPrice (StarCoinLibrary.Data storage self, uint _sellPrice, uint _node) constant returns (uint _maxBuyPrice) {
_maxBuyPrice = _sellPrice - 1;
for (uint i = 0; i < self.stockBuyOrderPrices[_node].length; i++) {
if(self.stockBuyOrderPrices[_node][i] > _maxBuyPrice) _maxBuyPrice = self.stockBuyOrderPrices[_node][i];
}
}
function stockDeleteFirstOrder(StarCoinLibrary.Data storage self, uint _node, uint _price, bool _isStockSellOrders) {
if (_isStockSellOrders == true) uint _length = self.stockSellOrders[_node][_price].length;
else _length = self.stockBuyOrders[_node][_price].length;
for (uint ii = 0; ii < _length - 1; ii++) {
if (_isStockSellOrders == true) self.stockSellOrders[_node][_price][ii] = self.stockSellOrders[_node][_price][ii + 1];
else self.stockBuyOrders[_node][_price][ii] = self.stockBuyOrders[_node][_price][ii + 1];
}
if (_isStockSellOrders == true) {
delete self.stockSellOrders[_node][_price][self.stockSellOrders[_node][_price].length - 1];
self.stockSellOrders[_node][_price].length--;
//Delete _price from stockSellOrderPrices[_node][] if it's the last order
if (self.stockSellOrders[_node][_price].length == 0) {
uint fromArg = 99999;
for (uint8 iii = 0; iii < self.stockSellOrderPrices[_node].length - 1; iii++) {
if (self.stockSellOrderPrices[_node][iii] == _price) {
fromArg = iii;
}
if (fromArg != 99999 && iii >= fromArg) self.stockSellOrderPrices[_node][iii] = self.stockSellOrderPrices[_node][iii + 1];
}
delete self.stockSellOrderPrices[_node][self.stockSellOrderPrices[_node].length-1];
self.stockSellOrderPrices[_node].length--;
}
}
else {
delete self.stockBuyOrders[_node][_price][self.stockBuyOrders[_node][_price].length - 1];
self.stockBuyOrders[_node][_price].length--;
//Delete _price from stockBuyOrderPrices[_node][] if it's the last order
if (self.stockBuyOrders[_node][_price].length == 0) {
fromArg = 99999;
for (iii = 0; iii < self.stockBuyOrderPrices[_node].length - 1; iii++) {
if (self.stockBuyOrderPrices[_node][iii] == _price) {
fromArg = iii;
}
if (fromArg != 99999 && iii >= fromArg) self.stockBuyOrderPrices[_node][iii] = self.stockBuyOrderPrices[_node][iii + 1];
}
delete self.stockBuyOrderPrices[_node][self.stockBuyOrderPrices[_node].length-1];
self.stockBuyOrderPrices[_node].length--;
}
}
}
function stockSaveOwnerInfo(StarCoinLibrary.Data storage self, uint _node, uint _amount, address _buyer, address _seller, uint _price) {
//--------------------------------------_buyer
self.StockOwnersBuyPrice[_buyer][_node].sumPriceAmount += _amount*_price;
self.StockOwnersBuyPrice[_buyer][_node].sumDateAmount += _amount*block.timestamp;
self.StockOwnersBuyPrice[_buyer][_node].sumAmount += _amount;
uint16 _thisNode = 0;
for (uint16 i6 = 0; i6 < self.stockOwnerInfo[_buyer].nodes.length; i6++) {
if (self.stockOwnerInfo[_buyer].nodes[i6] == _node) _thisNode = 1;
}
if (_thisNode == 0) self.stockOwnerInfo[_buyer].nodes.push(_node);
//--------------------------------------_seller
if(self.StockOwnersBuyPrice[_seller][_node].sumPriceAmount > 0) {
self.StockOwnersBuyPrice[_seller][_node].sumPriceAmount -= _amount*_price;
self.StockOwnersBuyPrice[_buyer][_node].sumDateAmount -= _amount*block.timestamp;
self.StockOwnersBuyPrice[_buyer][_node].sumAmount -= _amount;
}
_thisNode = 0;
for (i6 = 0; i6 < self.stockOwnerInfo[_seller].nodes.length; i6++) {
if (self.stockOwnerInfo[_seller].nodes[i6] == _node) _thisNode = i6;
}
if (_thisNode > 0) {
for (uint ii = _thisNode; ii < self.stockOwnerInfo[msg.sender].nodes.length - 1; ii++) {
self.stockOwnerInfo[msg.sender].nodes[ii] = self.stockOwnerInfo[msg.sender].nodes[ii + 1];
}
delete self.stockOwnerInfo[msg.sender].nodes[self.stockOwnerInfo[msg.sender].nodes.length - 1];
}
}
function deleteStockBuyOrder(StarCoinLibrary.Data storage self, uint _iii, uint _node, uint _price) {
for (uint ii = _iii; ii < self.stockBuyOrders[_node][_price].length - 1; ii++) {
self.stockBuyOrders[_node][_price][ii] = self.stockBuyOrders[_node][_price][ii + 1];
}
delete self.stockBuyOrders[_node][_price][self.stockBuyOrders[_node][_price].length - 1];
self.stockBuyOrders[_node][_price].length--;
//Delete _price from stockBuyOrderPrices[_node][] if it's the last order
if (self.stockBuyOrders[_node][_price].length == 0) {
uint _fromArg = 99999;
for (_iii = 0; _iii < self.stockBuyOrderPrices[_node].length - 1; _iii++) {
if (self.stockBuyOrderPrices[_node][_iii] == _price) {
_fromArg = _iii;
}
if (_fromArg != 99999 && _iii >= _fromArg) self.stockBuyOrderPrices[_node][_iii] = self.stockBuyOrderPrices[_node][_iii + 1];
}
delete self.stockBuyOrderPrices[_node][self.stockBuyOrderPrices[_node].length-1];
self.stockBuyOrderPrices[_node].length--;
}
}
function deleteStockSellOrder(StarCoinLibrary.Data storage self, uint _iii, uint _node, uint _price) {
for (uint ii = _iii; ii < self.stockSellOrders[_node][_price].length - 1; ii++) {
self.stockSellOrders[_node][_price][ii] = self.stockSellOrders[_node][_price][ii + 1];
}
delete self.stockSellOrders[_node][_price][self.stockSellOrders[_node][_price].length - 1];
self.stockSellOrders[_node][_price].length--;
//Delete _price from stockSellOrderPrices[_node][] if it's the last order
if (self.stockSellOrders[_node][_price].length == 0) {
uint _fromArg = 99999;
for (_iii = 0; _iii < self.stockSellOrderPrices[_node].length - 1; _iii++) {
if (self.stockSellOrderPrices[_node][_iii] == _price) {
_fromArg = _iii;
}
if (_fromArg != 99999 && _iii >= _fromArg) self.stockSellOrderPrices[_node][_iii] = self.stockSellOrderPrices[_node][_iii + 1];
}
delete self.stockSellOrderPrices[_node][self.stockSellOrderPrices[_node].length-1];
self.stockSellOrderPrices[_node].length--;
}
}
}
library StarCoinLibrary {
struct Data {
uint256 lastMint;
mapping (address => uint256) balanceOf;
mapping (address => uint256) frozen;
uint32 ordersId;
mapping (uint256 => orderInfo[]) buyOrders;
mapping (uint256 => orderInfo[]) sellOrders;
mapping (address => mapping (uint => uint)) stockBalanceOf;
mapping (address => mapping (uint => uint)) stockFrozen;
mapping (uint => uint) emissionLimits;
uint32 stockOrdersId;
mapping (uint => emissionNodeInfo) emissions;
mapping (uint => mapping (uint256 => stockOrderInfo[])) stockBuyOrders;
mapping (uint => mapping (uint256 => stockOrderInfo[])) stockSellOrders;
mapping (address => mapping (uint => uint)) lastDividends;
mapping (address => mapping (uint => averageBuyPrice)) StockOwnersBuyPrice;
mapping (address => ownerInfo) stockOwnerInfo;
uint[] buyOrderPrices;
uint[] sellOrderPrices;
mapping (uint => uint[]) stockBuyOrderPrices;
mapping (uint => uint[]) stockSellOrderPrices;
mapping (address => uint) pendingWithdrawals;
}
struct orderInfo {
uint date;
address client;
uint256 amount;
uint256 price;
bool isBuyer;
uint orderId;
}
struct emissionNodeInfo {
uint emissionNumber;
uint date;
}
struct stockOrderInfo {
uint date;
address client;
uint256 amount;
uint256 price;
bool isBuyer;
uint orderId;
uint node;
}
struct averageBuyPrice {
uint sumPriceAmount;
uint sumDateAmount;
uint sumAmount;
}
struct ownerInfo {
uint index;
uint[] nodes;
}
event Transfer(address indexed from, address indexed to, uint256 value);
event TradeHistory(uint date, address buyer, address seller, uint price, uint amount, uint orderId);
function buyOrder(Data storage self, uint256 _buyPrice) returns (uint[4] _results) {
uint _remainingValue = msg.value;
uint256[4] memory it;
if (minSellPrice(self, _buyPrice) != _buyPrice + 1) {
it[3] = self.sellOrderPrices.length;
for (it[1] = 0; it[1] < it[3]; it[1]++) {
uint _minPrice = minSellPrice(self, _buyPrice);
it[2] = self.sellOrders[_minPrice].length;
for (it[0] = 0; it[0] < it[2]; it[0]++) {
uint _amount = _remainingValue/_minPrice;
if (_amount >= self.sellOrders[_minPrice][0].amount) {
//buy starcoins for ether
self.balanceOf[msg.sender] += self.sellOrders[_minPrice][0].amount;// adds the amount to buyer's balance
self.frozen[self.sellOrders[_minPrice][0].client] -= self.sellOrders[_minPrice][0].amount;// subtracts the amount from seller's frozen balance
Transfer(self.sellOrders[_minPrice][0].client, msg.sender, self.sellOrders[_minPrice][0].amount);
//transfer ether to seller
uint256 amountTransfer = _minPrice*self.sellOrders[_minPrice][0].amount;
self.pendingWithdrawals[self.sellOrders[_minPrice][0].client] += amountTransfer;
//save the transaction
TradeHistory(block.timestamp, msg.sender, self.sellOrders[_minPrice][0].client, _minPrice, self.sellOrders[_minPrice][0].amount,
self.sellOrders[_minPrice][0].orderId);
_remainingValue -= amountTransfer;
_results[0] += self.sellOrders[_minPrice][0].amount;
//delete sellOrders[_minPrice][0] and move each element
deleteFirstOrder(self, _minPrice, true);
if (_remainingValue/_minPrice < 1) break;
}
else {
//edit sellOrders[_minPrice][0]
self.sellOrders[_minPrice][0].amount = self.sellOrders[_minPrice][0].amount - _amount;
//buy starcoins for ether
self.balanceOf[msg.sender] += _amount;// adds the _amount to buyer's balance
self.frozen[self.sellOrders[_minPrice][0].client] -= _amount;// subtracts the _amount from seller's frozen balance
Transfer(self.sellOrders[_minPrice][0].client, msg.sender, _amount);
//save the transaction
TradeHistory(block.timestamp, msg.sender, self.sellOrders[_minPrice][0].client, _minPrice, _amount, self.sellOrders[_minPrice][0].orderId);
//transfer ether to seller
uint256 amountTransfer1 = _amount*_minPrice;
self.pendingWithdrawals[self.sellOrders[_minPrice][0].client] += amountTransfer1;
_remainingValue -= amountTransfer1;
_results[0] += _amount;
if(_remainingValue/_minPrice < 1) {
_results[3] = 1;
break;
}
}
}
if (_remainingValue/_minPrice < 1) {
_results[3] = 1;
break;
}
}
if(_remainingValue/_buyPrice < 1)
self.pendingWithdrawals[msg.sender] += _remainingValue;//returns change to buyer
}
if (minSellPrice(self, _buyPrice) == _buyPrice + 1 && _remainingValue/_buyPrice >= 1) {
//save new order
_results[1] = _remainingValue/_buyPrice;
if (_remainingValue - _results[1]*_buyPrice > 0)
self.pendingWithdrawals[msg.sender] += _remainingValue - _results[1]*_buyPrice;//returns change to buyer
self.ordersId += 1;
_results[2] = self.ordersId;
self.buyOrders[_buyPrice].push(orderInfo( block.timestamp, msg.sender, _results[1], _buyPrice, true, self.ordersId));
_results[3] = 1;
//Add _buyPrice to buyOrderPrices[]
it[0] = 99999;
for (it[1] = 0; it[1] < self.buyOrderPrices.length; it[1]++) {
if (self.buyOrderPrices[it[1]] == _buyPrice)
it[0] = it[1];
}
if (it[0] == 99999)
self.buyOrderPrices.push(_buyPrice);
}
}
function minSellPrice(Data storage self, uint _buyPrice) constant returns (uint _minSellPrice) {
_minSellPrice = _buyPrice + 1;
for (uint i = 0; i < self.sellOrderPrices.length; i++) {
if(self.sellOrderPrices[i] < _minSellPrice) _minSellPrice = self.sellOrderPrices[i];
}
}
function sellOrder(Data storage self, uint256 _sellPrice, uint _amount) returns (uint[4] _results) {
uint _remainingAmount = _amount;
require(self.balanceOf[msg.sender] >= _amount);
uint256[4] memory it;
if (maxBuyPrice(self, _sellPrice) != _sellPrice - 1) {
it[3] = self.buyOrderPrices.length;
for (it[1] = 0; it[1] < it[3]; it[1]++) {
uint _maxPrice = maxBuyPrice(self, _sellPrice);
it[2] = self.buyOrders[_maxPrice].length;
for (it[0] = 0; it[0] < it[2]; it[0]++) {
if (_remainingAmount >= self.buyOrders[_maxPrice][0].amount) {
//sell starcoins for ether
self.balanceOf[msg.sender] -= self.buyOrders[_maxPrice][0].amount;// subtracts amount from seller's balance
self.balanceOf[self.buyOrders[_maxPrice][0].client] += self.buyOrders[_maxPrice][0].amount;// adds the amount to buyer's balance
Transfer(msg.sender, self.buyOrders[_maxPrice][0].client, self.buyOrders[_maxPrice][0].amount);
//transfer ether to seller
uint _amountTransfer = _maxPrice*self.buyOrders[_maxPrice][0].amount;
self.pendingWithdrawals[msg.sender] += _amountTransfer;
//save the transaction
TradeHistory(block.timestamp, self.buyOrders[_maxPrice][0].client, msg.sender, _maxPrice, self.buyOrders[_maxPrice][0].amount,
self.buyOrders[_maxPrice][0].orderId);
_remainingAmount -= self.buyOrders[_maxPrice][0].amount;
_results[0] += self.buyOrders[_maxPrice][0].amount;
//delete buyOrders[_maxPrice][0] and move each element
deleteFirstOrder(self, _maxPrice, false);
if(_remainingAmount < 1) break;
}
else {
//edit buyOrders[_maxPrice][0]
self.buyOrders[_maxPrice][0].amount = self.buyOrders[_maxPrice][0].amount-_remainingAmount;
//buy starcoins for ether
self.balanceOf[msg.sender] -= _remainingAmount;// subtracts amount from seller's balance
self.balanceOf[self.buyOrders[_maxPrice][0].client] += _remainingAmount;// adds the amount to buyer's balance
Transfer(msg.sender, self.buyOrders[_maxPrice][0].client, _remainingAmount);
//save the transaction
TradeHistory(block.timestamp, self.buyOrders[_maxPrice][0].client, msg.sender, _maxPrice, _remainingAmount, self.buyOrders[_maxPrice][0].orderId);
//transfer ether to seller
uint256 amountTransfer1 = _maxPrice*_remainingAmount;
self.pendingWithdrawals[msg.sender] += amountTransfer1;
_results[0] += _remainingAmount;
_remainingAmount = 0;
break;
}
}
if (_remainingAmount<1) {
_results[3] = 1;
break;
}
}
}
if (maxBuyPrice(self, _sellPrice) == _sellPrice - 1 && _remainingAmount >= 1) {
//save new order
_results[1] = _remainingAmount;
self.ordersId += 1;
_results[2] = self.ordersId;
self.sellOrders[_sellPrice].push(orderInfo( block.timestamp, msg.sender, _results[1], _sellPrice, false, _results[2]));
_results[3] = 1;
//transfer starcoins to the frozen balance
self.frozen[msg.sender] += _remainingAmount;
self.balanceOf[msg.sender] -= _remainingAmount;
//Add _sellPrice to sellOrderPrices[]
it[0] = 99999;
for (it[1] = 0; it[1] < self.sellOrderPrices.length; it[1]++) {
if (self.sellOrderPrices[it[1]] == _sellPrice)
it[0] = it[1];
}
if (it[0] == 99999)
self.sellOrderPrices.push(_sellPrice);
}
}
function maxBuyPrice (Data storage self, uint _sellPrice) constant returns (uint _maxBuyPrice) {
_maxBuyPrice = _sellPrice - 1;
for (uint i = 0; i < self.buyOrderPrices.length; i++) {
if(self.buyOrderPrices[i] > _maxBuyPrice) _maxBuyPrice = self.buyOrderPrices[i];
}
}
function deleteFirstOrder(Data storage self, uint _price, bool _isSellOrders) {
if (_isSellOrders == true) uint _length = self.sellOrders[_price].length;
else _length = self.buyOrders[_price].length;
for (uint ii = 0; ii < _length - 1; ii++) {
if (_isSellOrders == true) self.sellOrders[_price][ii] = self.sellOrders[_price][ii + 1];
else self.buyOrders[_price][ii] = self.buyOrders[_price][ii+1];
}
if (_isSellOrders == true) {
delete self.sellOrders[_price][self.sellOrders[_price].length - 1];
self.sellOrders[_price].length--;
//Delete _price from sellOrderPrices[] if it's the last order
if (_length == 1) {
uint _fromArg = 99999;
for (uint8 iii = 0; iii < self.sellOrderPrices.length - 1; iii++) {
if (self.sellOrderPrices[iii] == _price) {
_fromArg = iii;
}
if (_fromArg != 99999 && iii >= _fromArg) self.sellOrderPrices[iii] = self.sellOrderPrices[iii + 1];
}
delete self.sellOrderPrices[self.sellOrderPrices.length-1];
self.sellOrderPrices.length--;
}
}
else {
delete self.buyOrders[_price][self.buyOrders[_price].length - 1];
self.buyOrders[_price].length--;
//Delete _price from buyOrderPrices[] if it's the last order
if (_length == 1) {
_fromArg = 99999;
for (iii = 0; iii < self.buyOrderPrices.length - 1; iii++) {
if (self.buyOrderPrices[iii] == _price) {
_fromArg = iii;
}
if (_fromArg != 99999 && iii >= _fromArg) self.buyOrderPrices[iii] = self.buyOrderPrices[iii + 1];
}
delete self.buyOrderPrices[self.buyOrderPrices.length-1];
self.buyOrderPrices.length--;
}
}
}
function cancelBuyOrder(Data storage self, uint _thisOrderID, uint _price) public returns(bool) {
for (uint8 iii = 0; iii < self.buyOrders[_price].length; iii++) {
if (self.buyOrders[_price][iii].orderId == _thisOrderID) {
//delete buyOrders[_price][iii] and move each element
require(msg.sender == self.buyOrders[_price][iii].client);
uint _remainingValue = self.buyOrders[_price][iii].price*self.buyOrders[_price][iii].amount;
for (uint ii = iii; ii < self.buyOrders[_price].length - 1; ii++) {
self.buyOrders[_price][ii] = self.buyOrders[_price][ii + 1];
}
delete self.buyOrders[_price][self.buyOrders[_price].length - 1];
self.buyOrders[_price].length--;
self.pendingWithdrawals[msg.sender] += _remainingValue;//returns ether to buyer
break;
}
}
//Delete _price from buyOrderPrices[] if it's the last order
if (self.buyOrders[_price].length == 0) {
uint _fromArg = 99999;
for (uint8 iiii = 0; iiii < self.buyOrderPrices.length - 1; iiii++) {
if (self.buyOrderPrices[iiii] == _price) {
_fromArg = iiii;
}
if (_fromArg != 99999 && iiii >= _fromArg) self.buyOrderPrices[iiii] = self.buyOrderPrices[iiii + 1];
}
delete self.buyOrderPrices[self.buyOrderPrices.length-1];
self.buyOrderPrices.length--;
}
return true;
}
function cancelSellOrder(Data storage self, uint _thisOrderID, uint _price) public returns(bool) {
for (uint8 iii = 0; iii < self.sellOrders[_price].length; iii++) {
if (self.sellOrders[_price][iii].orderId == _thisOrderID) {
require(msg.sender == self.sellOrders[_price][iii].client);
//return starcoins from the frozen balance to seller
self.frozen[msg.sender] -= self.sellOrders[_price][iii].amount;
self.balanceOf[msg.sender] += self.sellOrders[_price][iii].amount;
//delete sellOrders[_price][iii] and move each element
for (uint ii = iii; ii < self.sellOrders[_price].length - 1; ii++) {
self.sellOrders[_price][ii] = self.sellOrders[_price][ii + 1];
}
delete self.sellOrders[_price][self.sellOrders[_price].length - 1];
self.sellOrders[_price].length--;
break;
}
}
//Delete _price from sellOrderPrices[] if it's the last order
if (self.sellOrders[_price].length == 0) {
uint _fromArg = 99999;
for (uint8 iiii = 0; iiii < self.sellOrderPrices.length - 1; iiii++) {
if (self.sellOrderPrices[iiii] == _price) {
_fromArg = iiii;
}
if (_fromArg != 99999 && iiii >= _fromArg)
self.sellOrderPrices[iiii] = self.sellOrderPrices[iiii + 1];
}
delete self.sellOrderPrices[self.sellOrderPrices.length-1];
self.sellOrderPrices.length--;
}
return true;
}
}
library StarmidLibrary {
event Transfer(address indexed from, address indexed to, uint256 value);
event StockTransfer(address indexed from, address indexed to, uint indexed node, uint256 value);
event StockTradeHistory(uint node, uint date, address buyer, address seller, uint price, uint amount, uint orderId);
function stockBuyOrder(StarCoinLibrary.Data storage self, uint _node, uint256 _buyPrice, uint _amount) public returns (uint[4] _results) {
require(self.balanceOf[msg.sender] >= _buyPrice*_amount);
uint256[4] memory it;
if (CommonLibrary.stockMinSellPrice(self, _buyPrice, _node) != _buyPrice + 1) {
it[3] = self.stockSellOrderPrices[_node].length;
for (it[1] = 0; it[1] < it[3]; it[1]++) {
uint minPrice = CommonLibrary.stockMinSellPrice(self, _buyPrice, _node);
it[2] = self.stockSellOrders[_node][minPrice].length;
for (it[0] = 0; it[0] < it[2]; it[0]++) {
if (_amount >= self.stockSellOrders[_node][minPrice][0].amount) {
//buy stocks for starcoins
self.stockBalanceOf[msg.sender][_node] += self.stockSellOrders[_node][minPrice][0].amount;// add the amount to buyer's balance
self.stockFrozen[self.stockSellOrders[_node][minPrice][0].client][_node] -= self.stockSellOrders[_node][minPrice][0].amount;// subtracts amount from seller's frozen stock balance
//write stockOwnerInfo and stockOwners for dividends
CommonLibrary.stockSaveOwnerInfo(self, _node, self.stockSellOrders[_node][minPrice][0].amount, msg.sender, self.stockSellOrders[_node][minPrice][0].client, minPrice);
//transfer starcoins to seller
self.balanceOf[msg.sender] -= self.stockSellOrders[_node][minPrice][0].amount*minPrice;// subtracts amount from buyer's balance
self.balanceOf[self.stockSellOrders[_node][minPrice][0].client] += self.stockSellOrders[_node][minPrice][0].amount*minPrice;// adds the amount to seller's balance
Transfer(self.stockSellOrders[_node][minPrice][0].client, msg.sender, self.stockSellOrders[_node][minPrice][0].amount*minPrice);
//save the transaction into event StocksTradeHistory;
StockTradeHistory(_node, block.timestamp, msg.sender, self.stockSellOrders[_node][minPrice][0].client, minPrice,
self.stockSellOrders[_node][minPrice][0].amount, self.stockSellOrders[_node][minPrice][0].orderId);
_amount -= self.stockSellOrders[_node][minPrice][0].amount;
_results[0] += self.stockSellOrders[_node][minPrice][0].amount;
//delete stockSellOrders[_node][minPrice][0] and move each element
CommonLibrary.stockDeleteFirstOrder(self, _node, minPrice, true);
if (_amount<1) break;
}
else {
//edit stockSellOrders[_node][minPrice][0]
self.stockSellOrders[_node][minPrice][0].amount -= _amount;
//buy stocks for starcoins
self.stockBalanceOf[msg.sender][_node] += _amount;// adds the _amount to buyer's balance
self.stockFrozen[self.stockSellOrders[_node][minPrice][0].client][_node] -= _amount;// subtracts _amount from seller's frozen stock balance
//write stockOwnerInfo and stockOwners for dividends
CommonLibrary.stockSaveOwnerInfo(self, _node, _amount, msg.sender, self.stockSellOrders[_node][minPrice][0].client, minPrice);
//transfer starcoins to seller
self.balanceOf[msg.sender] -= _amount*minPrice;// subtracts _amount from buyer's balance
self.balanceOf[self.stockSellOrders[_node][minPrice][0].client] += _amount*minPrice;// adds the amount to seller's balance
Transfer(self.stockSellOrders[_node][minPrice][0].client, msg.sender, _amount*minPrice);
//save the transaction into event StocksTradeHistory;
StockTradeHistory(_node, block.timestamp, msg.sender, self.stockSellOrders[_node][minPrice][0].client, minPrice,
_amount, self.stockSellOrders[_node][minPrice][0].orderId);
_results[0] += _amount;
_amount = 0;
break;
}
}
if(_amount < 1) {
_results[3] = 1;
break;
}
}
}
if (CommonLibrary.stockMinSellPrice(self, _buyPrice, _node) == _buyPrice + 1 && _amount >= 1) {
//save new order
_results[1] = _amount;
self.stockOrdersId += 1;
_results[2] = self.stockOrdersId;
self.stockBuyOrders[_node][_buyPrice].push(StarCoinLibrary.stockOrderInfo(block.timestamp, msg.sender, _results[1], _buyPrice, true, self.stockOrdersId, _node));
_results[3] = 1;
//transfer starcoins to the frozen balance
self.frozen[msg.sender] += _amount*_buyPrice;
self.balanceOf[msg.sender] -= _amount*_buyPrice;
//Add _buyPrice to stockBuyOrderPrices[_node][]
it[0] = 99999;
for (it[1] = 0; it[1] < self.stockBuyOrderPrices[_node].length; it[1]++) {
if (self.stockBuyOrderPrices[_node][it[1]] == _buyPrice)
it[0] = it[1];
}
if (it[0] == 99999) self.stockBuyOrderPrices[_node].push(_buyPrice);
}
}
function stockSellOrder(StarCoinLibrary.Data storage self, uint _node, uint _sellPrice, uint _amount) returns (uint[4] _results) {
require(self.stockBalanceOf[msg.sender][_node] >= _amount);
uint[4] memory it;
if (CommonLibrary.stockMaxBuyPrice(self, _sellPrice, _node) != _sellPrice - 1) {
it[3] = self.stockBuyOrderPrices[_node].length;
for (it[1] = 0; it[1] < it[3]; it[1]++) {
uint _maxPrice = CommonLibrary.stockMaxBuyPrice(self, _sellPrice, _node);
it[2] = self.stockBuyOrders[_node][_maxPrice].length;
for (it[0] = 0; it[0] < it[2]; it[0]++) {
if (_amount >= self.stockBuyOrders[_node][_maxPrice][0].amount) {
//sell stocks for starcoins
self.stockBalanceOf[msg.sender][_node] -= self.stockBuyOrders[_node][_maxPrice][0].amount;// subtracts the _amount from seller's balance
self.stockBalanceOf[self.stockBuyOrders[_node][_maxPrice][0].client][_node] += self.stockBuyOrders[_node][_maxPrice][0].amount;// adds the _amount to buyer's balance
//write stockOwnerInfo and stockOwners for dividends
CommonLibrary.stockSaveOwnerInfo(self, _node, self.stockBuyOrders[_node][_maxPrice][0].amount, self.stockBuyOrders[_node][_maxPrice][0].client, msg.sender, _maxPrice);
//transfer starcoins to seller
self.balanceOf[msg.sender] += self.stockBuyOrders[_node][_maxPrice][0].amount*_maxPrice;// adds the amount to buyer's balance
self.frozen[self.stockBuyOrders[_node][_maxPrice][0].client] -= self.stockBuyOrders[_node][_maxPrice][0].amount*_maxPrice;// subtracts amount from seller's frozen balance
Transfer(self.stockBuyOrders[_node][_maxPrice][0].client, msg.sender, self.stockBuyOrders[_node][_maxPrice][0].amount*_maxPrice);
//save the transaction
StockTradeHistory(_node, block.timestamp, self.stockBuyOrders[_node][_maxPrice][0].client, msg.sender,
_maxPrice, self.stockBuyOrders[_node][_maxPrice][0].amount, self.stockBuyOrders[_node][_maxPrice][0].orderId);
_amount -= self.stockBuyOrders[_node][_maxPrice][0].amount;
_results[0] += self.stockBuyOrders[_node][_maxPrice][0].amount;
//delete stockBuyOrders[_node][_maxPrice][0] and move each element
CommonLibrary.stockDeleteFirstOrder(self, _node, _maxPrice, false);
if(_amount < 1) break;
}
else {
//edit stockBuyOrders[_node][_maxPrice][0]
self.stockBuyOrders[_node][_maxPrice][0].amount -= _amount;
//sell stocks for starcoins
self.stockBalanceOf[msg.sender][_node] -= _amount;// subtracts _amount from seller's balance
self.stockBalanceOf[self.stockBuyOrders[_node][_maxPrice][0].client][_node] += _amount;// adds the _amount to buyer's balance
//write stockOwnerInfo and stockOwners for dividends
CommonLibrary.stockSaveOwnerInfo(self, _node, _amount, self.stockBuyOrders[_node][_maxPrice][0].client, msg.sender, _maxPrice);
//transfer starcoins to seller
self.balanceOf[msg.sender] += _amount*_maxPrice;// adds the _amount to buyer's balance
self.frozen[self.stockBuyOrders[_node][_maxPrice][0].client] -= _amount*_maxPrice;// subtracts _amount from seller's frozen balance
Transfer(self.stockBuyOrders[_node][_maxPrice][0].client, msg.sender, _amount*_maxPrice);
//save the transaction
StockTradeHistory(_node, block.timestamp, self.stockBuyOrders[_node][_maxPrice][0].client, msg.sender,
_maxPrice, _amount, self.stockBuyOrders[_node][_maxPrice][0].orderId);
_results[0] += _amount;
_amount = 0;
break;
}
}
if (_amount < 1) {
_results[3] = 1;
break;
}
}
}
if (CommonLibrary.stockMaxBuyPrice(self, _sellPrice, _node) == _sellPrice - 1 && _amount >= 1) {
//save new order
_results[1] = _amount;
self.stockOrdersId += 1;
_results[2] = self.stockOrdersId;
self.stockSellOrders[_node][_sellPrice].push(StarCoinLibrary.stockOrderInfo(block.timestamp, msg.sender, _results[1], _sellPrice, false, self.stockOrdersId, _node));
_results[3] = 1;
//transfer stocks to the frozen stock balance
self.stockFrozen[msg.sender][_node] += _amount;
self.stockBalanceOf[msg.sender][_node] -= _amount;
//Add _sellPrice to stockSellOrderPrices[_node][]
it[0] = 99999;
for (it[1] = 0; it[1] < self.stockSellOrderPrices[_node].length; it[1]++) {
if (self.stockSellOrderPrices[_node][it[1]] == _sellPrice)
it[0] = it[1];
}
if (it[0] == 99999)
self.stockSellOrderPrices[_node].push(_sellPrice);
}
}
function stockCancelBuyOrder(StarCoinLibrary.Data storage self, uint _node, uint _thisOrderID, uint _price) public returns(bool) {
for (uint iii = 0; iii < self.stockBuyOrders[_node][_price].length; iii++) {
if (self.stockBuyOrders[_node][_price][iii].orderId == _thisOrderID) {
require(msg.sender == self.stockBuyOrders[_node][_price][iii].client);
//return starcoins from the buyer`s frozen balance
self.frozen[msg.sender] -= self.stockBuyOrders[_node][_price][iii].amount*_price;
self.balanceOf[msg.sender] += self.stockBuyOrders[_node][_price][iii].amount*_price;
//delete stockBuyOrders[_node][_price][iii] and move each element
for (uint ii = iii; ii < self.stockBuyOrders[_node][_price].length - 1; ii++) {
self.stockBuyOrders[_node][_price][ii] = self.stockBuyOrders[_node][_price][ii + 1];
}
delete self.stockBuyOrders[_node][_price][self.stockBuyOrders[_node][_price].length - 1];
self.stockBuyOrders[_node][_price].length--;
break;
}
}
//Delete _price from stockBuyOrderPrices[_node][] if it's the last order
if (self.stockBuyOrders[_node][_price].length == 0) {
uint _fromArg = 99999;
for (iii = 0; iii < self.stockBuyOrderPrices[_node].length - 1; iii++) {
if (self.stockBuyOrderPrices[_node][iii] == _price) {
_fromArg = iii;
}
if (_fromArg != 99999 && iii >= _fromArg) self.stockBuyOrderPrices[_node][iii] = self.stockBuyOrderPrices[_node][iii + 1];
}
delete self.stockBuyOrderPrices[_node][self.stockBuyOrderPrices[_node].length-1];
self.stockBuyOrderPrices[_node].length--;
}
return true;
}
function stockCancelSellOrder(StarCoinLibrary.Data storage self, uint _node, uint _thisOrderID, uint _price) public returns(bool) {
for (uint iii = 0; iii < self.stockSellOrders[_node][_price].length; iii++) {
if (self.stockSellOrders[_node][_price][iii].orderId == _thisOrderID) {
require(msg.sender == self.stockSellOrders[_node][_price][iii].client);
//return stocks from the seller`s frozen stock balance
self.stockFrozen[msg.sender][_node] -= self.stockSellOrders[_node][_price][iii].amount;
self.stockBalanceOf[msg.sender][_node] += self.stockSellOrders[_node][_price][iii].amount;
//delete stockSellOrders[_node][_price][iii] and move each element
for (uint ii = iii; ii < self.stockSellOrders[_node][_price].length - 1; ii++) {
self.stockSellOrders[_node][_price][ii] = self.stockSellOrders[_node][_price][ii + 1];
}
delete self.stockSellOrders[_node][_price][self.stockSellOrders[_node][_price].length - 1];
self.stockSellOrders[_node][_price].length--;
break;
}
}
//Delete _price from stockSellOrderPrices[_node][] if it's the last order
if (self.stockSellOrders[_node][_price].length == 0) {
uint _fromArg = 99999;
for (iii = 0; iii < self.stockSellOrderPrices[_node].length - 1; iii++) {
if (self.stockSellOrderPrices[_node][iii] == _price) {
_fromArg = iii;
}
if (_fromArg != 99999 && iii >= _fromArg) self.stockSellOrderPrices[_node][iii] = self.stockSellOrderPrices[_node][iii + 1];
}
delete self.stockSellOrderPrices[_node][self.stockSellOrderPrices[_node].length-1];
self.stockSellOrderPrices[_node].length--;
}
return true;
}
}
library StarmidLibraryExtra {
event Transfer(address indexed from, address indexed to, uint256 value);
event StockTransfer(address indexed from, address indexed to, uint indexed node, uint256 value);
event StockTradeHistory(uint node, uint date, address buyer, address seller, uint price, uint amount, uint orderId);
event TradeHistory(uint date, address buyer, address seller, uint price, uint amount, uint orderId);
function buyCertainOrder(StarCoinLibrary.Data storage self, uint _price, uint _thisOrderID) returns (bool) {
uint _remainingValue = msg.value;
for (uint8 iii = 0; iii < self.sellOrders[_price].length; iii++) {
if (self.sellOrders[_price][iii].orderId == _thisOrderID) {
uint _amount = _remainingValue/_price;
require(_amount <= self.sellOrders[_price][iii].amount);
if (_amount == self.sellOrders[_price][iii].amount) {
//buy starcoins for ether
self.balanceOf[msg.sender] += self.sellOrders[_price][iii].amount;// adds the amount to buyer's balance
self.frozen[self.sellOrders[_price][iii].client] -= self.sellOrders[_price][iii].amount;// subtracts the amount from seller's frozen balance
Transfer(self.sellOrders[_price][iii].client, msg.sender, self.sellOrders[_price][iii].amount);
//transfer ether to seller
self.pendingWithdrawals[self.sellOrders[_price][iii].client] += _price*self.sellOrders[_price][iii].amount;
//save the transaction
TradeHistory(block.timestamp, msg.sender, self.sellOrders[_price][iii].client, _price, self.sellOrders[_price][iii].amount,
self.sellOrders[_price][iii].orderId);
_remainingValue -= _price*self.sellOrders[_price][iii].amount;
//delete sellOrders[_price][iii] and move each element
for (uint ii = iii; ii < self.sellOrders[_price].length - 1; ii++) {
self.sellOrders[_price][ii] = self.sellOrders[_price][ii + 1];
}
delete self.sellOrders[_price][self.sellOrders[_price].length - 1];
self.sellOrders[_price].length--;
//Delete _price from sellOrderPrices[] if it's the last order
if (self.sellOrders[_price].length == 0) {
uint fromArg = 99999;
for (ii = 0; ii < self.sellOrderPrices.length - 1; ii++) {
if (self.sellOrderPrices[ii] == _price) {
fromArg = ii;
}
if (fromArg != 99999 && ii >= fromArg)
self.sellOrderPrices[ii] = self.sellOrderPrices[ii + 1];
}
delete self.sellOrderPrices[self.sellOrderPrices.length-1];
self.sellOrderPrices.length--;
}
return true;
break;
}
else {
//edit sellOrders[_price][iii]
self.sellOrders[_price][iii].amount = self.sellOrders[_price][iii].amount - _amount;
//buy starcoins for ether
self.balanceOf[msg.sender] += _amount;// adds the _amount to buyer's balance
self.frozen[self.sellOrders[_price][iii].client] -= _amount;// subtracts the _amount from seller's frozen balance
Transfer(self.sellOrders[_price][iii].client, msg.sender, _amount);
//save the transaction
TradeHistory(block.timestamp, msg.sender, self.sellOrders[_price][iii].client, _price, _amount, self.sellOrders[_price][iii].orderId);
//transfer ether to seller
self.pendingWithdrawals[self.sellOrders[_price][iii].client] += _amount*_price;
_remainingValue -= _amount*_price;
return true;
break;
}
}
}
self.pendingWithdrawals[msg.sender] += _remainingValue;//returns change to buyer
}
function sellCertainOrder(StarCoinLibrary.Data storage self, uint _amount, uint _price, uint _thisOrderID) returns (bool) {
for (uint8 iii = 0; iii < self.buyOrders[_price].length; iii++) {
if (self.buyOrders[_price][iii].orderId == _thisOrderID) {
require(_amount <= self.buyOrders[_price][iii].amount && self.balanceOf[msg.sender] >= _amount);
if (_amount == self.buyOrders[_price][iii].amount) {
//sell starcoins for ether
self.balanceOf[msg.sender] -= self.buyOrders[_price][iii].amount;// subtracts amount from seller's balance
self.balanceOf[self.buyOrders[_price][iii].client] += self.buyOrders[_price][iii].amount;// adds the amount to buyer's balance
Transfer(msg.sender, self.buyOrders[_price][iii].client, self.buyOrders[_price][iii].amount);
//transfer ether to seller
uint _amountTransfer = _price*self.buyOrders[_price][iii].amount;
self.pendingWithdrawals[msg.sender] += _amountTransfer;
//save the transaction
TradeHistory(block.timestamp, self.buyOrders[_price][iii].client, msg.sender, _price, self.buyOrders[_price][iii].amount,
self.buyOrders[_price][iii].orderId);
_amount -= self.buyOrders[_price][iii].amount;
//delete buyOrders[_price][iii] and move each element
for (uint ii = iii; ii < self.buyOrders[_price].length - 1; ii++) {
self.buyOrders[_price][ii] = self.buyOrders[_price][ii + 1];
}
delete self.buyOrders[_price][self.buyOrders[_price].length - 1];
self.buyOrders[_price].length--;
//Delete _price from buyOrderPrices[] if it's the last order
if (self.buyOrders[_price].length == 0) {
uint _fromArg = 99999;
for (uint8 iiii = 0; iiii < self.buyOrderPrices.length - 1; iiii++) {
if (self.buyOrderPrices[iiii] == _price) {
_fromArg = iiii;
}
if (_fromArg != 99999 && iiii >= _fromArg) self.buyOrderPrices[iiii] = self.buyOrderPrices[iiii + 1];
}
delete self.buyOrderPrices[self.buyOrderPrices.length-1];
self.buyOrderPrices.length--;
}
return true;
break;
}
else {
//edit buyOrders[_price][iii]
self.buyOrders[_price][iii].amount = self.buyOrders[_price][iii].amount - _amount;
//buy starcoins for ether
self.balanceOf[msg.sender] -= _amount;// subtracts amount from seller's balance
self.balanceOf[self.buyOrders[_price][iii].client] += _amount;// adds the amount to buyer's balance
Transfer(msg.sender, self.buyOrders[_price][iii].client, _amount);
//save the transaction
TradeHistory(block.timestamp, self.buyOrders[_price][iii].client, msg.sender, _price, _amount, self.buyOrders[_price][iii].orderId);
//transfer ether to seller
self.pendingWithdrawals[msg.sender] += _price*_amount;
return true;
break;
}
}
}
}
function stockBuyCertainOrder(StarCoinLibrary.Data storage self, uint _node, uint _price, uint _amount, uint _thisOrderID) returns (bool) {
require(self.balanceOf[msg.sender] >= _price*_amount);
for (uint8 iii = 0; iii < self.stockSellOrders[_node][_price].length; iii++) {
if (self.stockSellOrders[_node][_price][iii].orderId == _thisOrderID) {
require(_amount <= self.stockSellOrders[_node][_price][iii].amount);
if (_amount == self.stockSellOrders[_node][_price][iii].amount) {
//buy stocks for starcoins
self.stockBalanceOf[msg.sender][_node] += self.stockSellOrders[_node][_price][iii].amount;// add the amount to buyer's balance
self.stockFrozen[self.stockSellOrders[_node][_price][iii].client][_node] -= self.stockSellOrders[_node][_price][iii].amount;// subtracts amount from seller's frozen stock balance
//write stockOwnerInfo and stockOwners for dividends
CommonLibrary.stockSaveOwnerInfo(self, _node, self.stockSellOrders[_node][_price][iii].amount, msg.sender, self.stockSellOrders[_node][_price][iii].client, _price);
//transfer starcoins to seller
self.balanceOf[msg.sender] -= self.stockSellOrders[_node][_price][iii].amount*_price;// subtracts amount from buyer's balance
self.balanceOf[self.stockSellOrders[_node][_price][iii].client] += self.stockSellOrders[_node][_price][iii].amount*_price;// adds the amount to seller's balance
Transfer(self.stockSellOrders[_node][_price][iii].client, msg.sender, self.stockSellOrders[_node][_price][iii].amount*_price);
//save the transaction into event StocksTradeHistory;
StockTradeHistory(_node, block.timestamp, msg.sender, self.stockSellOrders[_node][_price][iii].client, _price,
self.stockSellOrders[_node][_price][iii].amount, self.stockSellOrders[_node][_price][iii].orderId);
_amount -= self.stockSellOrders[_node][_price][iii].amount;
//delete stockSellOrders[_node][_price][iii] and move each element
CommonLibrary.deleteStockSellOrder(self, iii, _node, _price);
return true;
break;
}
else {
//edit stockSellOrders[_node][_price][iii]
self.stockSellOrders[_node][_price][iii].amount -= _amount;
//buy stocks for starcoins
self.stockBalanceOf[msg.sender][_node] += _amount;// adds the amount to buyer's balance
self.stockFrozen[self.stockSellOrders[_node][_price][iii].client][_node] -= _amount;// subtracts amount from seller's frozen stock balance
//write stockOwnerInfo and stockOwners for dividends
CommonLibrary.stockSaveOwnerInfo(self, _node, _amount, msg.sender, self.stockSellOrders[_node][_price][iii].client, _price);
//transfer starcoins to seller
self.balanceOf[msg.sender] -= _amount*_price;// subtracts amount from buyer's balance
self.balanceOf[self.stockSellOrders[_node][_price][iii].client] += _amount*_price;// adds the amount to seller's balance
Transfer(self.stockSellOrders[_node][_price][iii].client, msg.sender, _amount*_price);
//save the transaction into event StocksTradeHistory;
StockTradeHistory(_node, block.timestamp, msg.sender, self.stockSellOrders[_node][_price][iii].client, _price,
_amount, self.stockSellOrders[_node][_price][iii].orderId);
_amount = 0;
return true;
break;
}
}
}
}
function stockSellCertainOrder(StarCoinLibrary.Data storage self, uint _node, uint _price, uint _amount, uint _thisOrderID) returns (bool results) {
uint _remainingAmount = _amount;
for (uint8 iii = 0; iii < self.stockBuyOrders[_node][_price].length; iii++) {
if (self.stockBuyOrders[_node][_price][iii].orderId == _thisOrderID) {
require(_amount <= self.stockBuyOrders[_node][_price][iii].amount && self.stockBalanceOf[msg.sender][_node] >= _amount);
if (_remainingAmount == self.stockBuyOrders[_node][_price][iii].amount) {
//sell stocks for starcoins
self.stockBalanceOf[msg.sender][_node] -= self.stockBuyOrders[_node][_price][iii].amount;// subtracts amount from seller's balance
self.stockBalanceOf[self.stockBuyOrders[_node][_price][iii].client][_node] += self.stockBuyOrders[_node][_price][iii].amount;// adds the amount to buyer's balance
//write stockOwnerInfo and stockOwners for dividends
CommonLibrary.stockSaveOwnerInfo(self, _node, self.stockBuyOrders[_node][_price][iii].amount, self.stockBuyOrders[_node][_price][iii].client, msg.sender, _price);
//transfer starcoins to seller
self.balanceOf[msg.sender] += self.stockBuyOrders[_node][_price][iii].amount*_price;// adds the amount to buyer's balance
self.frozen[self.stockBuyOrders[_node][_price][iii].client] -= self.stockBuyOrders[_node][_price][iii].amount*_price;// subtracts amount from seller's frozen balance
Transfer(self.stockBuyOrders[_node][_price][iii].client, msg.sender, self.stockBuyOrders[_node][_price][iii].amount*_price);
//save the transaction
StockTradeHistory(_node, block.timestamp, self.stockBuyOrders[_node][_price][iii].client, msg.sender,
_price, self.stockBuyOrders[_node][_price][iii].amount, self.stockBuyOrders[_node][_price][iii].orderId);
_amount -= self.stockBuyOrders[_node][_price][iii].amount;
//delete stockBuyOrders[_node][_price][iii] and move each element
CommonLibrary.deleteStockBuyOrder(self, iii, _node, _price);
results = true;
break;
}
else {
//edit stockBuyOrders[_node][_price][0]
self.stockBuyOrders[_node][_price][iii].amount -= _amount;
//sell stocks for starcoins
self.stockBalanceOf[msg.sender][_node] -= _amount;// subtracts amount from seller's balance
self.stockBalanceOf[self.stockBuyOrders[_node][_price][iii].client][_node] += _amount;// adds the amount to buyer's balance
//write stockOwnerInfo and stockOwners for dividends
CommonLibrary.stockSaveOwnerInfo(self, _node, _amount, self.stockBuyOrders[_node][_price][iii].client, msg.sender, _price);
//transfer starcoins to seller
self.balanceOf[msg.sender] += _amount*_price;// adds the amount to buyer's balance
self.frozen[self.stockBuyOrders[_node][_price][iii].client] -= _amount*_price;// subtracts amount from seller's frozen balance
Transfer(self.stockBuyOrders[_node][_price][iii].client, msg.sender, _amount*_price);
//save the transaction
StockTradeHistory(_node, block.timestamp, self.stockBuyOrders[_node][_price][iii].client, msg.sender,
_price, _amount, self.stockBuyOrders[_node][_price][iii].orderId);
_amount = 0;
results = true;
break;
}
}
}
}
}
contract Nodes {
address public owner;
CommonLibrary.Data public vars;
mapping (address => string) public confirmationNodes;
uint confirmNodeId;
uint40 changePercentId;
uint40 pushNodeGroupId;
uint40 deleteNodeGroupId;
event NewNode(
uint256 id,
string nodeName,
uint8 producersPercent,
address producer,
uint date
);
event OwnerNotation(uint256 id, uint date, string newNotation);
event NewNodeGroup(uint16 id, string newNodeGroup);
event AddNodeAddress(uint id, uint nodeID, address nodeAdress);
event EditNode(
uint nodeID,
address nodeAdress,
address newProducer,
uint8 newProducersPercent,
bool starmidConfirmed
);
event ConfirmNode(uint id, uint nodeID);
event OutsourceConfirmNode(uint nodeID, address confirmationNode);
event ChangePercent(uint id, uint nodeId, uint producersPercent);
event PushNodeGroup(uint id, uint nodeId, uint newNodeGroup);
event DeleteNodeGroup(uint id, uint nodeId, uint deleteNodeGroup);
function Nodes() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
//-----------------------------------------------------Nodes---------------------------------------------------------------
function changeOwner(string _changeOwnerPassword, address _newOwnerAddress) onlyOwner returns(bool) {
//One-time tool for emergency owner change
if (keccak256(_changeOwnerPassword) == 0xe17a112b6fc12fc80c9b241de72da0d27ce7e244100f3c4e9358162a11bed629) {
owner = _newOwnerAddress;
return true;
}
else
return false;
}
function addOwnerNotations(string _newNotation) onlyOwner {
uint date = block.timestamp;
vars.ownerNotationId += 1;
OwnerNotation(vars.ownerNotationId, date, _newNotation);
}
function addConfirmationNode(string _newConfirmationNode) public returns(bool) {
confirmationNodes[msg.sender] = _newConfirmationNode;
return true;
}
function addNodeGroup(string _newNodeGroup) onlyOwner returns(uint16 _id) {
bool result;
(result, _id) = CommonLibrary.addNodeGroup(vars, _newNodeGroup);
require(result);
NewNodeGroup(_id, _newNodeGroup);
}
function addNode(string _newNode, uint8 _producersPercent) returns(bool) {
bool result;
uint _id;
(result, _id) = CommonLibrary.addNode(vars, _newNode, _producersPercent);
require(result);
NewNode(_id, _newNode, _producersPercent, msg.sender, block.timestamp);
return true;
}
function editNode(
uint _nodeID,
address _nodeAddress,
bool _isNewProducer,
address _newProducer,
uint8 _newProducersPercent,
bool _starmidConfirmed
) onlyOwner returns(bool) {
bool x = CommonLibrary.editNode(vars, _nodeID, _nodeAddress,_isNewProducer, _newProducer, _newProducersPercent, _starmidConfirmed);
require(x);
EditNode(_nodeID, _nodeAddress, _newProducer, _newProducersPercent, _starmidConfirmed);
return true;
}
function addNodeAddress(uint _nodeID, address _nodeAddress) public returns(bool) {
bool _result;
uint _id;
(_result, _id) = CommonLibrary.addNodeAddress(vars, _nodeID, _nodeAddress);
require(_result);
AddNodeAddress(_id, _nodeID, _nodeAddress);
return true;
}
function pushNodeGroup(uint _nodeID, uint16 _newNodeGroup) public returns(bool) {
require(msg.sender == vars.nodes[_nodeID].node);
vars.nodes[_nodeID].nodeGroup.push(_newNodeGroup);
pushNodeGroupId += 1;
PushNodeGroup(pushNodeGroupId, _nodeID, _newNodeGroup);
return true;
}
function deleteNodeGroup(uint _nodeID, uint16 _deleteNodeGroup) public returns(bool) {
require(msg.sender == vars.nodes[_nodeID].node);
for(uint16 i = 0; i < vars.nodes[_nodeID].nodeGroup.length; i++) {
if(_deleteNodeGroup == vars.nodes[_nodeID].nodeGroup[i]) {
for(uint16 ii = i; ii < vars.nodes[_nodeID].nodeGroup.length - 1; ii++)
vars.nodes[_nodeID].nodeGroup[ii] = vars.nodes[_nodeID].nodeGroup[ii + 1];
delete vars.nodes[_nodeID].nodeGroup[vars.nodes[_nodeID].nodeGroup.length - 1];
vars.nodes[_nodeID].nodeGroup.length--;
break;
}
}
deleteNodeGroupId += 1;
DeleteNodeGroup(deleteNodeGroupId, _nodeID, _deleteNodeGroup);
return true;
}
function confirmNode(uint _nodeID) onlyOwner returns(bool) {
vars.nodes[_nodeID].starmidConfirmed = true;
confirmNodeId += 1;
ConfirmNode(confirmNodeId, _nodeID);
return true;
}
function outsourceConfirmNode(uint _nodeID) public returns(bool) {
vars.nodes[_nodeID].outsourceConfirmed.push(msg.sender);
OutsourceConfirmNode(_nodeID, msg.sender);
return true;
}
function changePercent(uint _nodeId, uint8 _producersPercent) public returns(bool){
if(msg.sender == vars.nodes[_nodeId].producer && vars.nodes[_nodeId].node == 0x0000000000000000000000000000000000000000) {
vars.nodes[_nodeId].producersPercent = _producersPercent;
changePercentId += 1;
ChangePercent(changePercentId, _nodeId, _producersPercent);
return true;
}
}
function getNodeInfo(uint _nodeID) constant public returns(
address _producer,
address _node,
uint _date,
bool _starmidConfirmed,
string _nodeName,
address[] _outsourceConfirmed,
uint16[] _nodeGroup,
uint _producersPercent
) {
_producer = vars.nodes[_nodeID].producer;
_node = vars.nodes[_nodeID].node;
_date = vars.nodes[_nodeID].date;
_starmidConfirmed = vars.nodes[_nodeID].starmidConfirmed;
_nodeName = vars.nodes[_nodeID].nodeName;
_outsourceConfirmed = vars.nodes[_nodeID].outsourceConfirmed;
_nodeGroup = vars.nodes[_nodeID].nodeGroup;
_producersPercent = vars.nodes[_nodeID].producersPercent;
}
}
contract Starmid {
address public owner;
Nodes public nodesVars;
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
StarCoinLibrary.Data public sCVars;
event Transfer(address indexed from, address indexed to, uint256 value);
event BuyOrder(address indexed from, uint orderId, uint buyPrice);
event SellOrder(address indexed from, uint orderId, uint sellPrice);
event CancelBuyOrder(address indexed from, uint indexed orderId, uint price);
event CancelSellOrder(address indexed from, uint indexed orderId, uint price);
event TradeHistory(uint date, address buyer, address seller, uint price, uint amount, uint orderId);
//----------------------------------------------------Starmid exchange
event StockTransfer(address indexed from, address indexed to, uint indexed node, uint256 value);
event StockBuyOrder(uint node, uint buyPrice);
event StockSellOrder(uint node, uint sellPrice);
event StockCancelBuyOrder(uint node, uint price);
event StockCancelSellOrder(uint node, uint price);
event StockTradeHistory(uint node, uint date, address buyer, address seller, uint price, uint amount, uint orderId);
function Starmid(uint256 initialSupply, string tokenName, string tokenSymbol, uint8 decimalUnits) public {
owner = 0x378B9eea7ab9C15d9818EAdDe1156A079Cd02ba8;
totalSupply = initialSupply;
sCVars.balanceOf[msg.sender] = 5000000000;
sCVars.balanceOf[0x378B9eea7ab9C15d9818EAdDe1156A079Cd02ba8] = initialSupply - 5000000000;
name = tokenName;
symbol = tokenSymbol;
decimals = decimalUnits;
sCVars.lastMint = block.timestamp;
sCVars.emissionLimits[1] = 500000; sCVars.emissionLimits[2] = 500000; sCVars.emissionLimits[3] = 500000;
sCVars.emissionLimits[4] = 500000; sCVars.emissionLimits[5] = 500000; sCVars.emissionLimits[6] = 500000;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
//-----------------------------------------------------StarCoin Exchange------------------------------------------------------
function getWithdrawal() constant public returns(uint _amount) {
_amount = sCVars.pendingWithdrawals[msg.sender];
}
function withdraw() public returns(bool _result, uint _amount) {
_amount = sCVars.pendingWithdrawals[msg.sender];
sCVars.pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(_amount);
_result = true;
}
function changeOwner(string _changeOwnerPassword, address _newOwnerAddress) onlyOwner returns(bool) {
//One-time tool for emergency owner change
if (keccak256(_changeOwnerPassword) == 0xe17a112b6fc12fc80c9b241de72da0d27ce7e244100f3c4e9358162a11bed629) {
owner = _newOwnerAddress;
return true;
}
else
return false;
}
function setNodesVars(address _addr) public {
require(msg.sender == 0xfCbA69eF1D63b0A4CcD9ceCeA429157bA48d6a9c);
nodesVars = Nodes(_addr);
}
function getBalance(address _address) constant public returns(uint _balance) {
_balance = sCVars.balanceOf[_address];
}
function getBuyOrderPrices() constant public returns(uint[] _prices) {
_prices = sCVars.buyOrderPrices;
}
function getSellOrderPrices() constant public returns(uint[] _prices) {
_prices = sCVars.sellOrderPrices;
}
function getOrderInfo(bool _isBuyOrder, uint _price, uint _number) constant public returns(address _address, uint _amount, uint _orderId) {
if(_isBuyOrder == true) {
_address = sCVars.buyOrders[_price][_number].client;
_amount = sCVars.buyOrders[_price][_number].amount;
_orderId = sCVars.buyOrders[_price][_number].orderId;
}
else {
_address = sCVars.sellOrders[_price][_number].client;
_amount = sCVars.sellOrders[_price][_number].amount;
_orderId = sCVars.sellOrders[_price][_number].orderId;
}
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function mint() public onlyOwner returns(uint _mintedAmount) {
//Minted amount does not exceed 8,5% per annum. Thus, minting does not greatly increase the total supply
//and does not cause significant inflation and depreciation of the starcoin.
_mintedAmount = (block.timestamp - sCVars.lastMint)*totalSupply/(12*31536000);//31536000 seconds in year
sCVars.balanceOf[msg.sender] += _mintedAmount;
totalSupply += _mintedAmount;
sCVars.lastMint = block.timestamp;
Transfer(0, this, _mintedAmount);
Transfer(this, msg.sender, _mintedAmount);
}
function buyOrder(uint256 _buyPrice) payable public returns (uint[4] _results) {
require(_buyPrice > 0 && msg.value > 0);
_results = StarCoinLibrary.buyOrder(sCVars, _buyPrice);
require(_results[3] == 1);
BuyOrder(msg.sender, _results[2], _buyPrice);
}
function sellOrder(uint256 _sellPrice, uint _amount) public returns (uint[4] _results) {
require(_sellPrice > 0 && _amount > 0);
_results = StarCoinLibrary.sellOrder(sCVars, _sellPrice, _amount);
require(_results[3] == 1);
SellOrder(msg.sender, _results[2], _sellPrice);
}
function cancelBuyOrder(uint _thisOrderID, uint _price) public {
require(StarCoinLibrary.cancelBuyOrder(sCVars, _thisOrderID, _price));
CancelBuyOrder(msg.sender, _thisOrderID, _price);
}
function cancelSellOrder(uint _thisOrderID, uint _price) public {
require(StarCoinLibrary.cancelSellOrder(sCVars, _thisOrderID, _price));
CancelSellOrder(msg.sender, _thisOrderID, _price);
}
function _transfer(address _from, address _to, uint _value) internal {
require(_to != 0x0);
require(sCVars.balanceOf[_from] >= _value && sCVars.balanceOf[_to] + _value > sCVars.balanceOf[_to]);
sCVars.balanceOf[_from] -= _value;
sCVars.balanceOf[_to] += _value;
Transfer(_from, _to, _value);
}
function buyCertainOrder(uint _price, uint _thisOrderID) payable public returns (bool _results) {
_results = StarmidLibraryExtra.buyCertainOrder(sCVars, _price, _thisOrderID);
require(_results && msg.value > 0);
BuyOrder(msg.sender, _thisOrderID, _price);
}
function sellCertainOrder(uint _amount, uint _price, uint _thisOrderID) public returns (bool _results) {
_results = StarmidLibraryExtra.sellCertainOrder(sCVars, _amount, _price, _thisOrderID);
require(_results && _amount > 0);
SellOrder(msg.sender, _thisOrderID, _price);
}
//------------------------------------------------------Starmid exchange----------------------------------------------------------
function stockTransfer(address _to, uint _node, uint _value) public {
require(_to != 0x0);
require(sCVars.stockBalanceOf[msg.sender][_node] >= _value && sCVars.stockBalanceOf[_to][_node] + _value > sCVars.stockBalanceOf[_to][_node]);
var (x,y,) = nodesVars.getNodeInfo(_node);
require(msg.sender != y);//nodeOwner cannot transfer his stocks, only sell
sCVars.stockBalanceOf[msg.sender][_node] -= _value;
sCVars.stockBalanceOf[_to][_node] += _value;
StockTransfer(msg.sender, _to, _node, _value);
}
function getEmission(uint _node) constant public returns(uint _emissionNumber, uint _emissionDate, uint _emissionAmount) {
_emissionNumber = sCVars.emissions[_node].emissionNumber;
_emissionDate = sCVars.emissions[_node].date;
_emissionAmount = sCVars.emissionLimits[_emissionNumber];
}
function emission(uint _node) public returns(bool _result, uint _emissionNumber, uint _emissionAmount, uint _producersPercent) {
var (x,y,,,,,,z,) = nodesVars.getNodeInfo(_node);
address _nodeOwner = y;
address _nodeProducer = x;
_producersPercent = z;
require(msg.sender == _nodeOwner || msg.sender == _nodeProducer);
uint allStocks;
for (uint i = 1; i <= sCVars.emissions[_node].emissionNumber; i++) {
allStocks += sCVars.emissionLimits[i];
}
if (_nodeOwner !=0x0000000000000000000000000000000000000000 && block.timestamp > sCVars.emissions[_node].date + 5184000 &&
sCVars.stockBalanceOf[_nodeOwner][_node] <= allStocks/2 ) {
_emissionNumber = sCVars.emissions[_node].emissionNumber + 1;
sCVars.stockBalanceOf[_nodeOwner][_node] += sCVars.emissionLimits[_emissionNumber]*(100 - _producersPercent)/100;
//save stockOwnerInfo for _nodeOwner
uint thisNode = 0;
for (i = 0; i < sCVars.stockOwnerInfo[_nodeOwner].nodes.length; i++) {
if (sCVars.stockOwnerInfo[_nodeOwner].nodes[i] == _node) thisNode = 1;
}
if (thisNode == 0) sCVars.stockOwnerInfo[_nodeOwner].nodes.push(_node);
sCVars.stockBalanceOf[_nodeProducer][_node] += sCVars.emissionLimits[_emissionNumber]*_producersPercent/100;
//save stockOwnerInfo for _nodeProducer
thisNode = 0;
for (i = 0; i < sCVars.stockOwnerInfo[_nodeProducer].nodes.length; i++) {
if (sCVars.stockOwnerInfo[_nodeProducer].nodes[i] == _node) thisNode = 1;
}
if (thisNode == 0) sCVars.stockOwnerInfo[_nodeProducer].nodes.push(_node);
sCVars.emissions[_node].date = block.timestamp;
sCVars.emissions[_node].emissionNumber = _emissionNumber;
_emissionAmount = sCVars.emissionLimits[_emissionNumber];
_result = true;
}
else _result = false;
}
function getStockOwnerInfo(address _address) constant public returns(uint[] _nodes) {
_nodes = sCVars.stockOwnerInfo[_address].nodes;
}
function getStockBalance(address _address, uint _node) constant public returns(uint _balance) {
_balance = sCVars.stockBalanceOf[_address][_node];
}
function getWithFrozenStockBalance(address _address, uint _node) constant public returns(uint _balance) {
_balance = sCVars.stockBalanceOf[_address][_node] + sCVars.stockFrozen[_address][_node];
}
function getStockOrderInfo(bool _isBuyOrder, uint _node, uint _price, uint _number) constant public returns(address _address, uint _amount, uint _orderId) {
if(_isBuyOrder == true) {
_address = sCVars.stockBuyOrders[_node][_price][_number].client;
_amount = sCVars.stockBuyOrders[_node][_price][_number].amount;
_orderId = sCVars.stockBuyOrders[_node][_price][_number].orderId;
}
else {
_address = sCVars.stockSellOrders[_node][_price][_number].client;
_amount = sCVars.stockSellOrders[_node][_price][_number].amount;
_orderId = sCVars.stockSellOrders[_node][_price][_number].orderId;
}
}
function getStockBuyOrderPrices(uint _node) constant public returns(uint[] _prices) {
_prices = sCVars.stockBuyOrderPrices[_node];
}
function getStockSellOrderPrices(uint _node) constant public returns(uint[] _prices) {
_prices = sCVars.stockSellOrderPrices[_node];
}
function stockBuyOrder(uint _node, uint256 _buyPrice, uint _amount) public returns (uint[4] _results) {
require(_node > 0 && _buyPrice > 0 && _amount > 0);
_results = StarmidLibrary.stockBuyOrder(sCVars, _node, _buyPrice, _amount);
require(_results[3] == 1);
StockBuyOrder(_node, _buyPrice);
}
function stockSellOrder(uint _node, uint256 _sellPrice, uint _amount) public returns (uint[4] _results) {
require(_node > 0 && _sellPrice > 0 && _amount > 0);
_results = StarmidLibrary.stockSellOrder(sCVars, _node, _sellPrice, _amount);
require(_results[3] == 1);
StockSellOrder(_node, _sellPrice);
}
function stockCancelBuyOrder(uint _node, uint _thisOrderID, uint _price) public {
require(StarmidLibrary.stockCancelBuyOrder(sCVars, _node, _thisOrderID, _price));
StockCancelBuyOrder(_node, _price);
}
function stockCancelSellOrder(uint _node, uint _thisOrderID, uint _price) public {
require(StarmidLibrary.stockCancelSellOrder(sCVars, _node, _thisOrderID, _price));
StockCancelSellOrder(_node, _price);
}
function getLastDividends(uint _node) public constant returns (uint _lastDividents, uint _dividends) {
uint stockAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount;
uint sumAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount;
if(sumAmount > 0) {
uint stockAverageBuyPrice = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumPriceAmount/sumAmount;
uint dividendsBase = stockAmount*stockAverageBuyPrice;
_lastDividents = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumDateAmount/sumAmount;
if(_lastDividents > 0)_dividends = (block.timestamp - _lastDividents)*dividendsBase/(10*31536000);
else _dividends = 0;
}
}
//--------------------------------Dividends (10% to stock owner, 2,5% to node owner per annum)------------------------------------
function dividends(uint _node) public returns (bool _result, uint _dividends) {
var (x,y,) = nodesVars.getNodeInfo(_node);
uint _stockAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount;
uint _sumAmount = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumAmount;
if(_sumAmount > 0) {
uint _stockAverageBuyPrice = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumPriceAmount/_sumAmount;
uint _dividendsBase = _stockAmount*_stockAverageBuyPrice;
uint _averageDate = sCVars.StockOwnersBuyPrice[msg.sender][_node].sumDateAmount/_sumAmount;
//Stock owner`s dividends
uint _div = (block.timestamp - _averageDate)*_dividendsBase/(10*31536000);//31536000 seconds in year
sCVars.balanceOf[msg.sender] += _div;
//Node owner`s dividends
uint _nodeDividends = (block.timestamp - _averageDate)*_dividendsBase/(40*31536000);//31536000 seconds in year
sCVars.balanceOf[y] += _nodeDividends;
sCVars.StockOwnersBuyPrice[msg.sender][_node].sumDateAmount = block.timestamp*_stockAmount;//set new average dividends date
totalSupply += _div + _div/4;
_dividends = _div + _div/4;
Transfer(this, msg.sender, _div);
Transfer(this, y, _div/4);
_result = true;
}
}
function stockBuyCertainOrder(uint _node, uint _price, uint _amount, uint _thisOrderID) payable public returns (bool _results) {
_results = StarmidLibraryExtra.stockBuyCertainOrder(sCVars, _node, _price, _amount, _thisOrderID);
require(_results && _node > 0 && _amount > 0);
StockBuyOrder(_node, _price);
}
function stockSellCertainOrder(uint _node, uint _price, uint _amount, uint _thisOrderID) public returns (bool _results) {
_results = StarmidLibraryExtra.stockSellCertainOrder(sCVars, _node, _price, _amount, _thisOrderID);
require(_results && _node > 0 && _amount > 0);
StockSellOrder(_node, _price);
}
}
|
-----------------------------------------------------Nodes---------------------------------------------------------------One-time tool for emergency owner change
|
function changeOwner(string _changeOwnerPassword, address _newOwnerAddress) onlyOwner returns(bool) {
if (keccak256(_changeOwnerPassword) == 0xe17a112b6fc12fc80c9b241de72da0d27ce7e244100f3c4e9358162a11bed629) {
owner = _newOwnerAddress;
return true;
}
else
return false;
}
| 2,114,758 |
[
1,
9634,
13465,
3205,
9634,
18753,
3335,
17,
957,
5226,
364,
801,
24530,
3410,
2549,
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,
202,
915,
2549,
5541,
12,
1080,
389,
3427,
5541,
3913,
16,
1758,
389,
2704,
5541,
1887,
13,
1338,
5541,
1135,
12,
6430,
13,
288,
203,
202,
202,
430,
261,
79,
24410,
581,
5034,
24899,
3427,
5541,
3913,
13,
422,
374,
6554,
4033,
69,
17666,
70,
26,
7142,
2138,
7142,
3672,
71,
29,
70,
3247,
21,
323,
9060,
2414,
20,
72,
5324,
311,
27,
73,
3247,
24,
6625,
74,
23,
71,
24,
73,
29,
4763,
28,
30042,
69,
2499,
2992,
26,
5540,
13,
288,
203,
1082,
202,
8443,
273,
389,
2704,
5541,
1887,
31,
203,
1082,
202,
2463,
638,
31,
203,
202,
202,
97,
203,
202,
202,
12107,
7010,
1082,
202,
2463,
629,
31,
203,
202,
97,
203,
202,
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.24;
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) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20 {
function totalSupply() external view returns (uint256 _totalSupply);
function balanceOf(address _owner) external view returns (uint256 balance);
function transfer(address _to, uint256 _value) external returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success);
function approve(address _spender, uint256 _value) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
library AddressSet {
// Name is kept for drop-in replacement reasons. Recommended name `Instance`
struct Instance {
address[] list;
mapping(address => uint256) idx; // actually stores indexes incremented by 1
}
// _direction parameter is kept for drop-in replacement consistency; consider remove the parameter
// Gas efficient version of push
function push(Instance storage self, address addr) internal returns (bool) {
if (self.idx[addr] != 0) return false;
self.idx[addr] = self.list.push(addr);
return true;
}
// Now in O(1)
function sizeOf(Instance storage self) internal view returns (uint256) {
return self.list.length;
}
// Gets i-th address in O(1) time (RANDOM ACCESS!!!)
function getAddress(Instance storage self, uint256 index) internal view returns (address) {
return (index < self.list.length) ? self.list[index] : address(0);
}
// Gas efficient version of remove
function remove(Instance storage self, address addr) internal returns (bool) {
if (self.idx[addr] == 0) return false;
uint256 idx = self.idx[addr];
delete self.idx[addr];
if (self.list.length == idx) {
self.list.length--;
} else {
address last = self.list[self.list.length-1];
self.list.length--;
self.list[idx-1] = last;
self.idx[last] = idx;
}
return true;
}
}
contract UHCToken is ERC20 {
using SafeMath for uint256;
using AddressSet for AddressSet.Instance;
address public owner;
address public subowner;
bool public paused = false;
bool public contractEnable = true;
string public name = "UHC";
string public symbol = "UHC";
uint8 public decimals = 4;
uint256 private summarySupply;
uint8 public transferFeePercent = 3;
uint8 public refererFeePercent = 1;
struct account{
uint256 balance;
uint8 group;
uint8 status;
address referer;
bool isBlocked;
}
mapping(address => account) private accounts;
mapping(address => mapping (address => uint256)) private allowed;
mapping(bytes => address) private promos;
AddressSet.Instance private holders;
struct groupPolicy {
uint8 _default;
uint8 _backend;
uint8 _admin;
uint8 _owner;
}
groupPolicy public groupPolicyInstance = groupPolicy(0, 3, 4, 9);
event EvGroupChanged(address indexed _address, uint8 _oldgroup, uint8 _newgroup);
event EvMigration(address indexed _address, uint256 _balance, uint256 _secret);
event EvUpdateStatus(address indexed _address, uint8 _oldstatus, uint8 _newstatus);
event EvSetReferer(address indexed _referal, address _referer);
event SwitchPause(bool isPaused);
constructor (string _name, string _symbol, uint8 _decimals,uint256 _summarySupply, uint8 _transferFeePercent, uint8 _refererFeePercent) public {
require(_refererFeePercent < _transferFeePercent);
owner = msg.sender;
accounts[owner] = account(_summarySupply,groupPolicyInstance._owner,3, address(0), false);
holders.push(msg.sender);
name = _name;
symbol = _symbol;
decimals = _decimals;
summarySupply = _summarySupply;
transferFeePercent = _transferFeePercent;
refererFeePercent = _refererFeePercent;
emit Transfer(address(0), msg.sender, _summarySupply);
}
modifier minGroup(int _require) {
require(accounts[msg.sender].group >= _require);
_;
}
modifier onlySubowner() {
require(msg.sender == subowner);
_;
}
modifier whenNotPaused() {
require(!paused || accounts[msg.sender].group >= groupPolicyInstance._backend);
_;
}
modifier whenPaused() {
require(paused);
_;
}
modifier whenNotMigrating {
require(contractEnable);
_;
}
modifier whenMigrating {
require(!contractEnable);
_;
}
function servicePause() minGroup(groupPolicyInstance._admin) whenNotPaused public {
paused = true;
emit SwitchPause(paused);
}
function serviceUnpause() minGroup(groupPolicyInstance._admin) whenPaused public {
paused = false;
emit SwitchPause(paused);
}
function serviceGroupChange(address _address, uint8 _group) minGroup(groupPolicyInstance._admin) external returns(uint8) {
require(_address != address(0));
require(_group <= groupPolicyInstance._admin);
uint8 old = accounts[_address].group;
require(old < accounts[msg.sender].group);
accounts[_address].group = _group;
emit EvGroupChanged(_address, old, _group);
return accounts[_address].group;
}
function serviceTransferOwnership(address newOwner) minGroup(groupPolicyInstance._owner) external {
require(newOwner != address(0));
subowner = newOwner;
}
function serviceClaimOwnership() onlySubowner() external {
address temp = owner;
uint256 value = accounts[owner].balance;
accounts[owner].balance = accounts[owner].balance.sub(value);
holders.remove(owner);
accounts[msg.sender].balance = accounts[msg.sender].balance.add(value);
holders.push(msg.sender);
owner = msg.sender;
subowner = address(0);
delete accounts[temp].group;
uint8 oldGroup = accounts[msg.sender].group;
accounts[msg.sender].group = groupPolicyInstance._owner;
emit EvGroupChanged(msg.sender, oldGroup, groupPolicyInstance._owner);
emit Transfer(temp, owner, value);
}
function serviceSwitchTransferAbility(address _address) external minGroup(groupPolicyInstance._admin) returns(bool) {
require(accounts[_address].group < accounts[msg.sender].group);
accounts[_address].isBlocked = !accounts[_address].isBlocked;
return true;
}
function serviceUpdateTransferFeePercent(uint8 newFee) external minGroup(groupPolicyInstance._admin) {
require(newFee < 100);
require(newFee > refererFeePercent);
transferFeePercent = newFee;
}
function serviceUpdateRefererFeePercent(uint8 newFee) external minGroup(groupPolicyInstance._admin) {
require(newFee < 100);
require(transferFeePercent > newFee);
refererFeePercent = newFee;
}
function serviceSetPromo(bytes num, address _address) external minGroup(groupPolicyInstance._admin) {
promos[num] = _address;
}
function backendSetStatus(address _address, uint8 status) external minGroup(groupPolicyInstance._backend) returns(bool){
require(_address != address(0));
require(status >= 0 && status <= 4);
uint8 oldStatus = accounts[_address].status;
accounts[_address].status = status;
emit EvUpdateStatus(_address, oldStatus, status);
return true;
}
function backendSetReferer(address _referal, address _referer) external minGroup(groupPolicyInstance._backend) returns(bool) {
require(accounts[_referal].referer == address(0));
require(_referal != address(0));
require(_referal != _referer);
require(accounts[_referal].referer != _referer);
accounts[_referal].referer = _referer;
emit EvSetReferer(_referal, _referer);
return true;
}
function backendSendBonus(address _to, uint256 _value) external minGroup(groupPolicyInstance._backend) returns(bool) {
require(_to != address(0));
require(_value > 0);
require(accounts[owner].balance >= _value);
accounts[owner].balance = accounts[owner].balance.sub(_value);
accounts[_to].balance = accounts[_to].balance.add(_value);
emit Transfer(owner, _to, _value);
return true;
}
function backendRefund(address _from, uint256 _value) external minGroup(groupPolicyInstance._backend) returns(uint256 balance) {
require(_from != address(0));
require(_value > 0);
require(accounts[_from].balance >= _value);
accounts[_from].balance = accounts[_from].balance.sub(_value);
accounts[owner].balance = accounts[owner].balance.add(_value);
if(accounts[_from].balance == 0){
holders.remove(_from);
}
emit Transfer(_from, owner, _value);
return accounts[_from].balance;
}
function getGroup(address _check) external view returns(uint8 _group) {
return accounts[_check].group;
}
function getHoldersLength() external view returns(uint256){
return holders.sizeOf();
}
function getHolderByIndex(uint256 _index) external view returns(address){
return holders.getAddress(_index);
}
function getPromoAddress(bytes _promo) external view returns(address) {
return promos[_promo];
}
function getAddressTransferAbility(address _check) external view returns(bool) {
return !accounts[_check].isBlocked;
}
function transfer(address _to, uint256 _value) external returns (bool success) {
return _transfer(msg.sender, _to, address(0), _value);
}
function transferFrom(address _from, address _to, uint256 _value) external returns (bool success) {
return _transfer(_from, _to, msg.sender, _value);
}
function _transfer(address _from, address _to, address _allow, uint256 _value) minGroup(groupPolicyInstance._default) whenNotMigrating whenNotPaused internal returns(bool) {
require(!accounts[_from].isBlocked);
require(_from != address(0));
require(_to != address(0));
uint256 transferFee = accounts[_from].group == 0 ? _value.div(100).mul(accounts[_from].referer == address(0) ? transferFeePercent : transferFeePercent - refererFeePercent) : 0;
uint256 transferRefererFee = accounts[_from].referer == address(0) || accounts[_from].group != 0 ? 0 : _value.div(100).mul(refererFeePercent);
uint256 summaryValue = _value.add(transferFee).add(transferRefererFee);
require(accounts[_from].balance >= summaryValue);
require(_allow == address(0) || allowed[_from][_allow] >= summaryValue);
accounts[_from].balance = accounts[_from].balance.sub(summaryValue);
if(_allow != address(0)) {
allowed[_from][_allow] = allowed[_from][_allow].sub(summaryValue);
}
if(accounts[_from].balance == 0){
holders.remove(_from);
}
accounts[_to].balance = accounts[_to].balance.add(_value);
holders.push(_to);
emit Transfer(_from, _to, _value);
if(transferFee > 0) {
accounts[owner].balance = accounts[owner].balance.add(transferFee);
emit Transfer(_from, owner, transferFee);
}
if(transferRefererFee > 0) {
accounts[accounts[_from].referer].balance = accounts[accounts[_from].referer].balance.add(transferRefererFee);
holders.push(accounts[_from].referer);
emit Transfer(_from, accounts[_from].referer, transferRefererFee);
}
return true;
}
function approve(address _spender, uint256 _value) minGroup(groupPolicyInstance._default) whenNotPaused external returns (bool success) {
require (_value == 0 || allowed[msg.sender][_spender] == 0);
require(_spender != address(0));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function increaseApproval(address _spender, uint256 _addedValue) minGroup(groupPolicyInstance._default) whenNotPaused external returns (bool)
{
allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint256 _subtractedValue) minGroup(groupPolicyInstance._default) whenNotPaused external returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function allowance(address _owner, address _spender) external view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function balanceOf(address _owner) external view returns (uint256 balance) {
return accounts[_owner].balance;
}
function statusOf(address _owner) external view returns (uint8) {
return accounts[_owner].status;
}
function refererOf(address _owner) external constant returns (address) {
return accounts[_owner].referer;
}
function totalSupply() external constant returns (uint256 _totalSupply) {
_totalSupply = summarySupply;
}
function settingsSwitchState() external minGroup(groupPolicyInstance._owner) returns (bool state) {
contractEnable = !contractEnable;
return contractEnable;
}
function userMigration(uint256 _secret) external whenMigrating returns (bool successful) {
uint256 balance = accounts[msg.sender].balance;
require (balance > 0);
accounts[msg.sender].balance = accounts[msg.sender].balance.sub(balance);
holders.remove(msg.sender);
accounts[owner].balance = accounts[owner].balance.add(balance);
holders.push(owner);
emit EvMigration(msg.sender, balance, _secret);
emit Transfer(msg.sender, owner, balance);
return true;
}
}
|
_direction parameter is kept for drop-in replacement consistency; consider remove the parameter Gas efficient version of push
|
function push(Instance storage self, address addr) internal returns (bool) {
if (self.idx[addr] != 0) return false;
self.idx[addr] = self.list.push(addr);
return true;
}
| 893,415 |
[
1,
67,
9855,
1569,
353,
16555,
364,
3640,
17,
267,
6060,
14297,
31,
5260,
1206,
326,
1569,
31849,
14382,
1177,
434,
1817,
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,
1817,
12,
1442,
2502,
365,
16,
1758,
3091,
13,
2713,
1135,
261,
6430,
13,
288,
203,
3639,
309,
261,
2890,
18,
3465,
63,
4793,
65,
480,
374,
13,
327,
629,
31,
203,
3639,
365,
18,
3465,
63,
4793,
65,
273,
365,
18,
1098,
18,
6206,
12,
4793,
1769,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.20;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev 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) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @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 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 Contactable token
* @dev Basic version of a contactable contract, allowing the owner to provide a string with their
* contact information.
*/
contract Contactable is Ownable {
string public contactInformation;
/**
* @dev Allows the owner to set a string with their contact information.
* @param info The contact information to attach to the contract.
*/
function setContactInformation(string info) onlyOwner public {
contactInformation = info;
}
}
interface BlacklistInterface {
event Blacklisted(address indexed _node);
event Unblacklisted(address indexed _node);
function blacklist(address _node) public;
function unblacklist(address _node) public;
function isBanned(address _node) returns (bool);
}
contract Blacklist is BlacklistInterface, Ownable {
mapping (address => bool) blacklisted;
/**
* @dev Add a node to the blacklist.
* @param node The node to add to the blacklist.
*/
function blacklist(address node) public onlyOwner {
blacklisted[node] = true;
Blacklisted(node);
}
/**
* @dev Remove a node from the blacklist.
* @param node The node to remove from the blacklist.
*/
function unblacklist(address node) public onlyOwner {
blacklisted[node] = false;
Unblacklisted(node);
}
function isBanned(address node) returns (bool) {
if (blacklisted[node]) {
return true;
} else {
return false;
}
}
}
/**
* @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 ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic, Blacklist {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
modifier onlyPayloadSize(uint256 numwords) {
assert(msg.data.length >= numwords * 32 + 4);
_;
}
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) onlyPayloadSize(2) public returns (bool) {
require(_to != address(0));
require(!isBanned(_to));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @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 Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3) public returns (bool) {
require(_to != address(0));
require(!isBanned(_to));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) onlyPayloadSize(2) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) onlyPayloadSize(2) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) onlyPayloadSize(2) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @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 Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is PausableToken {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
uint256 limit = 952457688 * 10 ** 18;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply_.add(_amount) <= limit);
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(this), _to, _amount);
if(totalSupply_ == limit ){
finishMinting();
return false;
}
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
contract XTRD is MintableToken, Claimable, Contactable {
/*----------- ERC20 GLOBALS -----------*/
string public constant name = "XTRD";
string public constant symbol = "XTRD";
uint public constant decimals = 18;
/*----------- Ownership Reclaim -----------*/
address public reclaimableOwner;
/**
* @dev Restricts method call to only the address set as `reclaimableOwner`.
*/
modifier onlyReclaimableOwner() {
require(msg.sender == reclaimableOwner);
_;
}
/**
* @dev Sets the reclaim address to current owner.
*/
function setupReclaim() public onlyOwner {
require(reclaimableOwner == address(0));
reclaimableOwner = msg.sender;
}
/**
* @dev Resets the reclaim address to address(0).
*/
function resetReclaim() public onlyReclaimableOwner {
reclaimableOwner = address(0);
}
/**
* @dev Failsafe to reclaim ownership in the event sale is unable to
* return ownership. Reclaims ownership regardless of
* pending ownership transfer.
*/
function reclaimOwnership() public onlyReclaimableOwner {
// Erase any pending transfer.
pendingOwner = address(0);
// Transfer ownership.
OwnershipTransferred(owner, reclaimableOwner);
owner = reclaimableOwner;
// Reset reclaimableOwner.
reclaimableOwner = address(0);
}
}
|
* @title Mintable token @dev Simple ERC20 Token example, with mintable token creation/
|
contract MintableToken is PausableToken {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
uint256 limit = 952457688 * 10 ** 18;
modifier canMint() {
require(!mintingFinished);
_;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply_.add(_amount) <= limit);
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(this), _to, _amount);
if(totalSupply_ == limit ){
finishMinting();
return false;
}
return true;
}
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply_.add(_amount) <= limit);
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(this), _to, _amount);
if(totalSupply_ == limit ){
finishMinting();
return false;
}
return true;
}
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
| 11,802,169 |
[
1,
49,
474,
429,
1147,
225,
4477,
4232,
39,
3462,
3155,
3454,
16,
598,
312,
474,
429,
1147,
6710,
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
] |
[
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,
16351,
490,
474,
429,
1345,
353,
21800,
16665,
1345,
288,
203,
203,
225,
871,
490,
474,
12,
2867,
8808,
358,
16,
2254,
5034,
3844,
1769,
203,
225,
871,
490,
474,
10577,
5621,
203,
203,
225,
1426,
1071,
312,
474,
310,
10577,
273,
629,
31,
203,
225,
2254,
5034,
1800,
273,
16848,
3247,
25,
6669,
5482,
380,
1728,
2826,
6549,
31,
203,
203,
225,
9606,
848,
49,
474,
1435,
288,
203,
565,
2583,
12,
5,
81,
474,
310,
10577,
1769,
203,
565,
389,
31,
203,
225,
289,
203,
203,
225,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1338,
5541,
848,
49,
474,
1071,
1135,
261,
6430,
13,
288,
203,
565,
2583,
12,
4963,
3088,
1283,
27799,
1289,
24899,
8949,
13,
1648,
1800,
1769,
203,
565,
2078,
3088,
1283,
67,
273,
2078,
3088,
1283,
27799,
1289,
24899,
8949,
1769,
203,
565,
324,
26488,
63,
67,
869,
65,
273,
324,
26488,
63,
67,
869,
8009,
1289,
24899,
8949,
1769,
203,
565,
490,
474,
24899,
869,
16,
389,
8949,
1769,
203,
565,
12279,
12,
2867,
12,
2211,
3631,
389,
869,
16,
389,
8949,
1769,
203,
377,
203,
565,
309,
12,
4963,
3088,
1283,
67,
422,
1800,
262,
95,
203,
1377,
4076,
49,
474,
310,
5621,
203,
1377,
327,
629,
31,
203,
565,
289,
203,
565,
327,
638,
31,
203,
225,
289,
27699,
21281,
203,
225,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
1338,
5541,
848,
49,
474,
1071,
1135,
261,
6430,
13,
288,
203,
565,
2583,
2
] |
pragma solidity ^0.6.0;
contract initializable5 { //inject NONSTANDARD NAMING
bool private initialized;
bool private initializing;
modifier INITIALIZER65() { //inject NONSTANDARD NAMING
require(initializing || ISCONSTRUCTOR91() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
function ISCONSTRUCTOR91() private view returns (bool) { //inject NONSTANDARD NAMING
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract contextupgradesafe87 is initializable5 { //inject NONSTANDARD NAMING
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __CONTEXT_INIT10() internal INITIALIZER65 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED61();
}
function __CONTEXT_INIT_UNCHAINED61() internal INITIALIZER65 { //inject NONSTANDARD NAMING
}
function _MSGSENDER78() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA22() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
contract ownableupgradesafe25 is initializable5, contextupgradesafe87 { //inject NONSTANDARD NAMING
address private _owner;
event OWNERSHIPTRANSFERRED52(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function __OWNABLE_INIT13() internal INITIALIZER65 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED61();
__OWNABLE_INIT_UNCHAINED84();
}
function __OWNABLE_INIT_UNCHAINED84() internal INITIALIZER65 { //inject NONSTANDARD NAMING
address msgSender = _MSGSENDER78();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED52(address(0), msgSender);
}
function OWNER9() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER81() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER78(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP19() public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED52(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP24(address newOwner) public virtual ONLYOWNER81 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED52(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
library safemath14 { //inject NONSTANDARD NAMING
function ADD80(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB60(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB60(a, b, "SafeMath: subtraction overflow");
}
function SUB60(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL16(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV54(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV54(a, b, "SafeMath: division by zero");
}
function DIV54(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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;
}
function MOD56(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD56(a, b, "SafeMath: modulo by zero");
}
function MOD56(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
interface ierc2086 { //inject NONSTANDARD NAMING
function TOTALSUPPLY25() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF21(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER6(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE84(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE33(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM54(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER56(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL90(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library console87 { //inject NONSTANDARD NAMING
address constant console_address36 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING
function _SENDLOGPAYLOAD51(bytes memory payload) private view { //inject NONSTANDARD NAMING
uint256 payloadLength = payload.length;
address consoleAddress = console_address36;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function LOG40() internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log()"));
}
function LOGINT64(int p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(int)", p0));
}
function LOGUINT96(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0));
}
function LOGSTRING94(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0));
}
function LOGBOOL52(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0));
}
function LOGADDRESS2(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0));
}
function LOGBYTES0(bytes memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes)", p0));
}
function LOGBYTE23(byte p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(byte)", p0));
}
function LOGBYTES1100(bytes1 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes1)", p0));
}
function LOGBYTES273(bytes2 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes2)", p0));
}
function LOGBYTES377(bytes3 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes3)", p0));
}
function LOGBYTES477(bytes4 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes4)", p0));
}
function LOGBYTES578(bytes5 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes5)", p0));
}
function LOGBYTES61(bytes6 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes6)", p0));
}
function LOGBYTES735(bytes7 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes7)", p0));
}
function LOGBYTES818(bytes8 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes8)", p0));
}
function LOGBYTES931(bytes9 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes9)", p0));
}
function LOGBYTES1064(bytes10 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes10)", p0));
}
function LOGBYTES1141(bytes11 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes11)", p0));
}
function LOGBYTES1261(bytes12 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes12)", p0));
}
function LOGBYTES1365(bytes13 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes13)", p0));
}
function LOGBYTES1433(bytes14 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes14)", p0));
}
function LOGBYTES1532(bytes15 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes15)", p0));
}
function LOGBYTES1678(bytes16 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes16)", p0));
}
function LOGBYTES176(bytes17 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes17)", p0));
}
function LOGBYTES1833(bytes18 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes18)", p0));
}
function LOGBYTES1973(bytes19 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes19)", p0));
}
function LOGBYTES202(bytes20 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes20)", p0));
}
function LOGBYTES2137(bytes21 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes21)", p0));
}
function LOGBYTES2248(bytes22 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes22)", p0));
}
function LOGBYTES2317(bytes23 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes23)", p0));
}
function LOGBYTES2438(bytes24 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes24)", p0));
}
function LOGBYTES2548(bytes25 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes25)", p0));
}
function LOGBYTES261(bytes26 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes26)", p0));
}
function LOGBYTES2793(bytes27 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes27)", p0));
}
function LOGBYTES2869(bytes28 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes28)", p0));
}
function LOGBYTES299(bytes29 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes29)", p0));
}
function LOGBYTES3053(bytes30 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes30)", p0));
}
function LOGBYTES3139(bytes31 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes31)", p0));
}
function LOGBYTES3263(bytes32 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bytes32)", p0));
}
function LOG40(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint)", p0));
}
function LOG40(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string)", p0));
}
function LOG40(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool)", p0));
}
function LOG40(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address)", p0));
}
function LOG40(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function LOG40(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function LOG40(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function LOG40(uint p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function LOG40(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function LOG40(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function LOG40(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function LOG40(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function LOG40(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function LOG40(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function LOG40(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function LOG40(bool p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function LOG40(address p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function LOG40(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function LOG40(address p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function LOG40(address p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function LOG40(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function LOG40(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function LOG40(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function LOG40(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function LOG40(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function LOG40(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function LOG40(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function LOG40(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function LOG40(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function LOG40(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function LOG40(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function LOG40(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function LOG40(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function LOG40(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function LOG40(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function LOG40(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function LOG40(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function LOG40(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function LOG40(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function LOG40(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function LOG40(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function LOG40(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function LOG40(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function LOG40(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function LOG40(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function LOG40(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function LOG40(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function LOG40(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function LOG40(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function LOG40(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function LOG40(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function LOG40(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function LOG40(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD51(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
interface iuniswapv2factory11 { //inject NONSTANDARD NAMING
event PAIRCREATED16(address indexed token0, address indexed token1, address pair, uint); //inject NONSTANDARD NAMING
function FEETO47() external view returns (address); //inject NONSTANDARD NAMING
function FEETOSETTER62() external view returns (address); //inject NONSTANDARD NAMING
function GETPAIR25(address tokenA, address tokenB) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRS78(uint) external view returns (address pair); //inject NONSTANDARD NAMING
function ALLPAIRSLENGTH45() external view returns (uint); //inject NONSTANDARD NAMING
function CREATEPAIR19(address tokenA, address tokenB) external returns (address pair); //inject NONSTANDARD NAMING
function SETFEETO7(address) external; //inject NONSTANDARD NAMING
function SETFEETOSETTER93(address) external; //inject NONSTANDARD NAMING
}
contract feeapprover21 is ownableupgradesafe25 { //inject NONSTANDARD NAMING
using safemath14 for uint256;
function INITIALIZE58( //inject NONSTANDARD NAMING
address _NANOCOREAddress,
address _WETHAddress,
address _uniswapFactory
) public INITIALIZER65 {
ownableupgradesafe25.__OWNABLE_INIT13();
nanocoreTokenAddress = _NANOCOREAddress;
WETHAddress = _WETHAddress;
tokenUniswapPair = iuniswapv2factory11(_uniswapFactory).GETPAIR25(WETHAddress,nanocoreTokenAddress);
feePercentX100 = 15;
paused = false; // We start paused until sync post LGE happens.
}
address tokenUniswapPair;
iuniswapv2factory11 public uniswapFactory;
address internal WETHAddress;
address nanocoreTokenAddress;
address nanocoreVaultAddress;
uint8 public feePercentX100; // max 255 = 25.5% artificial clamp
uint256 public lastTotalSupplyOfLPTokens;
bool paused;
// Pausing transfers of the token
function SETPAUSED71(bool _pause) public ONLYOWNER81 { //inject NONSTANDARD NAMING
paused = _pause;
}
function SETFEEMULTIPLIER40(uint8 _feeMultiplier) public ONLYOWNER81 { //inject NONSTANDARD NAMING
feePercentX100 = _feeMultiplier;
}
function SETNANOCOREVAULTADDRESS89(address _nanocoreVaultAddress) public ONLYOWNER81 { //inject NONSTANDARD NAMING
nanocoreVaultAddress = _nanocoreVaultAddress;
}
function SYNC99() public { //inject NONSTANDARD NAMING
uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25();
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal;
}
function CALCULATEAMOUNTSAFTERFEE82( //inject NONSTANDARD NAMING
address sender,
address recipient, // unusued maybe use din future
uint256 amount
) public returns (uint256 transferToAmount, uint256 transferToFeeDistributorAmount)
{
require(paused == false, "FEE APPROVER: Transfers Paused");
uint256 _LPSupplyOfPairTotal = ierc2086(tokenUniswapPair).TOTALSUPPLY25();
// console.log("sender is " , sender);
// console.log("recipient is is " , recipient, 'pair is :', tokenUniswapPair);
// console.log("Old LP supply", lastTotalSupplyOfLPTokens);
// console.log("Current LP supply", _LPSupplyOfPairTotal);
if(sender == tokenUniswapPair)
require(lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal, "Liquidity withdrawals forbidden");
// console.log('Sender is pair' , sender == tokenUniswapPair);
// console.log('lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal' , lastTotalSupplyOfLPTokens <= _LPSupplyOfPairTotal);
if(sender == nanocoreVaultAddress || sender == tokenUniswapPair ) { // Dont have a fee when nanocorevault is sending, or infinite loop
console87.LOG40("Sending without fee"); // And when pair is sending ( buys are happening, no tax on it)
transferToFeeDistributorAmount = 0;
transferToAmount = amount;
}
else {
console87.LOG40("Normal fee transfer");
transferToFeeDistributorAmount = amount.MUL16(feePercentX100).DIV54(1000);
transferToAmount = amount.SUB60(transferToFeeDistributorAmount);
}
lastTotalSupplyOfLPTokens = _LPSupplyOfPairTotal;
}
}
|
inject NONSTANDARD NAMING
|
function LOG40(uint p0, address p1, bool p2) internal view {
| 1,018,910 |
[
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
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,
202,
915,
2018,
7132,
12,
11890,
293,
20,
16,
1758,
293,
21,
16,
1426,
293,
22,
13,
2713,
1476,
288,
202,
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
] |
./full_match/1/0x4C49E065336c75278820eFBBcCd4B1508F9f5fe7/sources/contracts/lib/Strings.sol
|
* @dev String operations./
|
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
function toString(int256 value) internal pure returns (string memory) {
return
string(
abi.encodePacked(
value < 0 ? "-" : "",
toString(SignedMath.abs(value))
)
);
}
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
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] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
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] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
function equal(
string memory a,
string memory b
) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
| 2,936,200 |
[
1,
780,
5295,
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,
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,
12083,
8139,
288,
203,
565,
1731,
2313,
3238,
5381,
389,
22093,
55,
273,
315,
26684,
28953,
14432,
203,
565,
2254,
28,
3238,
5381,
389,
15140,
67,
7096,
273,
4200,
31,
203,
203,
203,
565,
445,
1762,
12,
11890,
5034,
460,
13,
2713,
16618,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
22893,
288,
203,
5411,
2254,
5034,
769,
273,
2361,
18,
1330,
2163,
12,
1132,
13,
397,
404,
31,
203,
5411,
533,
3778,
1613,
273,
394,
533,
12,
2469,
1769,
203,
5411,
2254,
5034,
6571,
31,
203,
5411,
19931,
288,
203,
7734,
6571,
519,
527,
12,
4106,
16,
527,
12,
1578,
16,
769,
3719,
203,
5411,
289,
203,
5411,
1323,
261,
3767,
13,
288,
203,
7734,
6571,
413,
31,
203,
7734,
19931,
288,
203,
10792,
312,
2233,
28,
12,
6723,
16,
1160,
12,
1711,
12,
1132,
16,
1728,
3631,
389,
22093,
55,
3719,
203,
7734,
289,
203,
7734,
460,
9531,
1728,
31,
203,
7734,
309,
261,
1132,
422,
374,
13,
898,
31,
203,
5411,
289,
203,
5411,
327,
1613,
31,
203,
3639,
289,
203,
565,
289,
203,
203,
565,
445,
1762,
12,
11890,
5034,
460,
13,
2713,
16618,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
22893,
288,
203,
5411,
2254,
5034,
769,
273,
2361,
18,
1330,
2163,
12,
1132,
13,
397,
404,
31,
203,
5411,
533,
3778,
1613,
273,
394,
533,
12,
2469,
1769,
203,
5411,
2254,
5034,
6571,
31,
203,
5411,
19931,
288,
203,
7734,
6571,
519,
527,
12,
4106,
16,
527,
12,
1578,
16,
769,
3719,
203,
5411,
289,
203,
5411,
2
] |
./full_match/5/0xa95955f98aA19F2DeA68501028f60925dfDD9bf1/sources/browser/Untitled.sol
|
In any case, set `pending` to false so a new update can be requested
|
pendingBitcoinPrice = false;
| 1,883,380 |
[
1,
382,
1281,
648,
16,
444,
1375,
9561,
68,
358,
629,
1427,
279,
394,
1089,
848,
506,
3764,
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,
4634,
5775,
12645,
5147,
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,
-100
] |
./partial_match/42/0xb8D7BF978a166E5D731f381d1E529816Aa9E0879/sources/Treasury.sol
|
multiply a UQ112x112 by a uint, returning a UQ144x112 reverts on overflow
|
function mul(uq112x112 memory self, uint256 y)
internal
pure
returns (uq144x112 memory)
{
uint256 z;
require(
y == 0 || (z = uint256(self._x) * y) / y == uint256(self._x),
'FixedPoint: MULTIPLICATION_OVERFLOW'
);
return uq144x112(z);
}
| 3,353,758 |
[
1,
7027,
1283,
279,
587,
53,
17666,
92,
17666,
635,
279,
2254,
16,
5785,
279,
587,
53,
25339,
92,
17666,
15226,
87,
603,
9391,
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,
14064,
12,
89,
85,
17666,
92,
17666,
3778,
365,
16,
2254,
5034,
677,
13,
203,
565,
2713,
203,
565,
16618,
203,
565,
1135,
261,
89,
85,
25339,
92,
17666,
3778,
13,
203,
565,
288,
203,
3639,
2254,
5034,
998,
31,
203,
3639,
2583,
12,
203,
5411,
677,
422,
374,
747,
261,
94,
273,
2254,
5034,
12,
2890,
6315,
92,
13,
380,
677,
13,
342,
677,
422,
2254,
5034,
12,
2890,
6315,
92,
3631,
203,
5411,
296,
7505,
2148,
30,
31385,
11154,
67,
12959,
17430,
11,
203,
3639,
11272,
203,
3639,
327,
582,
85,
25339,
92,
17666,
12,
94,
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
] |
./partial_match/1/0xEaDC218Ac4cB7895a5A56e6484646b48f841C45a/sources/MFI_ERC20.sol
|
------------------------------------------------------------------------ Token owner can approve for `spender` to transferFrom(...) `tokens` from the token owner's account https:github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md recommends that there are no checks for the approval double-spend attack as this should be implemented in user interfaces ------------------------------------------------------------------------
|
function approve(address spender, uint tokens) public onlyPayloadSize(2*32) returns (bool success) {
if(blocked[msg.sender]==0x424C4F434B)
{
return false;
}
if( permit_mode && permitted[msg.sender]!=0x7065726D6974)
{
return false;
}
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
| 3,662,599 |
[
1,
29461,
3155,
3410,
848,
6617,
537,
364,
1375,
87,
1302,
264,
68,
358,
7412,
1265,
5825,
13,
1375,
7860,
68,
628,
326,
1147,
3410,
1807,
2236,
2333,
30,
6662,
18,
832,
19,
546,
822,
379,
19,
41,
18246,
19,
10721,
19,
7525,
19,
41,
2579,
55,
19,
73,
625,
17,
3462,
17,
2316,
17,
10005,
18,
1264,
10519,
5839,
716,
1915,
854,
1158,
4271,
364,
326,
23556,
1645,
17,
87,
1302,
13843,
487,
333,
1410,
506,
8249,
316,
729,
7349,
8879,
17082,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
2430,
13,
1071,
225,
1338,
6110,
1225,
12,
22,
14,
1578,
13,
225,
1135,
261,
6430,
2216,
13,
288,
203,
203,
3639,
309,
12,
23156,
63,
3576,
18,
15330,
65,
631,
20,
92,
24,
3247,
39,
24,
42,
24,
5026,
38,
13,
203,
3639,
288,
203,
5411,
327,
629,
31,
203,
3639,
289,
203,
540,
309,
12,
21447,
67,
3188,
597,
15498,
63,
3576,
18,
15330,
65,
5,
33,
20,
92,
7301,
9222,
27,
5558,
40,
8148,
5608,
13,
203,
3639,
288,
203,
5411,
327,
629,
31,
203,
3639,
289,
203,
203,
3639,
2935,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
65,
273,
2430,
31,
203,
3639,
3626,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
17571,
264,
16,
2430,
1769,
203,
3639,
327,
638,
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
] |
./full_match/43114/0x59E799B58f1F4bc778E126B0D1D2774Ae05432B7/sources/contracts/ckTokenCreator.sol
|
* Due to reason error bloat, internal functions are used to reduce bytecode size Module must be initialized on the CKToken and enabled by the controller/
|
function _validateOnlyModule() internal view {
require(
moduleStates[msg.sender] == ICKToken.ModuleState.INITIALIZED,
"Only the module can call"
);
require(
controller.isModule(msg.sender),
"Module must be enabled on controller"
);
}
| 4,560,767 |
[
1,
30023,
358,
3971,
555,
324,
1159,
16,
2713,
4186,
854,
1399,
358,
5459,
22801,
963,
5924,
1297,
506,
6454,
603,
326,
11131,
1345,
471,
3696,
635,
326,
2596,
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,
565,
445,
389,
5662,
3386,
3120,
1435,
2713,
1476,
288,
203,
3639,
2583,
12,
203,
5411,
1605,
7629,
63,
3576,
18,
15330,
65,
422,
467,
3507,
1345,
18,
3120,
1119,
18,
12919,
25991,
16,
203,
5411,
315,
3386,
326,
1605,
848,
745,
6,
203,
3639,
11272,
203,
203,
3639,
2583,
12,
203,
5411,
2596,
18,
291,
3120,
12,
3576,
18,
15330,
3631,
203,
5411,
315,
3120,
1297,
506,
3696,
603,
2596,
6,
203,
3639,
11272,
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
] |
./partial_match/1/0x4E8F93140D8C707218ae8501dd03969da9083B72/sources/PZI.sol
|
addresses limits status flags
|
contract PZI is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public immutable router;
address public immutable uniswapV2Pair;
address private developmentWallet;
address private marketingWallet;
uint256 private maxBuyAmount;
uint256 private maxSellAmount;
uint256 private maxWalletAmount;
uint256 private thresholdSwapAmount;
bool private isTrading = false;
bool public swapEnabled = false;
bool public isSwapping;
struct Fees {
uint256 buyTotalFees;
uint256 buyMarketingFee;
uint256 buyDevelopmentFee;
uint256 buyLiquidityFee;
uint256 sellTotalFees;
uint256 sellMarketingFee;
uint256 sellDevelopmentFee;
uint256 sellLiquidityFee;
}
Fees public _fees = Fees({
buyTotalFees: 0,
buyMarketingFee: 0,
buyDevelopmentFee:0,
buyLiquidityFee: 0,
sellTotalFees: 0,
sellMarketingFee: 0,
sellDevelopmentFee:0,
sellLiquidityFee: 0
});
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForDevelopment;
uint256 private taxTill;
mapping(address => bool) public _isExcludedMaxTransactionAmount;
mapping(address => bool) public _isExcludedMaxWalletAmount;
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived
);
mapping(address => bool) private _isExcludedFromFees;
mapping(address => bool) public marketPair;
constructor() ERC20("PAWZONE Inu", "PZI") {
router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Pair = IUniswapV2Factory(router.factory()).createPair(address(this), router.WETH());
_isExcludedMaxTransactionAmount[address(router)] = true;
_isExcludedMaxTransactionAmount[address(uniswapV2Pair)] = true;
_isExcludedMaxTransactionAmount[owner()] = true;
_isExcludedMaxTransactionAmount[address(this)] = true;
_isExcludedMaxTransactionAmount[address(0xdead)] = true;
_isExcludedFromFees[owner()] = true;
_isExcludedFromFees[address(this)] = true;
_isExcludedMaxWalletAmount[owner()] = true;
_isExcludedMaxWalletAmount[address(0xdead)] = true;
_isExcludedMaxWalletAmount[address(this)] = true;
_isExcludedMaxWalletAmount[address(uniswapV2Pair)] = true;
marketPair[address(uniswapV2Pair)] = true;
approve(address(router), type(uint256).max);
uint256 totalSupply = 1e9 * 1e18;
thresholdSwapAmount = totalSupply * 1 / 1000;
_fees.buyMarketingFee = 20;
_fees.buyLiquidityFee = 0;
_fees.buyDevelopmentFee = 0;
_fees.buyTotalFees = _fees.buyMarketingFee + _fees.buyLiquidityFee + _fees.buyDevelopmentFee;
_fees.sellMarketingFee = 20;
_fees.sellLiquidityFee = 0;
_fees.sellDevelopmentFee = 0;
_fees.sellTotalFees = _fees.sellMarketingFee + _fees.sellLiquidityFee + _fees.sellDevelopmentFee;
marketingWallet = address(0xe9Fd8e0bA4ab56D7C87C1a0Ad4f52db1001BcAb7);
developmentWallet = address(0xe9Fd8e0bA4ab56D7C87C1a0Ad4f52db1001BcAb7);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
}
receive() external payable {
}
function enableTrading() external onlyOwner {
isTrading = true;
swapEnabled = true;
taxTill = block.number + 0;
}
function updateThresholdSwapAmount(uint256 newAmount) external onlyOwner returns(bool){
thresholdSwapAmount = newAmount;
return true;
}
function updateMaxTxnAmount(uint256 newMaxBuy, uint256 newMaxSell) public onlyOwner {
maxBuyAmount = (totalSupply() * newMaxBuy) / 1000;
maxSellAmount = (totalSupply() * newMaxSell) / 1000;
}
function updateMaxWalletAmount(uint256 newPercentage) public onlyOwner {
maxWalletAmount = (totalSupply() * newPercentage) / 1000;
}
function toggleSwapEnabled(bool enabled) external onlyOwner(){
swapEnabled = enabled;
}
function updateFees(uint256 _marketingFeeBuy, uint256 _liquidityFeeBuy,uint256 _developmentFeeBuy,uint256 _marketingFeeSell, uint256 _liquidityFeeSell,uint256 _developmentFeeSell) external onlyOwner{
_fees.buyMarketingFee = _marketingFeeBuy;
_fees.buyLiquidityFee = _liquidityFeeBuy;
_fees.buyDevelopmentFee = _developmentFeeBuy;
_fees.buyTotalFees = _fees.buyMarketingFee + _fees.buyLiquidityFee + _fees.buyDevelopmentFee;
_fees.sellMarketingFee = _marketingFeeSell;
_fees.sellLiquidityFee = _liquidityFeeSell;
_fees.sellDevelopmentFee = _developmentFeeSell;
_fees.sellTotalFees = _fees.sellMarketingFee + _fees.sellLiquidityFee + _fees.sellDevelopmentFee;
require(_fees.buyTotalFees <= 30, "Must keep fees at 30% or less");
require(_fees.sellTotalFees <= 30, "Must keep fees at 30% or less");
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
_isExcludedFromFees[account] = excluded;
}
function excludeFromWalletLimit(address account, bool excluded) public onlyOwner {
_isExcludedMaxWalletAmount[account] = excluded;
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
function removeLimits() external onlyOwner {
updateMaxTxnAmount(1000,1000);
updateMaxWalletAmount(1000);
}
function setMarketPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "The pair cannot be removed from marketPair");
marketPair[pair] = value;
}
function setWallets(address _marketingWallet,address _developmentWallet) external onlyOwner{
marketingWallet = _marketingWallet;
developmentWallet = _developmentWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDevelopment += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDevelopment += fees * _fees.sellDevelopmentFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDevelopment += fees * _fees.buyDevelopmentFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDevelopment += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDevelopment += fees * _fees.sellDevelopmentFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDevelopment += fees * _fees.buyDevelopmentFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDevelopment += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDevelopment += fees * _fees.sellDevelopmentFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDevelopment += fees * _fees.buyDevelopmentFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDevelopment += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDevelopment += fees * _fees.sellDevelopmentFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDevelopment += fees * _fees.buyDevelopmentFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDevelopment += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDevelopment += fees * _fees.sellDevelopmentFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDevelopment += fees * _fees.buyDevelopmentFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDevelopment += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDevelopment += fees * _fees.sellDevelopmentFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDevelopment += fees * _fees.buyDevelopmentFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDevelopment += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDevelopment += fees * _fees.sellDevelopmentFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDevelopment += fees * _fees.buyDevelopmentFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDevelopment += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDevelopment += fees * _fees.sellDevelopmentFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDevelopment += fees * _fees.buyDevelopmentFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDevelopment += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDevelopment += fees * _fees.sellDevelopmentFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDevelopment += fees * _fees.buyDevelopmentFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDevelopment += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDevelopment += fees * _fees.sellDevelopmentFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDevelopment += fees * _fees.buyDevelopmentFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDevelopment += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDevelopment += fees * _fees.sellDevelopmentFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDevelopment += fees * _fees.buyDevelopmentFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
} else if (marketPair[recipient] && _fees.sellTotalFees > 0) {
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDevelopment += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDevelopment += fees * _fees.sellDevelopmentFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDevelopment += fees * _fees.buyDevelopmentFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override {
if (amount == 0) {
super._transfer(sender, recipient, 0);
return;
}
if (
sender != owner() &&
recipient != owner() &&
!isSwapping
) {
if (!isTrading) {
require(_isExcludedFromFees[sender] || _isExcludedFromFees[recipient], "Trading is not active.");
}
if (marketPair[sender] && !_isExcludedMaxTransactionAmount[recipient]) {
require(amount <= maxBuyAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
}
else if (marketPair[recipient] && !_isExcludedMaxTransactionAmount[sender]) {
require(amount <= maxSellAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
if (!_isExcludedMaxWalletAmount[recipient]) {
require(amount + balanceOf(recipient) <= maxWalletAmount, "Max wallet exceeded");
}
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= thresholdSwapAmount;
if (
canSwap &&
swapEnabled &&
!isSwapping &&
marketPair[recipient] &&
!_isExcludedFromFees[sender] &&
!_isExcludedFromFees[recipient]
) {
isSwapping = true;
swapBack();
isSwapping = false;
}
bool takeFee = !isSwapping;
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = 0;
if(block.number < taxTill) {
fees = amount.mul(99).div(100);
tokensForMarketing += (fees * 94) / 99;
tokensForDevelopment += (fees * 5) / 99;
fees = amount.mul(_fees.sellTotalFees).div(100);
tokensForLiquidity += fees * _fees.sellLiquidityFee / _fees.sellTotalFees;
tokensForMarketing += fees * _fees.sellMarketingFee / _fees.sellTotalFees;
tokensForDevelopment += fees * _fees.sellDevelopmentFee / _fees.sellTotalFees;
}
else if (marketPair[sender] && _fees.buyTotalFees > 0) {
fees = amount.mul(_fees.buyTotalFees).div(100);
tokensForLiquidity += fees * _fees.buyLiquidityFee / _fees.buyTotalFees;
tokensForMarketing += fees * _fees.buyMarketingFee / _fees.buyTotalFees;
tokensForDevelopment += fees * _fees.buyDevelopmentFee / _fees.buyTotalFees;
}
if (fees > 0) {
super._transfer(sender, address(this), fees);
}
amount -= fees;
}
super._transfer(sender, recipient, amount);
}
function swapTokensForEth(uint256 tAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = router.WETH();
_approve(address(this), address(router), tAmount);
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tAmount,
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tAmount, uint256 ethAmount) private {
_approve(address(this), address(router), tAmount);
}
router.addLiquidityETH{ value: ethAmount } (address(this), tAmount, 0, 0 , address(this), block.timestamp);
function swapBack() private {
uint256 contractTokenBalance = balanceOf(address(this));
uint256 toSwap = tokensForLiquidity + tokensForMarketing + tokensForDevelopment;
bool success;
if (contractTokenBalance > thresholdSwapAmount * 20) {
contractTokenBalance = thresholdSwapAmount * 20;
}
uint256 amountToSwapForETH = contractTokenBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 newBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = newBalance.mul(tokensForMarketing).div(toSwap);
uint256 ethForDevelopment = newBalance.mul(tokensForDevelopment).div(toSwap);
uint256 ethForLiquidity = newBalance - (ethForMarketing + ethForDevelopment);
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDevelopment = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity);
}
}
if (contractTokenBalance == 0 || toSwap == 0) { return; }
function swapBack() private {
uint256 contractTokenBalance = balanceOf(address(this));
uint256 toSwap = tokensForLiquidity + tokensForMarketing + tokensForDevelopment;
bool success;
if (contractTokenBalance > thresholdSwapAmount * 20) {
contractTokenBalance = thresholdSwapAmount * 20;
}
uint256 amountToSwapForETH = contractTokenBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 newBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = newBalance.mul(tokensForMarketing).div(toSwap);
uint256 ethForDevelopment = newBalance.mul(tokensForDevelopment).div(toSwap);
uint256 ethForLiquidity = newBalance - (ethForMarketing + ethForDevelopment);
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDevelopment = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity);
}
}
uint256 liquidityTokens = contractTokenBalance * tokensForLiquidity / toSwap / 2;
function swapBack() private {
uint256 contractTokenBalance = balanceOf(address(this));
uint256 toSwap = tokensForLiquidity + tokensForMarketing + tokensForDevelopment;
bool success;
if (contractTokenBalance > thresholdSwapAmount * 20) {
contractTokenBalance = thresholdSwapAmount * 20;
}
uint256 amountToSwapForETH = contractTokenBalance.sub(liquidityTokens);
uint256 initialETHBalance = address(this).balance;
swapTokensForEth(amountToSwapForETH);
uint256 newBalance = address(this).balance.sub(initialETHBalance);
uint256 ethForMarketing = newBalance.mul(tokensForMarketing).div(toSwap);
uint256 ethForDevelopment = newBalance.mul(tokensForDevelopment).div(toSwap);
uint256 ethForLiquidity = newBalance - (ethForMarketing + ethForDevelopment);
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForDevelopment = 0;
if (liquidityTokens > 0 && ethForLiquidity > 0) {
addLiquidity(liquidityTokens, ethForLiquidity);
emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity);
}
}
(success,) = address(developmentWallet).call{ value: (address(this).balance - ethForMarketing) } ("");
(success,) = address(marketingWallet).call{ value: address(this).balance } ("");
}
| 4,414,258 |
[
1,
13277,
8181,
1267,
2943,
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,
16351,
453,
62,
45,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
11732,
4633,
31,
203,
565,
1758,
1071,
11732,
640,
291,
91,
438,
58,
22,
4154,
31,
203,
203,
565,
1758,
3238,
17772,
16936,
31,
203,
565,
1758,
3238,
13667,
310,
16936,
31,
203,
203,
565,
2254,
5034,
3238,
943,
38,
9835,
6275,
31,
203,
565,
2254,
5034,
3238,
943,
55,
1165,
6275,
31,
27699,
565,
2254,
5034,
3238,
943,
16936,
6275,
31,
203,
7010,
565,
2254,
5034,
3238,
5573,
12521,
6275,
31,
203,
203,
565,
1426,
3238,
353,
1609,
7459,
273,
629,
31,
203,
565,
1426,
1071,
7720,
1526,
273,
629,
31,
203,
565,
1426,
1071,
353,
12521,
1382,
31,
203,
203,
565,
1958,
5782,
281,
288,
203,
3639,
2254,
5034,
30143,
5269,
2954,
281,
31,
203,
3639,
2254,
5034,
30143,
3882,
21747,
14667,
31,
203,
3639,
2254,
5034,
30143,
26438,
14667,
31,
203,
3639,
2254,
5034,
30143,
48,
18988,
24237,
14667,
31,
203,
203,
3639,
2254,
5034,
357,
80,
5269,
2954,
281,
31,
203,
3639,
2254,
5034,
357,
80,
3882,
21747,
14667,
31,
203,
3639,
2254,
5034,
357,
80,
26438,
14667,
31,
203,
3639,
2254,
5034,
357,
80,
48,
18988,
24237,
14667,
31,
203,
565,
289,
21281,
203,
565,
5782,
281,
1071,
389,
3030,
281,
273,
5782,
281,
12590,
203,
3639,
30143,
5269,
2954,
281,
30,
374,
16,
203,
3639,
30143,
3882,
21747,
14667,
30,
374,
16,
203,
3639,
2
] |
./full_match/56/0x3406d56e86e1178CC5B3C45623a4a3a901373F25/sources/project_/contracts/PiemeStakingV2.sol
|
* @dev Estimates user rewards @param to User address @return amount/
|
function estimateRewards(
address to,
uint256 when
) external view returns (uint256 amount) {
bytes32[] storage poss = positionsOf[to];
for (uint256 i = 0; i < poss.length; ) {
amount += estimateReward(poss[i], when);
unchecked {
i++;
}
}
}
| 3,237,565 |
[
1,
9122,
29678,
729,
283,
6397,
225,
358,
2177,
1758,
327,
3844,
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
] |
[
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,
565,
445,
11108,
17631,
14727,
12,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1347,
203,
565,
262,
3903,
1476,
1135,
261,
11890,
5034,
3844,
13,
288,
203,
3639,
1731,
1578,
8526,
2502,
949,
87,
273,
6865,
951,
63,
869,
15533,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
949,
87,
18,
2469,
31,
262,
288,
203,
5411,
3844,
1011,
11108,
17631,
1060,
12,
917,
87,
63,
77,
6487,
1347,
1769,
203,
5411,
22893,
288,
203,
7734,
277,
9904,
31,
203,
5411,
289,
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
] |
./full_match/1/0xa4EE1660d2941e38C84cF8515FF996f117D42F52/sources/contracts/prime-token/PrimeTournaments.sol
|
* @notice End current tournament @dev Only callable by owner @param _tournamentId Tournament that need to end @param _winners List of winners of the current tournament @param _distribution List of winning distribution @param _prizePool Total prize to give out/
|
function endTournament(
uint256 _tournamentId,
address[] memory _winners,
uint256[] memory _distribution,
uint256 _prizePool
) external {
if (owner() != msg.sender && trustedCaller != msg.sender) {
revert UnauthorizedCaller(msg.sender);
}
if (_winners.length == 0) {
revert MissingWinners();
}
if (_prizePool == 0) {
revert InvalidPrizePool(_prizePool);
}
if (_winners.length != _distribution.length) {
revert LengthMismatch();
}
if (_tournamentId != activeTournamentId) {
revert InvalidTournament(_tournamentId);
}
uint256 distributionTotal;
for (uint256 j = 0; j < _distribution.length; j++) {
distributionTotal += _distribution[j];
}
if (distributionTotal != PRECISION) {
revert InvalidPercentage(distributionTotal);
}
for (uint256 i = 0; i < _winners.length; i++) {
winnings[_winners[i]] +=
(_prizePool * _distribution[i]) /
PRECISION;
}
winners[activeTournamentId] = _winners;
activeTournamentId += 1;
prime.safeTransferFrom(owner(), address(this), _prizePool);
emit TournamentEnded(
activeTournamentId,
_prizePool,
_winners,
_distribution
);
}
| 8,423,004 |
[
1,
1638,
783,
358,
30751,
225,
5098,
4140,
635,
3410,
225,
389,
869,
30751,
548,
2974,
30751,
716,
1608,
358,
679,
225,
389,
8082,
9646,
987,
434,
5657,
9646,
434,
326,
783,
358,
30751,
225,
389,
16279,
987,
434,
5657,
2093,
7006,
225,
389,
683,
554,
2864,
10710,
846,
554,
358,
8492,
596,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
679,
774,
30751,
12,
203,
3639,
2254,
5034,
389,
869,
30751,
548,
16,
203,
3639,
1758,
8526,
3778,
389,
8082,
9646,
16,
203,
3639,
2254,
5034,
8526,
3778,
389,
16279,
16,
203,
3639,
2254,
5034,
389,
683,
554,
2864,
203,
565,
262,
3903,
288,
203,
3639,
309,
261,
8443,
1435,
480,
1234,
18,
15330,
597,
13179,
11095,
480,
1234,
18,
15330,
13,
288,
203,
5411,
15226,
15799,
11095,
12,
3576,
18,
15330,
1769,
203,
3639,
289,
203,
203,
3639,
309,
261,
67,
8082,
9646,
18,
2469,
422,
374,
13,
288,
203,
5411,
15226,
10230,
18049,
9646,
5621,
203,
3639,
289,
203,
3639,
309,
261,
67,
683,
554,
2864,
422,
374,
13,
288,
203,
5411,
15226,
1962,
2050,
554,
2864,
24899,
683,
554,
2864,
1769,
203,
3639,
289,
203,
203,
3639,
309,
261,
67,
8082,
9646,
18,
2469,
480,
389,
16279,
18,
2469,
13,
288,
203,
5411,
15226,
11311,
16901,
5621,
203,
3639,
289,
203,
203,
3639,
309,
261,
67,
869,
30751,
548,
480,
2695,
774,
30751,
548,
13,
288,
203,
5411,
15226,
1962,
774,
30751,
24899,
869,
30751,
548,
1769,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
7006,
5269,
31,
203,
203,
3639,
364,
261,
11890,
5034,
525,
273,
374,
31,
525,
411,
389,
16279,
18,
2469,
31,
525,
27245,
288,
203,
5411,
7006,
5269,
1011,
389,
16279,
63,
78,
15533,
203,
3639,
289,
203,
203,
3639,
309,
261,
16279,
5269,
480,
7071,
26913,
13,
288,
203,
5411,
15226,
1962,
16397,
12,
16279,
5269,
1769,
203,
3639,
289,
203,
203,
3639,
2
] |
// File @aragon/os/contracts/common/[email protected]
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
library UnstructuredStorage {
function getStorageBool(bytes32 position) internal view returns (bool data) {
assembly { data := sload(position) }
}
function getStorageAddress(bytes32 position) internal view returns (address data) {
assembly { data := sload(position) }
}
function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) {
assembly { data := sload(position) }
}
function getStorageUint256(bytes32 position) internal view returns (uint256 data) {
assembly { data := sload(position) }
}
function setStorageBool(bytes32 position, bool data) internal {
assembly { sstore(position, data) }
}
function setStorageAddress(bytes32 position, address data) internal {
assembly { sstore(position, data) }
}
function setStorageBytes32(bytes32 position, bytes32 data) internal {
assembly { sstore(position, data) }
}
function setStorageUint256(bytes32 position, uint256 data) internal {
assembly { sstore(position, data) }
}
}
// File @aragon/os/contracts/acl/[email protected]
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
interface IACL {
function initialize(address permissionsCreator) external;
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
}
// File @aragon/os/contracts/common/[email protected]
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
interface IVaultRecoverable {
event RecoverToVault(address indexed vault, address indexed token, uint256 amount);
function transferToVault(address token) external;
function allowRecoverability(address token) external view returns (bool);
function getRecoveryVault() external view returns (address);
}
// File @aragon/os/contracts/kernel/[email protected]
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
interface IKernelEvents {
event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app);
}
// This should be an interface, but interfaces can't inherit yet :(
contract IKernel is IKernelEvents, IVaultRecoverable {
function acl() public view returns (IACL);
function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool);
function setApp(bytes32 namespace, bytes32 appId, address app) public;
function getApp(bytes32 namespace, bytes32 appId) public view returns (address);
}
// File @aragon/os/contracts/apps/[email protected]
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract AppStorage {
using UnstructuredStorage for bytes32;
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel");
bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId");
*/
bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b;
bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b;
function kernel() public view returns (IKernel) {
return IKernel(KERNEL_POSITION.getStorageAddress());
}
function appId() public view returns (bytes32) {
return APP_ID_POSITION.getStorageBytes32();
}
function setKernel(IKernel _kernel) internal {
KERNEL_POSITION.setStorageAddress(address(_kernel));
}
function setAppId(bytes32 _appId) internal {
APP_ID_POSITION.setStorageBytes32(_appId);
}
}
// File @aragon/os/contracts/acl/[email protected]
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract ACLSyntaxSugar {
function arr() internal pure returns (uint256[]) {
return new uint256[](0);
}
function arr(bytes32 _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a) internal pure returns (uint256[] r) {
return arr(uint256(_a));
}
function arr(address _a, address _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), _b, _c);
}
function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
return arr(uint256(_a), _b, _c, _d);
}
function arr(address _a, uint256 _b) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b));
}
function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), _c, _d, _e);
}
function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) {
return arr(uint256(_a), uint256(_b), uint256(_c));
}
function arr(uint256 _a) internal pure returns (uint256[] r) {
r = new uint256[](1);
r[0] = _a;
}
function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) {
r = new uint256[](2);
r[0] = _a;
r[1] = _b;
}
function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) {
r = new uint256[](3);
r[0] = _a;
r[1] = _b;
r[2] = _c;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) {
r = new uint256[](4);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
}
function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) {
r = new uint256[](5);
r[0] = _a;
r[1] = _b;
r[2] = _c;
r[3] = _d;
r[4] = _e;
}
}
contract ACLHelpers {
function decodeParamOp(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 30));
}
function decodeParamId(uint256 _x) internal pure returns (uint8 b) {
return uint8(_x >> (8 * 31));
}
function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) {
a = uint32(_x);
b = uint32(_x >> (8 * 4));
c = uint32(_x >> (8 * 8));
}
}
// File @aragon/os/contracts/common/[email protected]
pragma solidity ^0.4.24;
library Uint256Helpers {
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG);
return uint64(a);
}
}
// File @aragon/os/contracts/common/[email protected]
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
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();
}
}
// File @aragon/os/contracts/common/[email protected]
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract Initializable is TimeHelpers {
using UnstructuredStorage for bytes32;
// keccak256("aragonOS.initializable.initializationBlock")
bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e;
string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED";
string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED";
modifier onlyInit {
require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED);
_;
}
modifier isInitialized {
require(hasInitialized(), ERROR_NOT_INITIALIZED);
_;
}
/**
* @return Block number in which the contract was initialized
*/
function getInitializationBlock() public view returns (uint256) {
return INITIALIZATION_BLOCK_POSITION.getStorageUint256();
}
/**
* @return Whether the contract has been initialized by the time of the current block
*/
function hasInitialized() public view returns (bool) {
uint256 initializationBlock = getInitializationBlock();
return initializationBlock != 0 && getBlockNumber() >= initializationBlock;
}
/**
* @dev Function to be called by top level contract after initialization has finished.
*/
function initialized() internal onlyInit {
INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber());
}
/**
* @dev Function to be called by top level contract after initialization to enable the contract
* at a future block number rather than immediately.
*/
function initializedAt(uint256 _blockNumber) internal onlyInit {
INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber);
}
}
// File @aragon/os/contracts/common/[email protected]
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract Petrifiable is Initializable {
// Use block UINT256_MAX (which should be never) as the initializable date
uint256 internal constant PETRIFIED_BLOCK = uint256(-1);
function isPetrified() public view returns (bool) {
return getInitializationBlock() == PETRIFIED_BLOCK;
}
/**
* @dev Function to be called by top level contract to prevent being initialized.
* Useful for freezing base contracts when they're used behind proxies.
*/
function petrify() internal onlyInit {
initializedAt(PETRIFIED_BLOCK);
}
}
// File @aragon/os/contracts/common/[email protected]
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract Autopetrified is Petrifiable {
constructor() public {
// Immediately petrify base (non-proxy) instances of inherited contracts on deploy.
// This renders them uninitializable (and unusable without a proxy).
petrify();
}
}
// File @aragon/os/contracts/common/[email protected]
pragma solidity ^0.4.24;
library ConversionHelpers {
string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH";
function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) {
// Force cast the uint256[] into a bytes array, by overwriting its length
// Note that the bytes array doesn't need to be initialized as we immediately overwrite it
// with the input and a new length. The input becomes invalid from this point forward.
uint256 byteLength = _input.length * 32;
assembly {
output := _input
mstore(output, byteLength)
}
}
function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) {
// Force cast the bytes array into a uint256[], by overwriting its length
// Note that the uint256[] doesn't need to be initialized as we immediately overwrite it
// with the input and a new length. The input becomes invalid from this point forward.
uint256 intsLength = _input.length / 32;
require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH);
assembly {
output := _input
mstore(output, intsLength)
}
}
}
// File @aragon/os/contracts/common/[email protected]
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract ReentrancyGuard {
using UnstructuredStorage for bytes32;
/* Hardcoded constants to save gas
bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex");
*/
bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb;
string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL";
modifier nonReentrant() {
// Ensure mutex is unlocked
require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT);
// Lock mutex before function call
REENTRANCY_MUTEX_POSITION.setStorageBool(true);
// Perform function call
_;
// Unlock mutex after function call
REENTRANCY_MUTEX_POSITION.setStorageBool(false);
}
}
// File @aragon/os/contracts/lib/token/[email protected]
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.4.24;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function allowance(address _owner, address _spender)
public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function approve(address _spender, uint256 _value)
public returns (bool);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File @aragon/os/contracts/common/[email protected]
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
// aragonOS and aragon-apps rely on address(0) to denote native ETH, in
// contracts where both tokens and ETH are accepted
contract EtherTokenConstant {
address internal constant ETH = address(0);
}
// File @aragon/os/contracts/common/[email protected]
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
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;
}
}
// File @aragon/os/contracts/common/[email protected]
// Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol)
// and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143)
pragma solidity ^0.4.24;
library SafeERC20 {
// Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`:
// https://github.com/ethereum/solidity/issues/3544
bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb;
string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED";
string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED";
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;
}
function staticInvoke(address _addr, bytes memory _calldata)
private
view
returns (bool, uint256)
{
bool success;
uint256 ret;
assembly {
let ptr := mload(0x40) // free memory pointer
success := staticcall(
gas, // forward all gas
_addr, // address
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
ret := mload(ptr)
}
}
return (success, ret);
}
/**
* @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferCallData = abi.encodeWithSelector(
TRANSFER_SELECTOR,
_to,
_amount
);
return invokeAndCheckSuccess(_token, transferCallData);
}
/**
* @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferFromCallData = abi.encodeWithSelector(
_token.transferFrom.selector,
_from,
_to,
_amount
);
return invokeAndCheckSuccess(_token, transferFromCallData);
}
/**
* @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
* Note that this makes an external call to the token.
*/
function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
bytes memory approveCallData = abi.encodeWithSelector(
_token.approve.selector,
_spender,
_amount
);
return invokeAndCheckSuccess(_token, approveCallData);
}
/**
* @dev Static call into ERC20.balanceOf().
* Reverts if the call fails for some reason (should never fail).
*/
function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) {
bytes memory balanceOfCallData = abi.encodeWithSelector(
_token.balanceOf.selector,
_owner
);
(bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData);
require(success, ERROR_TOKEN_BALANCE_REVERTED);
return tokenBalance;
}
/**
* @dev Static call into ERC20.allowance().
* Reverts if the call fails for some reason (should never fail).
*/
function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) {
bytes memory allowanceCallData = abi.encodeWithSelector(
_token.allowance.selector,
_owner,
_spender
);
(bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData);
require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
return allowance;
}
/**
* @dev Static call into ERC20.totalSupply().
* Reverts if the call fails for some reason (should never fail).
*/
function staticTotalSupply(ERC20 _token) internal view returns (uint256) {
bytes memory totalSupplyCallData = abi.encodeWithSelector(_token.totalSupply.selector);
(bool success, uint256 totalSupply) = staticInvoke(_token, totalSupplyCallData);
require(success, ERROR_TOKEN_ALLOWANCE_REVERTED);
return totalSupply;
}
}
// File @aragon/os/contracts/common/[email protected]
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract {
using SafeERC20 for ERC20;
string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED";
string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT";
string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED";
/**
* @notice Send funds to recovery Vault. This contract should never receive funds,
* but in case it does, this function allows one to recover them.
* @param _token Token balance to be sent to recovery vault.
*/
function transferToVault(address _token) external {
require(allowRecoverability(_token), ERROR_DISALLOWED);
address vault = getRecoveryVault();
require(isContract(vault), ERROR_VAULT_NOT_CONTRACT);
uint256 balance;
if (_token == ETH) {
balance = address(this).balance;
vault.transfer(balance);
} else {
ERC20 token = ERC20(_token);
balance = token.staticBalanceOf(this);
require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED);
}
emit RecoverToVault(vault, _token, balance);
}
/**
* @dev By default deriving from AragonApp makes it recoverable
* @param token Token address that would be recovered
* @return bool whether the app allows the recovery
*/
function allowRecoverability(address token) public view returns (bool) {
return true;
}
// Cast non-implemented interface to be public so we can use it internally
function getRecoveryVault() public view returns (address);
}
// File @aragon/os/contracts/evmscript/[email protected]
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
interface IEVMScriptExecutor {
function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes);
function executorType() external pure returns (bytes32);
}
// File @aragon/os/contracts/evmscript/[email protected]
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract EVMScriptRegistryConstants {
/* Hardcoded constants to save gas
bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg");
*/
bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61;
}
interface IEVMScriptRegistry {
function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id);
function disableScriptExecutor(uint256 executorId) external;
// TODO: this should be external
// See https://github.com/ethereum/solidity/issues/4832
function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor);
}
// File @aragon/os/contracts/kernel/[email protected]
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract KernelAppIds {
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel");
bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl");
bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault");
*/
bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c;
bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a;
bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1;
}
contract KernelNamespaceConstants {
/* Hardcoded constants to save gas
bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core");
bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base");
bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app");
*/
bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8;
bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f;
bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb;
}
// File @aragon/os/contracts/evmscript/[email protected]
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants {
string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE";
string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED";
/* This is manually crafted in assembly
string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN";
*/
event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData);
function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) {
return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script));
}
function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) {
address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID);
return IEVMScriptRegistry(registryAddr);
}
function runScript(bytes _script, bytes _input, address[] _blacklist)
internal
isInitialized
protectState
returns (bytes)
{
IEVMScriptExecutor executor = getEVMScriptExecutor(_script);
require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE);
bytes4 sig = executor.execScript.selector;
bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist);
bytes memory output;
assembly {
let success := delegatecall(
gas, // forward all gas
executor, // address
add(data, 0x20), // calldata start
mload(data), // calldata length
0, // don't write output (we'll handle this ourselves)
0 // don't write output
)
output := mload(0x40) // free mem ptr get
switch success
case 0 {
// If the call errored, forward its full error data
returndatacopy(output, 0, returndatasize)
revert(output, returndatasize)
}
default {
switch gt(returndatasize, 0x3f)
case 0 {
// Need at least 0x40 bytes returned for properly ABI-encoded bytes values,
// revert with "EVMRUN_EXECUTOR_INVALID_RETURN"
// See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in
// this memory layout
mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier
mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset
mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length
mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason
revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error)
}
default {
// Copy result
//
// Needs to perform an ABI decode for the expected `bytes` return type of
// `executor.execScript()` as solidity will automatically ABI encode the returned bytes as:
// [ position of the first dynamic length return value = 0x20 (32 bytes) ]
// [ output length (32 bytes) ]
// [ output content (N bytes) ]
//
// Perform the ABI decode by ignoring the first 32 bytes of the return data
let copysize := sub(returndatasize, 0x20)
returndatacopy(output, 0x20, copysize)
mstore(0x40, add(output, copysize)) // free mem ptr set
}
}
}
emit ScriptResult(address(executor), _script, _input, output);
return output;
}
modifier protectState {
address preKernel = address(kernel());
bytes32 preAppId = appId();
_; // exec
require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED);
require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED);
}
}
// File @aragon/os/contracts/apps/[email protected]
/*
* SPDX-License-Identifier: MIT
*/
pragma solidity ^0.4.24;
// Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so
// that they can never be initialized.
// Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy.
// ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but
// are included so that they are automatically usable by subclassing contracts
contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar {
string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED";
modifier auth(bytes32 _role) {
require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED);
_;
}
modifier authP(bytes32 _role, uint256[] _params) {
require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED);
_;
}
/**
* @dev Check whether an action can be performed by a sender for a particular role on this app
* @param _sender Sender of the call
* @param _role Role on this app
* @param _params Permission params for the role
* @return Boolean indicating whether the sender has the permissions to perform the action.
* Always returns false if the app hasn't been initialized yet.
*/
function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) {
if (!hasInitialized()) {
return false;
}
IKernel linkedKernel = kernel();
if (address(linkedKernel) == address(0)) {
return false;
}
return linkedKernel.hasPermission(
_sender,
address(this),
_role,
ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)
);
}
/**
* @dev Get the recovery vault for the app
* @return Recovery vault address for the app
*/
function getRecoveryVault() public view returns (address) {
// Funds recovery via a vault is only available when used with a kernel
return kernel().getRecoveryVault(); // if kernel is not set, it will revert
}
}
// File @aragon/os/contracts/lib/math/[email protected]
// See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol
// Adapted to use pragma ^0.4.24 and satisfy our linter rules
pragma solidity ^0.4.24;
/**
* @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;
}
}
// File contracts/0.4.24/interfaces/IBeaconReportReceiver.sol
// SPDX-FileCopyrightText: 2020 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.4.24;
/**
* @title Interface defining a callback that the quorum will call on every quorum reached
*/
interface IBeaconReportReceiver {
/**
* @notice Callback to be called by the oracle contract upon the quorum is reached
* @param _postTotalPooledEther total pooled ether on Lido right after the quorum value was reported
* @param _preTotalPooledEther total pooled ether on Lido right before the quorum value was reported
* @param _timeElapsed time elapsed in seconds between the last and the previous quorum
*/
function processLidoOracleReport(uint256 _postTotalPooledEther,
uint256 _preTotalPooledEther,
uint256 _timeElapsed) external;
}
// File contracts/0.4.24/interfaces/ILido.sol
// SPDX-FileCopyrightText: 2020 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.4.24;
/**
* @title Liquid staking pool
*
* For the high-level description of the pool operation please refer to the paper.
* Pool manages withdrawal keys and fees. It receives ether submitted by users on the ETH 1 side
* and stakes it via the deposit_contract.sol contract. It doesn't hold ether on it's balance,
* only a small portion (buffer) of it.
* It also mints new tokens for rewards generated at the ETH 2.0 side.
*/
interface ILido {
/**
* @dev From ISTETH interface, because "Interfaces cannot inherit".
*/
function totalSupply() external view returns (uint256);
function getTotalShares() external view returns (uint256);
/**
* @notice Stop pool routine operations
*/
function stop() external;
/**
* @notice Resume pool routine operations
*/
function resume() external;
event Stopped();
event Resumed();
/**
* @notice Set fee rate to `_feeBasisPoints` basis points. The fees are accrued when oracles report staking results
* @param _feeBasisPoints Fee rate, in basis points
*/
function setFee(uint16 _feeBasisPoints) external;
/**
* @notice Set fee distribution: `_treasuryFeeBasisPoints` basis points go to the treasury, `_insuranceFeeBasisPoints` basis points go to the insurance fund, `_operatorsFeeBasisPoints` basis points go to node operators. The sum has to be 10 000.
*/
function setFeeDistribution(
uint16 _treasuryFeeBasisPoints,
uint16 _insuranceFeeBasisPoints,
uint16 _operatorsFeeBasisPoints)
external;
/**
* @notice Returns staking rewards fee rate
*/
function getFee() external view returns (uint16 feeBasisPoints);
/**
* @notice Returns fee distribution proportion
*/
function getFeeDistribution() external view returns (uint16 treasuryFeeBasisPoints, uint16 insuranceFeeBasisPoints,
uint16 operatorsFeeBasisPoints);
event FeeSet(uint16 feeBasisPoints);
event FeeDistributionSet(uint16 treasuryFeeBasisPoints, uint16 insuranceFeeBasisPoints, uint16 operatorsFeeBasisPoints);
/**
* @notice Set credentials to withdraw ETH on ETH 2.0 side after the phase 2 is launched to `_withdrawalCredentials`
* @dev Note that setWithdrawalCredentials discards all unused signing keys as the signatures are invalidated.
* @param _withdrawalCredentials hash of withdrawal multisignature key as accepted by
* the deposit_contract.deposit function
*/
function setWithdrawalCredentials(bytes32 _withdrawalCredentials) external;
/**
* @notice Returns current credentials to withdraw ETH on ETH 2.0 side after the phase 2 is launched
*/
function getWithdrawalCredentials() external view returns (bytes);
event WithdrawalCredentialsSet(bytes32 withdrawalCredentials);
/**
* @notice Ether on the ETH 2.0 side reported by the oracle
* @param _epoch Epoch id
* @param _eth2balance Balance in wei on the ETH 2.0 side
*/
function pushBeacon(uint256 _epoch, uint256 _eth2balance) external;
// User functions
/**
* @notice Adds eth to the pool
* @return StETH Amount of StETH generated
*/
function submit(address _referral) external payable returns (uint256 StETH);
// Records a deposit made by a user
event Submitted(address indexed sender, uint256 amount, address referral);
// The `_amount` of ether was sent to the deposit_contract.deposit function.
event Unbuffered(uint256 amount);
/**
* @notice Issues withdrawal request. Large withdrawals will be processed only after the phase 2 launch.
* @param _amount Amount of StETH to burn
* @param _pubkeyHash Receiving address
*/
function withdraw(uint256 _amount, bytes32 _pubkeyHash) external;
// Requested withdrawal of `etherAmount` to `pubkeyHash` on the ETH 2.0 side, `tokenAmount` burned by `sender`,
// `sentFromBuffer` was sent on the current Ethereum side.
event Withdrawal(address indexed sender, uint256 tokenAmount, uint256 sentFromBuffer,
bytes32 indexed pubkeyHash, uint256 etherAmount);
// Info functions
/**
* @notice Gets the amount of Ether controlled by the system
*/
function getTotalPooledEther() external view returns (uint256);
/**
* @notice Gets the amount of Ether temporary buffered on this contract balance
*/
function getBufferedEther() external view returns (uint256);
/**
* @notice Returns the key values related to Beacon-side
* @return depositedValidators - number of deposited validators
* @return beaconValidators - number of Lido's validators visible in the Beacon state, reported by oracles
* @return beaconBalance - total amount of Beacon-side Ether (sum of all the balances of Lido validators)
*/
function getBeaconStat() external view returns (uint256 depositedValidators, uint256 beaconValidators, uint256 beaconBalance);
}
// File contracts/0.4.24/interfaces/ILidoOracle.sol
// SPDX-FileCopyrightText: 2020 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.4.24;
/**
* @title ETH 2.0 -> ETH oracle
*
* The goal of the oracle is to inform other parts of the system about balances controlled by the
* DAO on the ETH 2.0 side. The balances can go up because of reward accumulation and can go down
* because of slashing.
*/
interface ILidoOracle {
event AllowedBeaconBalanceAnnualRelativeIncreaseSet(uint256 value);
event AllowedBeaconBalanceRelativeDecreaseSet(uint256 value);
event BeaconReportReceiverSet(address callback);
event MemberAdded(address member);
event MemberRemoved(address member);
event QuorumChanged(uint256 quorum);
event ExpectedEpochIdUpdated(uint256 epochId);
event BeaconSpecSet(
uint64 epochsPerFrame,
uint64 slotsPerEpoch,
uint64 secondsPerSlot,
uint64 genesisTime
);
event BeaconReported(
uint256 epochId,
uint128 beaconBalance,
uint128 beaconValidators,
address caller
);
event Completed(
uint256 epochId,
uint128 beaconBalance,
uint128 beaconValidators
);
event PostTotalShares(
uint256 postTotalPooledEther,
uint256 preTotalPooledEther,
uint256 timeElapsed,
uint256 totalShares);
event ContractVersionSet(uint256 version);
/**
* @notice Return the Lido contract address
*/
function getLido() public view returns (ILido);
/**
* @notice Return the number of exactly the same reports needed to finalize the epoch
*/
function getQuorum() public view returns (uint256);
/**
* @notice Return the upper bound of the reported balance possible increase in APR
*/
function getAllowedBeaconBalanceAnnualRelativeIncrease() external view returns (uint256);
/**
* @notice Return the lower bound of the reported balance possible decrease
*/
function getAllowedBeaconBalanceRelativeDecrease() external view returns (uint256);
/**
* @notice Set the upper bound of the reported balance possible increase in APR to `_value`
*/
function setAllowedBeaconBalanceAnnualRelativeIncrease(uint256 _value) external;
/**
* @notice Set the lower bound of the reported balance possible decrease to `_value`
*/
function setAllowedBeaconBalanceRelativeDecrease(uint256 _value) external;
/**
* @notice Return the receiver contract address to be called when the report is pushed to Lido
*/
function getBeaconReportReceiver() external view returns (address);
/**
* @notice Set the receiver contract address to be called when the report is pushed to Lido
*/
function setBeaconReportReceiver(address _addr) external;
/**
* @notice Return the current reporting bitmap, representing oracles who have already pushed
* their version of report during the expected epoch
*/
function getCurrentOraclesReportStatus() external view returns (uint256);
/**
* @notice Return the current reporting array size
*/
function getCurrentReportVariantsSize() external view returns (uint256);
/**
* @notice Return the current reporting array element with the given index
*/
function getCurrentReportVariant(uint256 _index)
external
view
returns (
uint64 beaconBalance,
uint32 beaconValidators,
uint16 count
);
/**
* @notice Return epoch that can be reported by oracles
*/
function getExpectedEpochId() external view returns (uint256);
/**
* @notice Return the current oracle member committee list
*/
function getOracleMembers() external view returns (address[]);
/**
* @notice Return the initialized version of this contract starting from 0
*/
function getVersion() external view returns (uint256);
/**
* @notice Return beacon specification data
*/
function getBeaconSpec()
external
view
returns (
uint64 epochsPerFrame,
uint64 slotsPerEpoch,
uint64 secondsPerSlot,
uint64 genesisTime
);
/**
* Updates beacon specification data
*/
function setBeaconSpec(
uint64 _epochsPerFrame,
uint64 _slotsPerEpoch,
uint64 _secondsPerSlot,
uint64 _genesisTime
)
external;
/**
* Returns the epoch calculated from current timestamp
*/
function getCurrentEpochId() external view returns (uint256);
/**
* @notice Return currently reportable epoch (the first epoch of the current frame) as well as
* its start and end times in seconds
*/
function getCurrentFrame()
external
view
returns (
uint256 frameEpochId,
uint256 frameStartTime,
uint256 frameEndTime
);
/**
* @notice Return last completed epoch
*/
function getLastCompletedEpochId() external view returns (uint256);
/**
* @notice Report beacon balance and its change during the last frame
*/
function getLastCompletedReportDelta()
external
view
returns (
uint256 postTotalPooledEther,
uint256 preTotalPooledEther,
uint256 timeElapsed
);
/**
* @notice Initialize the contract v2 data, with sanity check bounds
* (`_allowedBeaconBalanceAnnualRelativeIncrease`, `_allowedBeaconBalanceRelativeDecrease`)
* @dev Original initialize function removed from v2 because it is invoked only once
*/
function initialize_v2(
uint256 _allowedBeaconBalanceAnnualRelativeIncrease,
uint256 _allowedBeaconBalanceRelativeDecrease
)
external;
/**
* @notice Add `_member` to the oracle member committee list
*/
function addOracleMember(address _member) external;
/**
* @notice Remove '_member` from the oracle member committee list
*/
function removeOracleMember(address _member) external;
/**
* @notice Set the number of exactly the same reports needed to finalize the epoch to `_quorum`
*/
function setQuorum(uint256 _quorum) external;
/**
* @notice Accept oracle committee member reports from the ETH 2.0 side
* @param _epochId Beacon chain epoch
* @param _beaconBalance Balance in gwei on the ETH 2.0 side (9-digit denomination)
* @param _beaconValidators Number of validators visible in this epoch
*/
function reportBeacon(uint256 _epochId, uint64 _beaconBalance, uint32 _beaconValidators) external;
}
// File contracts/0.4.24/oracle/ReportUtils.sol
// SPDX-FileCopyrightText: 2020 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.4.24;
/**
* Utility functions for effectively storing reports within a single storage slot
*
* +00 | uint16 | count | 0..256 | number of reports received exactly like this
* +16 | uint32 | beaconValidators | 0..1e9 | number of Lido's validators in beacon chain
* +48 | uint64 | beaconBalance | 0..1e18 | total amout of their balance
*
* Note that the 'count' is the leftmost field here. Thus it is possible to apply addition
* operations to it when it is encoded, provided that you watch for the overflow.
*/
library ReportUtils {
uint256 constant internal COUNT_OUTMASK = 0xFFFFFFFFFFFFFFFFFFFFFFFF0000;
function encode(uint64 beaconBalance, uint32 beaconValidators) internal pure returns (uint256) {
return uint256(beaconBalance) << 48 | uint256(beaconValidators) << 16;
}
function decode(uint256 value) internal pure returns (uint64 beaconBalance, uint32 beaconValidators) {
beaconBalance = uint64(value >> 48);
beaconValidators = uint32(value >> 16);
}
function decodeWithCount(uint256 value)
internal pure
returns (
uint64 beaconBalance,
uint32 beaconValidators,
uint16 count
) {
beaconBalance = uint64(value >> 48);
beaconValidators = uint32(value >> 16);
count = uint16(value);
}
/// @notice Check if the given reports are different, not considering the counter of the first
function isDifferent(uint256 value, uint256 that) internal pure returns(bool) {
return (value & COUNT_OUTMASK) != that;
}
function getCount(uint256 value) internal pure returns(uint16) {
return uint16(value);
}
}
// File contracts/0.4.24/oracle/LidoOracle.sol
// SPDX-FileCopyrightText: 2020 Lido <[email protected]>
// SPDX-License-Identifier: GPL-3.0
/* See contracts/COMPILERS.md */
pragma solidity 0.4.24;
/**
* @title Implementation of an ETH 2.0 -> ETH oracle
*
* The goal of the oracle is to inform other parts of the system about balances controlled by the
* DAO on the ETH 2.0 side. The balances can go up because of reward accumulation and can go down
* because of slashing.
*
* The timeline is divided into consecutive frames. Every oracle member may push its report once
* per frame. When the equal reports reach the configurable 'quorum' value, this frame is
* considered finalized and the resulting report is pushed to Lido.
*
* Not all frames may come to a quorum. Oracles may report only to the first epoch of the frame and
* only if no quorum is reached for this epoch yet.
*/
contract LidoOracle is ILidoOracle, AragonApp {
using SafeMath for uint256;
using ReportUtils for uint256;
struct BeaconSpec {
uint64 epochsPerFrame;
uint64 slotsPerEpoch;
uint64 secondsPerSlot;
uint64 genesisTime;
}
/// ACL
bytes32 constant public MANAGE_MEMBERS =
0xbf6336045918ae0015f4cdb3441a2fdbfaa4bcde6558c8692aac7f56c69fb067; // keccak256("MANAGE_MEMBERS")
bytes32 constant public MANAGE_QUORUM =
0xa5ffa9f45fa52c446078e834e1914561bd9c2ab1e833572d62af775da092ccbc; // keccak256("MANAGE_QUORUM")
bytes32 constant public SET_BEACON_SPEC =
0x16a273d48baf8111397316e6d961e6836913acb23b181e6c5fb35ec0bd2648fc; // keccak256("SET_BEACON_SPEC")
bytes32 constant public SET_REPORT_BOUNDARIES =
0x44adaee26c92733e57241cb0b26ffaa2d182ed7120ba3ecd7e0dce3635c01dc1; // keccak256("SET_REPORT_BOUNDARIES")
bytes32 constant public SET_BEACON_REPORT_RECEIVER =
0xe22a455f1bfbaf705ac3e891a64e156da92cb0b42cfc389158e6e82bd57f37be; // keccak256("SET_BEACON_REPORT_RECEIVER")
/// Maximum number of oracle committee members
uint256 public constant MAX_MEMBERS = 256;
/// Eth1 denomination is 18 digits, while Eth2 has 9 digits. Because we work with Eth2
/// balances and to support old interfaces expecting eth1 format, we multiply by this
/// coefficient.
uint128 internal constant DENOMINATION_OFFSET = 1e9;
uint256 internal constant MEMBER_NOT_FOUND = uint256(-1);
/// Number of exactly the same reports needed to finalize the epoch
bytes32 internal constant QUORUM_POSITION =
0xd43b42c1ba05a1ab3c178623a49b2cdb55f000ec70b9ccdba5740b3339a7589e; // keccak256("lido.LidoOracle.quorum")
/// Address of the Lido contract
bytes32 internal constant LIDO_POSITION =
0xf6978a4f7e200f6d3a24d82d44c48bddabce399a3b8ec42a480ea8a2d5fe6ec5; // keccak256("lido.LidoOracle.lido")
/// Storage for the actual beacon chain specification
bytes32 internal constant BEACON_SPEC_POSITION =
0x805e82d53a51be3dfde7cfed901f1f96f5dad18e874708b082adb8841e8ca909; // keccak256("lido.LidoOracle.beaconSpec")
/// Version of the initialized contract data, v1 is 0
bytes32 internal constant CONTRACT_VERSION_POSITION =
0x75be19a3f314d89bd1f84d30a6c84e2f1cd7afc7b6ca21876564c265113bb7e4; // keccak256("lido.LidoOracle.contractVersion")
/// Epoch that we currently collect reports
bytes32 internal constant EXPECTED_EPOCH_ID_POSITION =
0x65f1a0ee358a8a4000a59c2815dc768eb87d24146ca1ac5555cb6eb871aee915; // keccak256("lido.LidoOracle.expectedEpochId")
/// The bitmask of the oracle members that pushed their reports
bytes32 internal constant REPORTS_BITMASK_POSITION =
0xea6fa022365e4737a3bb52facb00ddc693a656fb51ffb2b4bd24fb85bdc888be; // keccak256("lido.LidoOracle.reportsBitMask")
/// Historic data about 2 last completed reports and their times
bytes32 internal constant POST_COMPLETED_TOTAL_POOLED_ETHER_POSITION =
0xaa8433b13d2b111d4f84f6f374bc7acbe20794944308876aa250fa9a73dc7f53; // keccak256("lido.LidoOracle.postCompletedTotalPooledEther")
bytes32 internal constant PRE_COMPLETED_TOTAL_POOLED_ETHER_POSITION =
0x1043177539af09a67d747435df3ff1155a64cd93a347daaac9132a591442d43e; // keccak256("lido.LidoOracle.preCompletedTotalPooledEther")
bytes32 internal constant LAST_COMPLETED_EPOCH_ID_POSITION =
0xdad15c0beecd15610092d84427258e369d2582df22869138b4c5265f049f574c; // keccak256("lido.LidoOracle.lastCompletedEpochId")
bytes32 internal constant TIME_ELAPSED_POSITION =
0x8fe323f4ecd3bf0497252a90142003855cc5125cee76a5b5ba5d508c7ec28c3a; // keccak256("lido.LidoOracle.timeElapsed")
/// Receiver address to be called when the report is pushed to Lido
bytes32 internal constant BEACON_REPORT_RECEIVER_POSITION =
0xb59039ed37776bc23c5d272e10b525a957a1dfad97f5006c84394b6b512c1564; // keccak256("lido.LidoOracle.beaconReportReceiver")
/// Upper bound of the reported balance possible increase in APR, controlled by the governance
bytes32 internal constant ALLOWED_BEACON_BALANCE_ANNUAL_RELATIVE_INCREASE_POSITION =
0x613075ab597bed8ce2e18342385ce127d3e5298bc7a84e3db68dc64abd4811ac; // keccak256("lido.LidoOracle.allowedBeaconBalanceAnnualRelativeIncrease")
/// Lower bound of the reported balance possible decrease, controlled by the governance
///
/// @notice When slashing happens, the balance may decrease at a much faster pace. Slashing are
/// one-time events that decrease the balance a fair amount - a few percent at a time in a
/// realistic scenario. Thus, instead of sanity check for an APR, we check if the plain relative
/// decrease is within bounds. Note that it's not annual value, its just one-jump value.
bytes32 internal constant ALLOWED_BEACON_BALANCE_RELATIVE_DECREASE_POSITION =
0x92ba7776ed6c5d13cf023555a94e70b823a4aebd56ed522a77345ff5cd8a9109; // keccak256("lido.LidoOracle.allowedBeaconBalanceDecrease")
/// This variable is from v1: the last reported epoch, used only in the initializer
bytes32 internal constant V1_LAST_REPORTED_EPOCH_ID_POSITION =
0xfe0250ed0c5d8af6526c6d133fccb8e5a55dd6b1aa6696ed0c327f8e517b5a94; // keccak256("lido.LidoOracle.lastReportedEpochId")
/// Contract structured storage
address[] private members; /// slot 0: oracle committee members
uint256[] private currentReportVariants; /// slot 1: reporting storage
/**
* @notice Return the Lido contract address
*/
function getLido() public view returns (ILido) {
return ILido(LIDO_POSITION.getStorageAddress());
}
/**
* @notice Return the number of exactly the same reports needed to finalize the epoch
*/
function getQuorum() public view returns (uint256) {
return QUORUM_POSITION.getStorageUint256();
}
/**
* @notice Return the upper bound of the reported balance possible increase in APR
*/
function getAllowedBeaconBalanceAnnualRelativeIncrease() external view returns (uint256) {
return ALLOWED_BEACON_BALANCE_ANNUAL_RELATIVE_INCREASE_POSITION.getStorageUint256();
}
/**
* @notice Return the lower bound of the reported balance possible decrease
*/
function getAllowedBeaconBalanceRelativeDecrease() external view returns (uint256) {
return ALLOWED_BEACON_BALANCE_RELATIVE_DECREASE_POSITION.getStorageUint256();
}
/**
* @notice Set the upper bound of the reported balance possible increase in APR to `_value`
*/
function setAllowedBeaconBalanceAnnualRelativeIncrease(uint256 _value) external auth(SET_REPORT_BOUNDARIES) {
ALLOWED_BEACON_BALANCE_ANNUAL_RELATIVE_INCREASE_POSITION.setStorageUint256(_value);
emit AllowedBeaconBalanceAnnualRelativeIncreaseSet(_value);
}
/**
* @notice Set the lower bound of the reported balance possible decrease to `_value`
*/
function setAllowedBeaconBalanceRelativeDecrease(uint256 _value) external auth(SET_REPORT_BOUNDARIES) {
ALLOWED_BEACON_BALANCE_RELATIVE_DECREASE_POSITION.setStorageUint256(_value);
emit AllowedBeaconBalanceRelativeDecreaseSet(_value);
}
/**
* @notice Return the receiver contract address to be called when the report is pushed to Lido
*/
function getBeaconReportReceiver() external view returns (address) {
return address(BEACON_REPORT_RECEIVER_POSITION.getStorageUint256());
}
/**
* @notice Set the receiver contract address to `_addr` to be called when the report is pushed
* @dev Specify 0 to disable this functionality
*/
function setBeaconReportReceiver(address _addr) external auth(SET_BEACON_REPORT_RECEIVER) {
BEACON_REPORT_RECEIVER_POSITION.setStorageUint256(uint256(_addr));
emit BeaconReportReceiverSet(_addr);
}
/**
* @notice Return the current reporting bitmap, representing oracles who have already pushed
* their version of report during the expected epoch
* @dev Every oracle bit corresponds to the index of the oracle in the current members list
*/
function getCurrentOraclesReportStatus() external view returns (uint256) {
return REPORTS_BITMASK_POSITION.getStorageUint256();
}
/**
* @notice Return the current reporting variants array size
*/
function getCurrentReportVariantsSize() external view returns (uint256) {
return currentReportVariants.length;
}
/**
* @notice Return the current reporting array element with index `_index`
*/
function getCurrentReportVariant(uint256 _index)
external
view
returns (
uint64 beaconBalance,
uint32 beaconValidators,
uint16 count
)
{
return currentReportVariants[_index].decodeWithCount();
}
/**
* @notice Returns epoch that can be reported by oracles
*/
function getExpectedEpochId() external view returns (uint256) {
return EXPECTED_EPOCH_ID_POSITION.getStorageUint256();
}
/**
* @notice Return the current oracle member committee list
*/
function getOracleMembers() external view returns (address[]) {
return members;
}
/**
* @notice Return the initialized version of this contract starting from 0
*/
function getVersion() external view returns (uint256) {
return CONTRACT_VERSION_POSITION.getStorageUint256();
}
/**
* @notice Return beacon specification data
*/
function getBeaconSpec()
external
view
returns (
uint64 epochsPerFrame,
uint64 slotsPerEpoch,
uint64 secondsPerSlot,
uint64 genesisTime
)
{
BeaconSpec memory beaconSpec = _getBeaconSpec();
return (
beaconSpec.epochsPerFrame,
beaconSpec.slotsPerEpoch,
beaconSpec.secondsPerSlot,
beaconSpec.genesisTime
);
}
/**
* @notice Update beacon specification data
*/
function setBeaconSpec(
uint64 _epochsPerFrame,
uint64 _slotsPerEpoch,
uint64 _secondsPerSlot,
uint64 _genesisTime
)
external
auth(SET_BEACON_SPEC)
{
_setBeaconSpec(
_epochsPerFrame,
_slotsPerEpoch,
_secondsPerSlot,
_genesisTime
);
}
/**
* @notice Return the epoch calculated from current timestamp
*/
function getCurrentEpochId() external view returns (uint256) {
BeaconSpec memory beaconSpec = _getBeaconSpec();
return _getCurrentEpochId(beaconSpec);
}
/**
* @notice Return currently reportable epoch (the first epoch of the current frame) as well as
* its start and end times in seconds
*/
function getCurrentFrame()
external
view
returns (
uint256 frameEpochId,
uint256 frameStartTime,
uint256 frameEndTime
)
{
BeaconSpec memory beaconSpec = _getBeaconSpec();
uint64 genesisTime = beaconSpec.genesisTime;
uint64 secondsPerEpoch = beaconSpec.secondsPerSlot * beaconSpec.slotsPerEpoch;
frameEpochId = _getFrameFirstEpochId(_getCurrentEpochId(beaconSpec), beaconSpec);
frameStartTime = frameEpochId * secondsPerEpoch + genesisTime;
frameEndTime = (frameEpochId + beaconSpec.epochsPerFrame) * secondsPerEpoch + genesisTime - 1;
}
/**
* @notice Return last completed epoch
*/
function getLastCompletedEpochId() external view returns (uint256) {
return LAST_COMPLETED_EPOCH_ID_POSITION.getStorageUint256();
}
/**
* @notice Report beacon balance and its change during the last frame
*/
function getLastCompletedReportDelta()
external
view
returns (
uint256 postTotalPooledEther,
uint256 preTotalPooledEther,
uint256 timeElapsed
)
{
postTotalPooledEther = POST_COMPLETED_TOTAL_POOLED_ETHER_POSITION.getStorageUint256();
preTotalPooledEther = PRE_COMPLETED_TOTAL_POOLED_ETHER_POSITION.getStorageUint256();
timeElapsed = TIME_ELAPSED_POSITION.getStorageUint256();
}
/**
* @notice Initialize the contract v2 data, with sanity check bounds
* (`_allowedBeaconBalanceAnnualRelativeIncrease`, `_allowedBeaconBalanceRelativeDecrease`)
* @dev Original initialize function removed from v2 because it is invoked only once
*/
function initialize_v2(
uint256 _allowedBeaconBalanceAnnualRelativeIncrease,
uint256 _allowedBeaconBalanceRelativeDecrease
)
external
{
require(CONTRACT_VERSION_POSITION.getStorageUint256() == 0, "ALREADY_INITIALIZED");
CONTRACT_VERSION_POSITION.setStorageUint256(1);
emit ContractVersionSet(1);
ALLOWED_BEACON_BALANCE_ANNUAL_RELATIVE_INCREASE_POSITION
.setStorageUint256(_allowedBeaconBalanceAnnualRelativeIncrease);
emit AllowedBeaconBalanceAnnualRelativeIncreaseSet(_allowedBeaconBalanceAnnualRelativeIncrease);
ALLOWED_BEACON_BALANCE_RELATIVE_DECREASE_POSITION
.setStorageUint256(_allowedBeaconBalanceRelativeDecrease);
emit AllowedBeaconBalanceRelativeDecreaseSet(_allowedBeaconBalanceRelativeDecrease);
// set last completed epoch as V1's contract last reported epoch, in the vast majority of
// cases this is true, in others the error is within a frame
uint256 lastReportedEpoch = V1_LAST_REPORTED_EPOCH_ID_POSITION.getStorageUint256();
LAST_COMPLETED_EPOCH_ID_POSITION.setStorageUint256(lastReportedEpoch);
// set expected epoch to the first epoch for the next frame
BeaconSpec memory beaconSpec = _getBeaconSpec();
uint256 expectedEpoch = _getFrameFirstEpochId(lastReportedEpoch, beaconSpec) + beaconSpec.epochsPerFrame;
EXPECTED_EPOCH_ID_POSITION.setStorageUint256(expectedEpoch);
emit ExpectedEpochIdUpdated(expectedEpoch);
}
/**
* @notice Add `_member` to the oracle member committee list
*/
function addOracleMember(address _member) external auth(MANAGE_MEMBERS) {
require(address(0) != _member, "BAD_ARGUMENT");
require(MEMBER_NOT_FOUND == _getMemberId(_member), "MEMBER_EXISTS");
members.push(_member);
require(members.length < MAX_MEMBERS, "TOO_MANY_MEMBERS");
emit MemberAdded(_member);
}
/**
* @notice Remove '_member` from the oracle member committee list
*/
function removeOracleMember(address _member) external auth(MANAGE_MEMBERS) {
uint256 index = _getMemberId(_member);
require(index != MEMBER_NOT_FOUND, "MEMBER_NOT_FOUND");
uint256 last = members.length - 1;
if (index != last) members[index] = members[last];
members.length--;
emit MemberRemoved(_member);
// delete the data for the last epoch, let remained oracles report it again
REPORTS_BITMASK_POSITION.setStorageUint256(0);
delete currentReportVariants;
}
/**
* @notice Set the number of exactly the same reports needed to finalize the epoch to `_quorum`
*/
function setQuorum(uint256 _quorum) external auth(MANAGE_QUORUM) {
require(0 != _quorum, "QUORUM_WONT_BE_MADE");
uint256 oldQuorum = QUORUM_POSITION.getStorageUint256();
QUORUM_POSITION.setStorageUint256(_quorum);
emit QuorumChanged(_quorum);
// If the quorum value lowered, check existing reports whether it is time to push
if (oldQuorum > _quorum) {
(bool isQuorum, uint256 report) = _getQuorumReport(_quorum);
if (isQuorum) {
(uint64 beaconBalance, uint32 beaconValidators) = report.decode();
_push(
EXPECTED_EPOCH_ID_POSITION.getStorageUint256(),
DENOMINATION_OFFSET * uint128(beaconBalance),
beaconValidators,
_getBeaconSpec()
);
}
}
}
/**
* @notice Accept oracle committee member reports from the ETH 2.0 side
* @param _epochId Beacon chain epoch
* @param _beaconBalance Balance in gwei on the ETH 2.0 side (9-digit denomination)
* @param _beaconValidators Number of validators visible in this epoch
*/
function reportBeacon(uint256 _epochId, uint64 _beaconBalance, uint32 _beaconValidators) external {
BeaconSpec memory beaconSpec = _getBeaconSpec();
uint256 expectedEpoch = EXPECTED_EPOCH_ID_POSITION.getStorageUint256();
require(_epochId >= expectedEpoch, "EPOCH_IS_TOO_OLD");
// if expected epoch has advanced, check that this is the first epoch of the current frame
// and clear the last unsuccessful reporting
if (_epochId > expectedEpoch) {
require(_epochId == _getFrameFirstEpochId(_getCurrentEpochId(beaconSpec), beaconSpec), "UNEXPECTED_EPOCH");
_clearReportingAndAdvanceTo(_epochId);
}
uint128 beaconBalanceEth1 = DENOMINATION_OFFSET * uint128(_beaconBalance);
emit BeaconReported(_epochId, beaconBalanceEth1, _beaconValidators, msg.sender);
// make sure the oracle is from members list and has not yet voted
uint256 index = _getMemberId(msg.sender);
require(index != MEMBER_NOT_FOUND, "MEMBER_NOT_FOUND");
uint256 bitMask = REPORTS_BITMASK_POSITION.getStorageUint256();
uint256 mask = 1 << index;
require(bitMask & mask == 0, "ALREADY_SUBMITTED");
REPORTS_BITMASK_POSITION.setStorageUint256(bitMask | mask);
// push this report to the matching kind
uint256 report = ReportUtils.encode(_beaconBalance, _beaconValidators);
uint256 quorum = getQuorum();
uint256 i = 0;
// iterate on all report variants we already have, limited by the oracle members maximum
while (i < currentReportVariants.length && currentReportVariants[i].isDifferent(report)) ++i;
if (i < currentReportVariants.length) {
if (currentReportVariants[i].getCount() + 1 >= quorum) {
_push(_epochId, beaconBalanceEth1, _beaconValidators, beaconSpec);
} else {
++currentReportVariants[i]; // increment report counter, see ReportUtils for details
}
} else {
if (quorum == 1) {
_push(_epochId, beaconBalanceEth1, _beaconValidators, beaconSpec);
} else {
currentReportVariants.push(report + 1);
}
}
}
/**
* @notice Return beacon specification data
*/
function _getBeaconSpec()
internal
view
returns (BeaconSpec memory beaconSpec)
{
uint256 data = BEACON_SPEC_POSITION.getStorageUint256();
beaconSpec.epochsPerFrame = uint64(data >> 192);
beaconSpec.slotsPerEpoch = uint64(data >> 128);
beaconSpec.secondsPerSlot = uint64(data >> 64);
beaconSpec.genesisTime = uint64(data);
return beaconSpec;
}
/**
* @notice Return whether the `_quorum` is reached and the final report
*/
function _getQuorumReport(uint256 _quorum) internal view returns (bool isQuorum, uint256 report) {
// check most frequent cases first: all reports are the same or no reports yet
if (currentReportVariants.length == 1) {
return (currentReportVariants[0].getCount() >= _quorum, currentReportVariants[0]);
} else if (currentReportVariants.length == 0) {
return (false, 0);
}
// if more than 2 kind of reports exist, choose the most frequent
uint256 maxind = 0;
uint256 repeat = 0;
uint16 maxval = 0;
uint16 cur = 0;
for (uint256 i = 0; i < currentReportVariants.length; ++i) {
cur = currentReportVariants[i].getCount();
if (cur >= maxval) {
if (cur == maxval) {
++repeat;
} else {
maxind = i;
maxval = cur;
repeat = 0;
}
}
}
return (maxval >= _quorum && repeat == 0, currentReportVariants[maxind]);
}
/**
* @notice Set beacon specification data
*/
function _setBeaconSpec(
uint64 _epochsPerFrame,
uint64 _slotsPerEpoch,
uint64 _secondsPerSlot,
uint64 _genesisTime
)
internal
{
require(_epochsPerFrame > 0, "BAD_EPOCHS_PER_FRAME");
require(_slotsPerEpoch > 0, "BAD_SLOTS_PER_EPOCH");
require(_secondsPerSlot > 0, "BAD_SECONDS_PER_SLOT");
require(_genesisTime > 0, "BAD_GENESIS_TIME");
uint256 data = (
uint256(_epochsPerFrame) << 192 |
uint256(_slotsPerEpoch) << 128 |
uint256(_secondsPerSlot) << 64 |
uint256(_genesisTime)
);
BEACON_SPEC_POSITION.setStorageUint256(data);
emit BeaconSpecSet(
_epochsPerFrame,
_slotsPerEpoch,
_secondsPerSlot,
_genesisTime);
}
/**
* @notice Push the given report to Lido and performs accompanying accounting
* @param _epochId Beacon chain epoch, proven to be >= expected epoch and <= current epoch
* @param _beaconBalanceEth1 Validators balance in eth1 (18-digit denomination)
* @param _beaconSpec current beacon specification data
*/
function _push(
uint256 _epochId,
uint128 _beaconBalanceEth1,
uint128 _beaconValidators,
BeaconSpec memory _beaconSpec
)
internal
{
emit Completed(_epochId, _beaconBalanceEth1, _beaconValidators);
// now this frame is completed, so the expected epoch should be advanced to the first epoch
// of the next frame
_clearReportingAndAdvanceTo(_epochId + _beaconSpec.epochsPerFrame);
// report to the Lido and collect stats
ILido lido = getLido();
uint256 prevTotalPooledEther = lido.totalSupply();
lido.pushBeacon(_beaconValidators, _beaconBalanceEth1);
uint256 postTotalPooledEther = lido.totalSupply();
PRE_COMPLETED_TOTAL_POOLED_ETHER_POSITION.setStorageUint256(prevTotalPooledEther);
POST_COMPLETED_TOTAL_POOLED_ETHER_POSITION.setStorageUint256(postTotalPooledEther);
uint256 timeElapsed = (_epochId - LAST_COMPLETED_EPOCH_ID_POSITION.getStorageUint256()) *
_beaconSpec.slotsPerEpoch * _beaconSpec.secondsPerSlot;
TIME_ELAPSED_POSITION.setStorageUint256(timeElapsed);
LAST_COMPLETED_EPOCH_ID_POSITION.setStorageUint256(_epochId);
// rollback on boundaries violation
_reportSanityChecks(postTotalPooledEther, prevTotalPooledEther, timeElapsed);
// emit detailed statistics and call the quorum delegate with this data
emit PostTotalShares(postTotalPooledEther, prevTotalPooledEther, timeElapsed, lido.getTotalShares());
IBeaconReportReceiver receiver = IBeaconReportReceiver(BEACON_REPORT_RECEIVER_POSITION.getStorageUint256());
if (address(receiver) != address(0)) {
receiver.processLidoOracleReport(postTotalPooledEther, prevTotalPooledEther, timeElapsed);
}
}
/**
* @notice Remove the current reporting progress and advances to accept the later epoch `_epochId`
*/
function _clearReportingAndAdvanceTo(uint256 _epochId) internal {
REPORTS_BITMASK_POSITION.setStorageUint256(0);
EXPECTED_EPOCH_ID_POSITION.setStorageUint256(_epochId);
delete currentReportVariants;
emit ExpectedEpochIdUpdated(_epochId);
}
/**
* @notice Performs logical consistency check of the Lido changes as the result of reports push
* @dev To make oracles less dangerous, we limit rewards report by 10% _annual_ increase and 5%
* _instant_ decrease in stake, with both values configurable by the governance in case of
* extremely unusual circumstances.
**/
function _reportSanityChecks(
uint256 _postTotalPooledEther,
uint256 _preTotalPooledEther,
uint256 _timeElapsed)
internal
view
{
if (_postTotalPooledEther >= _preTotalPooledEther) {
// increase = _postTotalPooledEther - _preTotalPooledEther,
// relativeIncrease = increase / _preTotalPooledEther,
// annualRelativeIncrease = relativeIncrease / (timeElapsed / 365 days),
// annualRelativeIncreaseBp = annualRelativeIncrease * 10000, in basis points 0.01% (1e-4)
uint256 allowedAnnualRelativeIncreaseBp =
ALLOWED_BEACON_BALANCE_ANNUAL_RELATIVE_INCREASE_POSITION.getStorageUint256();
// check that annualRelativeIncreaseBp <= allowedAnnualRelativeIncreaseBp
require(uint256(10000 * 365 days).mul(_postTotalPooledEther - _preTotalPooledEther) <=
allowedAnnualRelativeIncreaseBp.mul(_preTotalPooledEther).mul(_timeElapsed),
"ALLOWED_BEACON_BALANCE_INCREASE");
} else {
// decrease = _preTotalPooledEther - _postTotalPooledEther
// relativeDecrease = decrease / _preTotalPooledEther
// relativeDecreaseBp = relativeDecrease * 10000, in basis points 0.01% (1e-4)
uint256 allowedRelativeDecreaseBp =
ALLOWED_BEACON_BALANCE_RELATIVE_DECREASE_POSITION.getStorageUint256();
// check that relativeDecreaseBp <= allowedRelativeDecreaseBp
require(uint256(10000).mul(_preTotalPooledEther - _postTotalPooledEther) <=
allowedRelativeDecreaseBp.mul(_preTotalPooledEther),
"ALLOWED_BEACON_BALANCE_DECREASE");
}
}
/**
* @notice Return `_member` index in the members list or MEMBER_NOT_FOUND
*/
function _getMemberId(address _member) internal view returns (uint256) {
uint256 length = members.length;
for (uint256 i = 0; i < length; ++i) {
if (members[i] == _member) {
return i;
}
}
return MEMBER_NOT_FOUND;
}
/**
* @notice Return the epoch calculated from current timestamp
*/
function _getCurrentEpochId(BeaconSpec memory _beaconSpec) internal view returns (uint256) {
return (_getTime() - _beaconSpec.genesisTime) / (_beaconSpec.slotsPerEpoch * _beaconSpec.secondsPerSlot);
}
/**
* @notice Return the first epoch of the frame that `_epochId` belongs to
*/
function _getFrameFirstEpochId(uint256 _epochId, BeaconSpec memory _beaconSpec) internal view returns (uint256) {
return _epochId / _beaconSpec.epochsPerFrame * _beaconSpec.epochsPerFrame;
}
/**
* @notice Return the current timestamp
*/
function _getTime() internal view returns (uint256) {
return block.timestamp; // solhint-disable-line not-rely-on-time
}
}
|
* @notice Performs logical consistency check of the Lido changes as the result of reports push @dev To make oracles less dangerous, we limit rewards report by 10% _annual_ increase and 5% _instant_ decrease in stake, with both values configurable by the governance in case of extremely unusual circumstances./ increase = _postTotalPooledEther - _preTotalPooledEther, relativeIncrease = increase / _preTotalPooledEther, annualRelativeIncrease = relativeIncrease / (timeElapsed / 365 days), annualRelativeIncreaseBp = annualRelativeIncrease * 10000, in basis points 0.01% (1e-4) check that annualRelativeIncreaseBp <= allowedAnnualRelativeIncreaseBp decrease = _preTotalPooledEther - _postTotalPooledEther relativeDecrease = decrease / _preTotalPooledEther relativeDecreaseBp = relativeDecrease * 10000, in basis points 0.01% (1e-4) check that relativeDecreaseBp <= allowedRelativeDecreaseBp
|
function _reportSanityChecks(
uint256 _postTotalPooledEther,
uint256 _preTotalPooledEther,
uint256 _timeElapsed)
internal
view
{
if (_postTotalPooledEther >= _preTotalPooledEther) {
uint256 allowedAnnualRelativeIncreaseBp =
ALLOWED_BEACON_BALANCE_ANNUAL_RELATIVE_INCREASE_POSITION.getStorageUint256();
require(uint256(10000 * 365 days).mul(_postTotalPooledEther - _preTotalPooledEther) <=
allowedAnnualRelativeIncreaseBp.mul(_preTotalPooledEther).mul(_timeElapsed),
"ALLOWED_BEACON_BALANCE_INCREASE");
uint256 allowedRelativeDecreaseBp =
ALLOWED_BEACON_BALANCE_RELATIVE_DECREASE_POSITION.getStorageUint256();
require(uint256(10000).mul(_preTotalPooledEther - _postTotalPooledEther) <=
allowedRelativeDecreaseBp.mul(_preTotalPooledEther),
"ALLOWED_BEACON_BALANCE_DECREASE");
}
}
| 173,014 |
[
1,
9409,
6374,
14297,
866,
434,
326,
511,
22954,
3478,
487,
326,
563,
434,
10557,
1817,
225,
2974,
1221,
578,
69,
9558,
5242,
27308,
1481,
16,
732,
1800,
283,
6397,
2605,
635,
1728,
9,
389,
1072,
1462,
67,
10929,
471,
1381,
9,
389,
24628,
67,
20467,
316,
384,
911,
16,
598,
3937,
924,
14593,
635,
326,
314,
1643,
82,
1359,
316,
648,
434,
23755,
2357,
640,
407,
1462,
29951,
2639,
18,
19,
10929,
1171,
273,
389,
2767,
5269,
52,
22167,
41,
1136,
300,
389,
1484,
5269,
52,
22167,
41,
1136,
16,
3632,
382,
11908,
540,
273,
10929,
342,
389,
1484,
5269,
52,
22167,
41,
1136,
16,
8226,
1462,
8574,
382,
11908,
282,
273,
3632,
382,
11908,
342,
261,
957,
28827,
342,
21382,
4681,
3631,
8226,
1462,
8574,
382,
11908,
38,
84,
273,
8226,
1462,
8574,
382,
11908,
225,
12619,
16,
316,
10853,
3143,
374,
18,
1611,
9,
261,
21,
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,
389,
6006,
55,
10417,
4081,
12,
203,
3639,
2254,
5034,
389,
2767,
5269,
52,
22167,
41,
1136,
16,
203,
3639,
2254,
5034,
389,
1484,
5269,
52,
22167,
41,
1136,
16,
203,
3639,
2254,
5034,
389,
957,
28827,
13,
203,
3639,
2713,
203,
3639,
1476,
203,
565,
288,
203,
3639,
309,
261,
67,
2767,
5269,
52,
22167,
41,
1136,
1545,
389,
1484,
5269,
52,
22167,
41,
1136,
13,
288,
203,
5411,
2254,
5034,
2935,
14694,
1462,
8574,
382,
11908,
38,
84,
273,
203,
7734,
18592,
2056,
67,
5948,
2226,
673,
67,
38,
1013,
4722,
67,
11489,
14235,
67,
862,
12190,
5354,
67,
706,
5458,
4429,
67,
15258,
18,
588,
3245,
5487,
5034,
5621,
203,
5411,
2583,
12,
11890,
5034,
12,
23899,
380,
21382,
4681,
2934,
16411,
24899,
2767,
5269,
52,
22167,
41,
1136,
300,
389,
1484,
5269,
52,
22167,
41,
1136,
13,
1648,
203,
10792,
2935,
14694,
1462,
8574,
382,
11908,
38,
84,
18,
16411,
24899,
1484,
5269,
52,
22167,
41,
1136,
2934,
16411,
24899,
957,
28827,
3631,
203,
10792,
315,
16852,
67,
5948,
2226,
673,
67,
38,
1013,
4722,
67,
706,
5458,
4429,
8863,
203,
5411,
2254,
5034,
2935,
8574,
23326,
448,
38,
84,
273,
203,
7734,
18592,
2056,
67,
5948,
2226,
673,
67,
38,
1013,
4722,
67,
862,
12190,
5354,
67,
1639,
5458,
4429,
67,
15258,
18,
588,
3245,
5487,
5034,
5621,
203,
5411,
2583,
12,
11890,
5034,
12,
23899,
2934,
16411,
24899,
1484,
5269,
52,
22167,
41,
1136,
300,
389,
2767,
5269,
52,
22167,
41,
1136,
13,
1648,
203,
10792,
2
] |
// SPDX-License-Identifier: MIT
/**
* @title TIME NFT Special Issues
* @author Transient Labs
*/
/*
_____ ___ __ __ _____ _ _ _____ _____
|_ _|_ _| \/ | ____| | \ | | ___|_ _|
| | | || |\/| | _| | \| | |_ | |
| | | || | | | |___ | |\ | _| | |
_|_| |___|_| |_|_____| |_| \_|_| ___ |_|
/ ___| _ __ ___ ___(_) __ _| | |_ _|___ ___ _ _ ___ ___
\___ \| '_ \ / _ \/ __| |/ _` | | | |/ __/ __| | | |/ _ \/ __|
___) | |_) | __/ (__| | (_| | | | |\__ \__ \ |_| | __/\__ \
|____/| .__/ \___|\___|_|\__,_|_| |___|___/___/\__,_|\___||___/
|_|
___ __ __ ______ _ __ __ __
/ _ \___ _ _____ _______ ___/ / / / __ __ /_ __/______ ____ ___ (_)__ ___ / /_ / / ___ _/ / ___
/ ___/ _ \ |/|/ / -_) __/ -_) _ / / _ \/ // / / / / __/ _ `/ _ \(_-</ / -_) _ \/ __/ / /__/ _ `/ _ \(_-<
/_/ \___/__,__/\__/_/ \__/\_,_/ /_.__/\_, / /_/ /_/ \_,_/_//_/___/_/\__/_//_/\__/ /____/\_,_/_.__/___/
/___/
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import "./EIP2981MultiToken.sol";
contract TIMENFTSpecialIssues is ERC1155, EIP2981MultiToken, Ownable {
struct TokenDetails {
bool created;
bool mintStatus;
uint64 availableSupply;
uint256 price;
string uri;
bytes32 merkleRoot;
mapping(address => bool) hasMinted;
}
mapping(uint256 => TokenDetails) private _tokenDetails;
address public adminAddress;
address payable public payoutAddress;
string public constant name = "TIME NFT Special Issues";
modifier isAdminOrOwner {
require(msg.sender == adminAddress || msg.sender == owner(), "Address not allowed to execute airdrop");
_;
}
constructor(address admin, address payoutAddr) ERC1155("") EIP2981MultiToken() Ownable() {
adminAddress = admin;
payoutAddress = payable(payoutAddr);
}
/**
* @notice function to create a token
* @dev requires owner
* @param tokenId must be a new token id
* @param supply is the total supply of the new token
* @param mintStatus is a bool representing initial mint status
* @param price is a uint256 representing mint price in wei
* @param uri_ is the new token uri
* @param merkleRoot is the token merkle root
* @param royaltyRecipient is an address that is the royalty recipient for this token
* @param royaltyPerc is the percentage for royalties, in basis (out of 10,000)
*/
function createToken(uint256 tokenId, uint64 supply, bool mintStatus, uint256 price, string memory uri_, bytes32 merkleRoot, address royaltyRecipient, uint256 royaltyPerc) external onlyOwner {
require(_tokenDetails[tokenId].created == false, "Token ID already exists");
require(royaltyRecipient != address(0), "Royalty recipient can't be the 0 address");
require(royaltyPerc < 10000, "Royalty percent can't be more than 10,000");
_tokenDetails[tokenId].created = true;
_tokenDetails[tokenId].availableSupply = supply;
_tokenDetails[tokenId].mintStatus = mintStatus;
_tokenDetails[tokenId].price = price;
_tokenDetails[tokenId].uri = uri_;
_tokenDetails[tokenId].merkleRoot = merkleRoot;
_royaltyAddr[tokenId] = royaltyRecipient;
_royaltyPerc[tokenId] = royaltyPerc;
}
/**
* @notice function to set available supply for a certain token
* @dev requires owner of contract
* @param tokenId is the token id
* @param supply is the new available supply for that token
*/
function setTokenSupply(uint256 tokenId, uint64 supply) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
_tokenDetails[tokenId].availableSupply = supply;
}
/**
* @notice sets the URI for individual tokens
* @dev requires owner
* @dev emits URI event per the ERC 1155 standard
* @param newURI is the base URI set for each token
* @param tokenId is the token id
*/
function setURI(uint256 tokenId, string memory newURI) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
_tokenDetails[tokenId].uri = newURI;
emit URI(newURI, tokenId);
}
/**
* @notice set token mint status
* @dev requires owner
* @param tokenId is the token id
* @param status is the desired status
*/
function setMintStatus(uint256 tokenId, bool status) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
_tokenDetails[tokenId].mintStatus = status;
}
/**
* @notice set token price
* @dev requires owner
* @param tokenId is the token id
* @param price is the new price
*/
function setTokenPrice(uint256 tokenId, uint256 price) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
_tokenDetails[tokenId].price = price;
}
/**
* @notice set token merkle root
* @dev requires owner
* @param tokenId is the token id
* @param root is the new merkle root
*/
function setMerkleRoot(uint256 tokenId, bytes32 root) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
_tokenDetails[tokenId].merkleRoot = root;
}
/**
* @notice function to set the admin address on the contract
* @dev requires owner of the contract
* @param newAdmin is the new admin address
*/
function setNewAdmin(address newAdmin) external onlyOwner {
require(newAdmin != address(0), "New admin cannot be the zero address");
adminAddress = newAdmin;
}
/**
* @notice function to set the payout address
* @dev requires owner of the contract
* @param payoutAddr is the new payout address
*/
function setPayoutAddress(address payoutAddr) external onlyOwner {
require(payoutAddr != address(0), "Payout address cannot be the zero address");
payoutAddress = payable(payoutAddr);
}
/**
* @notice function to change the royalty recipient
* @dev requires owner
* @dev this is useful if an account gets compromised or anything like that
* @param tokenId is the token id to assign this address to
* @param newRecipient is the new royalty recipient
*/
function setRoyaltyRecipient(uint256 tokenId, address newRecipient) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
require(newRecipient != address(0), "New recipient is the zero address");
_royaltyAddr[tokenId] = newRecipient;
}
/**
* @notice function to change the royalty percentage
* @dev requires owner
* @dev this is useful if the amount was set improperly at contract creation.
* @param tokenId is the token id
* @param newPerc is the new royalty percentage, in basis points (out of 10,000)
*/
function setRoyaltyPercentage(uint256 tokenId, uint256 newPerc) external onlyOwner {
require(_tokenDetails[tokenId].created, "Token ID not valid");
require(newPerc < 10000, "New percentage must be less than 10,0000");
_royaltyPerc[tokenId] = newPerc;
}
/**
* @notice function for batch minting the token to many addresses
* @dev requires owner or admin
* @param tokenId is the token id to airdrop
* @param addresses is an array of addresses to mint to
*/
function airdrop(uint256 tokenId, address[] calldata addresses) external isAdminOrOwner {
require(_tokenDetails[tokenId].created, "Token not created");
require(_tokenDetails[tokenId].availableSupply >= addresses.length, "Not enough token supply available");
_tokenDetails[tokenId].availableSupply -= uint64(addresses.length);
for (uint256 i; i < addresses.length; i++) {
_mint(addresses[i], tokenId, 1, "");
}
}
/**
* @notice function for users to mint
* @dev requires payment
* @param tokenId is the token id to mint
* @param merkleProof is the has for merkle proof verification
*/
function mint(uint256 tokenId, bytes32[] calldata merkleProof) external payable {
TokenDetails storage token = _tokenDetails[tokenId];
require(token.availableSupply > 0, "Not enough token supply available");
require(token.mintStatus == true, "Mint not open");
require(msg.value >= token.price, "Not enough ether attached to the transaction");
require(token.hasMinted[msg.sender] == false, "Sender has already minted");
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(merkleProof, token.merkleRoot, leaf), "Not on allowlist");
token.hasMinted[msg.sender] = true;
token.availableSupply --;
_mint(msg.sender, tokenId, 1, "");
}
/**
* @notice function to withdraw ether from the contract
* @dev requires owner
*/
function withdrawEther() external onlyOwner {
payoutAddress.transfer(address(this).balance);
}
/**
* @notice function to return available token supply
* @dev does not throw for non-existent tokens
* @param tokenId is the token id
* @return uint64 representing available supply
*/
function getTokenSupply(uint256 tokenId) external view returns(uint64) {
return _tokenDetails[tokenId].availableSupply;
}
/**
* @notice function to see if an address has minted a certain token
* @dev does not throw for non-existent tokens
* @param tokenId is the token id
* @param addr is the address to check
* @return boolean indicating status
*/
function getHasMinted(uint256 tokenId, address addr) external view returns (bool) {
return _tokenDetails[tokenId].hasMinted[addr];
}
/**
* @notice function to see the mint status for a token
* @dev does not throw for non-existent tokens
* @param tokenId is the token id
* @return boolean indicating mint status
*/
function getMintStatus(uint256 tokenId) external view returns (bool) {
return _tokenDetails[tokenId].mintStatus;
}
/**
* @notice function to see the price for a token
* @dev does not throw for non-existent tokens
* @param tokenId is the token id
* @return uint256 with price in Wei
*/
function getTokenPrice(uint256 tokenId) external view returns (uint256) {
return _tokenDetails[tokenId].price;
}
/**
* @notice function to see the merkle root for a token
* @dev does not throw for non-existent tokens
* @param tokenId is the token id
* @return bytes32 with merkle root
*/
function getMerkleRoot(uint256 tokenId) external view returns (bytes32) {
return _tokenDetails[tokenId].merkleRoot;
}
/**
* @notice overrides supportsInterface function
* @param interfaceId is supplied from anyone/contract calling this function, as defined in ERC 165
* @return a boolean saying if this contract supports the interface or not
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155, EIP2981MultiToken) returns (bool) {
return super.supportsInterface(interfaceId);
}
/**
* @notice function to return uri for a specific token type
* @param tokenId is the uint256 representation of a token ID
* @return string representing the uri for the token id
*/
function uri(uint256 tokenId) public view override returns (string memory) {
return _tokenDetails[tokenId].uri;
}
}
// SPDX-License-Identifier: MIT
/**
* @title EIP 2981 base contract
* @author Transient Labs
* @notice contract implementation of EIP 2981
*/
/*
___ __ __ ______ _ __ __ __
/ _ \___ _ _____ _______ ___/ / / / __ __ /_ __/______ ____ ___ (_)__ ___ / /_ / / ___ _/ / ___
/ ___/ _ \ |/|/ / -_) __/ -_) _ / / _ \/ // / / / / __/ _ `/ _ \(_-</ / -_) _ \/ __/ / /__/ _ `/ _ \(_-<
/_/ \___/__,__/\__/_/ \__/\_,_/ /_.__/\_, / /_/ /_/ \_,_/_//_/___/_/\__/_//_/\__/ /____/\_,_/_.__/___/
/___/
*/
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
import "./IEIP2981.sol";
contract EIP2981MultiToken is IEIP2981, ERC165 {
mapping(uint256 => address) internal _royaltyAddr;
mapping(uint256 => uint256) internal _royaltyPerc; // percentage in basis (out of 10,000)
/**
* @notice override ERC 165 implementation of this function
* @dev if using this contract with another contract that suppports ERC 265, will have to override in the inheriting contract
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) returns (bool) {
return interfaceId == type(IEIP2981).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @notice EIP 2981 royalty support
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount) {
require(_royaltyAddr[_tokenId] != address(0), "Royalty recipient can't be the 0 address");
return (_royaltyAddr[_tokenId], _royaltyPerc[_tokenId] * _salePrice / 10000);
}
}
// 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 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
///
/// @dev Interface for the NFT Royalty Standard
///
interface IEIP2981 {
/// ERC165 bytes to add to interface array - set in parent contract
/// implementing this standard
///
/// bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
/// @notice Called with the sale price to determine how much royalty
// is owed and to whom.
/// @param _tokenId - the NFT asset queried for royalty information
/// @param _salePrice - the sale price of the NFT asset specified by _tokenId
/// @return receiver - address of who should be sent the royalty payment
/// @return royaltyAmount - the royalty payment amount for _salePrice
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver,uint256 royaltyAmount);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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/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/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts 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);
}
|
* @notice function to see if an address has minted a certain token @dev does not throw for non-existent tokens @param tokenId is the token id @param addr is the address to check @return boolean indicating status/
|
function getHasMinted(uint256 tokenId, address addr) external view returns (bool) {
return _tokenDetails[tokenId].hasMinted[addr];
}
| 6,941,840 |
[
1,
915,
358,
2621,
309,
392,
1758,
711,
312,
474,
329,
279,
8626,
1147,
565,
1552,
486,
604,
364,
1661,
17,
19041,
2430,
565,
1147,
548,
353,
326,
1147,
612,
565,
3091,
353,
326,
1758,
358,
866,
282,
327,
1250,
11193,
1267,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
336,
5582,
49,
474,
329,
12,
11890,
5034,
1147,
548,
16,
1758,
3091,
13,
3903,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
389,
2316,
3790,
63,
2316,
548,
8009,
5332,
49,
474,
329,
63,
4793,
15533,
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/0xE065ff6A26F286DDb0E823920CAAeCD1fCD57bA1/sources/contracts/Hypervisor.sol
|
@title Hypervisor @notice A Uniswap V2-like interface with fungible liquidity to Uniswap V3 which allows for arbitrary liquidity provision: one-sided, lop-sided, and balanced @param _pool Uniswap V3 pool for which liquidity is managed @param _owner Owner of the Hypervisor
|
contract Hypervisor is IVault, IUniswapV3MintCallback, IUniswapV3SwapCallback, ERC20Permit {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using SignedSafeMath for int256;
IUniswapV3Pool public pool;
IERC20 public token0;
IERC20 public token1;
uint24 public fee;
int24 public tickSpacing;
int24 public baseLower;
int24 public baseUpper;
int24 public limitLower;
int24 public limitUpper;
address public owner;
uint256 public deposit0Max;
uint256 public deposit1Max;
uint256 public maxTotalSupply;
mapping(address => bool) public list;
bool public whitelisted;
bool public directDeposit;
uint256 public constant PRECISION = 1e36;
constructor(
address _pool,
address _owner,
string memory name,
string memory symbol
) ERC20Permit(name) ERC20(name, symbol) {
pool = IUniswapV3Pool(_pool);
token0 = IERC20(pool.token0());
token1 = IERC20(pool.token1());
fee = pool.fee();
tickSpacing = pool.tickSpacing();
owner = _owner;
deposit0Max = uint256(-1);
deposit1Max = uint256(-1);
whitelisted = false;
}
function deposit(
uint256 deposit0,
uint256 deposit1,
address to
) external override returns (uint256 shares) {
return deposit(deposit0, deposit1, to, msg.sender);
}
function deposit(
uint256 deposit0,
uint256 deposit1,
address to,
address from
) public returns (uint256 shares) {
require(deposit0 > 0 || deposit1 > 0, "deposits must be nonzero");
require(deposit0 <= deposit0Max && deposit1 <= deposit1Max, "deposits must be less than maximum amounts");
require(to != address(0) && to != address(this), "to");
require(!whitelisted || list[from], "must be on the list");
(uint128 baseLiquidity,,) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity,,) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(currentTick());
uint256 price = FullMath.mulDiv(uint256(sqrtPrice).mul(uint256(sqrtPrice)), PRECISION, 2**(96 * 2));
(uint256 pool0, uint256 pool1) = getTotalAmounts();
uint256 deposit0PricedInToken1 = deposit0.mul(price).div(PRECISION);
shares = deposit1.add(deposit0PricedInToken1);
if (deposit0 > 0) {
token0.safeTransferFrom(from, address(this), deposit0);
}
if (deposit1 > 0) {
token1.safeTransferFrom(from, address(this), deposit1);
}
if (totalSupply() != 0) {
uint256 pool0PricedInToken1 = pool0.mul(price).div(PRECISION);
shares = shares.mul(totalSupply()).div(pool0PricedInToken1.add(pool1));
if (directDeposit) {
baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
}
_mint(to, shares);
emit Deposit(from, to, shares, deposit0, deposit1);
}
function deposit(
uint256 deposit0,
uint256 deposit1,
address to,
address from
) public returns (uint256 shares) {
require(deposit0 > 0 || deposit1 > 0, "deposits must be nonzero");
require(deposit0 <= deposit0Max && deposit1 <= deposit1Max, "deposits must be less than maximum amounts");
require(to != address(0) && to != address(this), "to");
require(!whitelisted || list[from], "must be on the list");
(uint128 baseLiquidity,,) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity,,) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(currentTick());
uint256 price = FullMath.mulDiv(uint256(sqrtPrice).mul(uint256(sqrtPrice)), PRECISION, 2**(96 * 2));
(uint256 pool0, uint256 pool1) = getTotalAmounts();
uint256 deposit0PricedInToken1 = deposit0.mul(price).div(PRECISION);
shares = deposit1.add(deposit0PricedInToken1);
if (deposit0 > 0) {
token0.safeTransferFrom(from, address(this), deposit0);
}
if (deposit1 > 0) {
token1.safeTransferFrom(from, address(this), deposit1);
}
if (totalSupply() != 0) {
uint256 pool0PricedInToken1 = pool0.mul(price).div(PRECISION);
shares = shares.mul(totalSupply()).div(pool0PricedInToken1.add(pool1));
if (directDeposit) {
baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
}
_mint(to, shares);
emit Deposit(from, to, shares, deposit0, deposit1);
}
function deposit(
uint256 deposit0,
uint256 deposit1,
address to,
address from
) public returns (uint256 shares) {
require(deposit0 > 0 || deposit1 > 0, "deposits must be nonzero");
require(deposit0 <= deposit0Max && deposit1 <= deposit1Max, "deposits must be less than maximum amounts");
require(to != address(0) && to != address(this), "to");
require(!whitelisted || list[from], "must be on the list");
(uint128 baseLiquidity,,) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity,,) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(currentTick());
uint256 price = FullMath.mulDiv(uint256(sqrtPrice).mul(uint256(sqrtPrice)), PRECISION, 2**(96 * 2));
(uint256 pool0, uint256 pool1) = getTotalAmounts();
uint256 deposit0PricedInToken1 = deposit0.mul(price).div(PRECISION);
shares = deposit1.add(deposit0PricedInToken1);
if (deposit0 > 0) {
token0.safeTransferFrom(from, address(this), deposit0);
}
if (deposit1 > 0) {
token1.safeTransferFrom(from, address(this), deposit1);
}
if (totalSupply() != 0) {
uint256 pool0PricedInToken1 = pool0.mul(price).div(PRECISION);
shares = shares.mul(totalSupply()).div(pool0PricedInToken1.add(pool1));
if (directDeposit) {
baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
}
_mint(to, shares);
emit Deposit(from, to, shares, deposit0, deposit1);
}
function deposit(
uint256 deposit0,
uint256 deposit1,
address to,
address from
) public returns (uint256 shares) {
require(deposit0 > 0 || deposit1 > 0, "deposits must be nonzero");
require(deposit0 <= deposit0Max && deposit1 <= deposit1Max, "deposits must be less than maximum amounts");
require(to != address(0) && to != address(this), "to");
require(!whitelisted || list[from], "must be on the list");
(uint128 baseLiquidity,,) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity,,) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(currentTick());
uint256 price = FullMath.mulDiv(uint256(sqrtPrice).mul(uint256(sqrtPrice)), PRECISION, 2**(96 * 2));
(uint256 pool0, uint256 pool1) = getTotalAmounts();
uint256 deposit0PricedInToken1 = deposit0.mul(price).div(PRECISION);
shares = deposit1.add(deposit0PricedInToken1);
if (deposit0 > 0) {
token0.safeTransferFrom(from, address(this), deposit0);
}
if (deposit1 > 0) {
token1.safeTransferFrom(from, address(this), deposit1);
}
if (totalSupply() != 0) {
uint256 pool0PricedInToken1 = pool0.mul(price).div(PRECISION);
shares = shares.mul(totalSupply()).div(pool0PricedInToken1.add(pool1));
if (directDeposit) {
baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
}
_mint(to, shares);
emit Deposit(from, to, shares, deposit0, deposit1);
}
function deposit(
uint256 deposit0,
uint256 deposit1,
address to,
address from
) public returns (uint256 shares) {
require(deposit0 > 0 || deposit1 > 0, "deposits must be nonzero");
require(deposit0 <= deposit0Max && deposit1 <= deposit1Max, "deposits must be less than maximum amounts");
require(to != address(0) && to != address(this), "to");
require(!whitelisted || list[from], "must be on the list");
(uint128 baseLiquidity,,) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity,,) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(currentTick());
uint256 price = FullMath.mulDiv(uint256(sqrtPrice).mul(uint256(sqrtPrice)), PRECISION, 2**(96 * 2));
(uint256 pool0, uint256 pool1) = getTotalAmounts();
uint256 deposit0PricedInToken1 = deposit0.mul(price).div(PRECISION);
shares = deposit1.add(deposit0PricedInToken1);
if (deposit0 > 0) {
token0.safeTransferFrom(from, address(this), deposit0);
}
if (deposit1 > 0) {
token1.safeTransferFrom(from, address(this), deposit1);
}
if (totalSupply() != 0) {
uint256 pool0PricedInToken1 = pool0.mul(price).div(PRECISION);
shares = shares.mul(totalSupply()).div(pool0PricedInToken1.add(pool1));
if (directDeposit) {
baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
}
_mint(to, shares);
emit Deposit(from, to, shares, deposit0, deposit1);
}
function deposit(
uint256 deposit0,
uint256 deposit1,
address to,
address from
) public returns (uint256 shares) {
require(deposit0 > 0 || deposit1 > 0, "deposits must be nonzero");
require(deposit0 <= deposit0Max && deposit1 <= deposit1Max, "deposits must be less than maximum amounts");
require(to != address(0) && to != address(this), "to");
require(!whitelisted || list[from], "must be on the list");
(uint128 baseLiquidity,,) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity,,) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(currentTick());
uint256 price = FullMath.mulDiv(uint256(sqrtPrice).mul(uint256(sqrtPrice)), PRECISION, 2**(96 * 2));
(uint256 pool0, uint256 pool1) = getTotalAmounts();
uint256 deposit0PricedInToken1 = deposit0.mul(price).div(PRECISION);
shares = deposit1.add(deposit0PricedInToken1);
if (deposit0 > 0) {
token0.safeTransferFrom(from, address(this), deposit0);
}
if (deposit1 > 0) {
token1.safeTransferFrom(from, address(this), deposit1);
}
if (totalSupply() != 0) {
uint256 pool0PricedInToken1 = pool0.mul(price).div(PRECISION);
shares = shares.mul(totalSupply()).div(pool0PricedInToken1.add(pool1));
if (directDeposit) {
baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
}
_mint(to, shares);
emit Deposit(from, to, shares, deposit0, deposit1);
}
function deposit(
uint256 deposit0,
uint256 deposit1,
address to,
address from
) public returns (uint256 shares) {
require(deposit0 > 0 || deposit1 > 0, "deposits must be nonzero");
require(deposit0 <= deposit0Max && deposit1 <= deposit1Max, "deposits must be less than maximum amounts");
require(to != address(0) && to != address(this), "to");
require(!whitelisted || list[from], "must be on the list");
(uint128 baseLiquidity,,) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity,,) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
uint160 sqrtPrice = TickMath.getSqrtRatioAtTick(currentTick());
uint256 price = FullMath.mulDiv(uint256(sqrtPrice).mul(uint256(sqrtPrice)), PRECISION, 2**(96 * 2));
(uint256 pool0, uint256 pool1) = getTotalAmounts();
uint256 deposit0PricedInToken1 = deposit0.mul(price).div(PRECISION);
shares = deposit1.add(deposit0PricedInToken1);
if (deposit0 > 0) {
token0.safeTransferFrom(from, address(this), deposit0);
}
if (deposit1 > 0) {
token1.safeTransferFrom(from, address(this), deposit1);
}
if (totalSupply() != 0) {
uint256 pool0PricedInToken1 = pool0.mul(price).div(PRECISION);
shares = shares.mul(totalSupply()).div(pool0PricedInToken1.add(pool1));
if (directDeposit) {
baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
}
_mint(to, shares);
emit Deposit(from, to, shares, deposit0, deposit1);
}
require(maxTotalSupply == 0 || totalSupply() <= maxTotalSupply, "maxTotalSupply");
function withdraw(
uint256 shares,
address to,
address from
) external override returns (uint256 amount0, uint256 amount1) {
require(shares > 0, "shares");
require(to != address(0), "to");
(uint256 base0, uint256 base1) = _burnLiquidity(
baseLower,
baseUpper,
_liquidityForShares(baseLower, baseUpper, shares),
to,
false
);
(uint256 limit0, uint256 limit1) = _burnLiquidity(
limitLower,
limitUpper,
_liquidityForShares(limitLower, limitUpper, shares),
to,
false
);
uint256 totalSupply = totalSupply();
uint256 unusedAmount0 = token0.balanceOf(address(this)).mul(shares).div(totalSupply);
uint256 unusedAmount1 = token1.balanceOf(address(this)).mul(shares).div(totalSupply);
if (unusedAmount0 > 0) token0.safeTransfer(to, unusedAmount0);
if (unusedAmount1 > 0) token1.safeTransfer(to, unusedAmount1);
amount0 = base0.add(limit0).add(unusedAmount0);
amount1 = base1.add(limit1).add(unusedAmount1);
require(
from == msg.sender || IUniversalVault(from).owner() == msg.sender,
"Sender must own the tokens"
);
_burn(from, shares);
emit Withdraw(from, to, shares, amount0, amount1);
}
function rebalance(
int24 _baseLower,
int24 _baseUpper,
int24 _limitLower,
int24 _limitUpper,
address feeRecipient,
int256 swapQuantity
) external override onlyOwner {
require(
_baseLower < _baseUpper &&
_baseLower % tickSpacing == 0 &&
_baseUpper % tickSpacing == 0,
"base position invalid"
);
require(
_limitLower < _limitUpper &&
_limitLower % tickSpacing == 0 &&
_limitUpper % tickSpacing == 0,
"limit position invalid"
);
(uint128 baseLiquidity, , ) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity, , ) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
(, uint256 feesBase0, uint256 feesBase1) = _position(limitLower, limitUpper);
uint256 fees0 = feesBase0.add(feesLimit0);
uint256 fees1 = feesBase1.add(feesLimit1);
_burnLiquidity(baseLower, baseUpper, baseLiquidity, address(this), true);
_burnLiquidity(limitLower, limitUpper, limitLiquidity, address(this), true);
if (fees1 > 0) token1.safeTransfer(feeRecipient, fees1.div(10));
emit Rebalance(
currentTick(),
token0.balanceOf(address(this)),
token1.balanceOf(address(this)),
fees0,
fees1,
totalSupply()
);
if (swapQuantity != 0) {
pool.swap(
address(this),
swapQuantity > 0,
swapQuantity > 0 ? swapQuantity : -swapQuantity,
swapQuantity > 0 ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1,
abi.encode(address(this))
);
}
baseLower = _baseLower;
baseUpper = _baseUpper;
baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
limitLower = _limitLower;
limitUpper = _limitUpper;
limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
function rebalance(
int24 _baseLower,
int24 _baseUpper,
int24 _limitLower,
int24 _limitUpper,
address feeRecipient,
int256 swapQuantity
) external override onlyOwner {
require(
_baseLower < _baseUpper &&
_baseLower % tickSpacing == 0 &&
_baseUpper % tickSpacing == 0,
"base position invalid"
);
require(
_limitLower < _limitUpper &&
_limitLower % tickSpacing == 0 &&
_limitUpper % tickSpacing == 0,
"limit position invalid"
);
(uint128 baseLiquidity, , ) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity, , ) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
(, uint256 feesBase0, uint256 feesBase1) = _position(limitLower, limitUpper);
uint256 fees0 = feesBase0.add(feesLimit0);
uint256 fees1 = feesBase1.add(feesLimit1);
_burnLiquidity(baseLower, baseUpper, baseLiquidity, address(this), true);
_burnLiquidity(limitLower, limitUpper, limitLiquidity, address(this), true);
if (fees1 > 0) token1.safeTransfer(feeRecipient, fees1.div(10));
emit Rebalance(
currentTick(),
token0.balanceOf(address(this)),
token1.balanceOf(address(this)),
fees0,
fees1,
totalSupply()
);
if (swapQuantity != 0) {
pool.swap(
address(this),
swapQuantity > 0,
swapQuantity > 0 ? swapQuantity : -swapQuantity,
swapQuantity > 0 ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1,
abi.encode(address(this))
);
}
baseLower = _baseLower;
baseUpper = _baseUpper;
baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
limitLower = _limitLower;
limitUpper = _limitUpper;
limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
function rebalance(
int24 _baseLower,
int24 _baseUpper,
int24 _limitLower,
int24 _limitUpper,
address feeRecipient,
int256 swapQuantity
) external override onlyOwner {
require(
_baseLower < _baseUpper &&
_baseLower % tickSpacing == 0 &&
_baseUpper % tickSpacing == 0,
"base position invalid"
);
require(
_limitLower < _limitUpper &&
_limitLower % tickSpacing == 0 &&
_limitUpper % tickSpacing == 0,
"limit position invalid"
);
(uint128 baseLiquidity, , ) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity, , ) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
(, uint256 feesBase0, uint256 feesBase1) = _position(limitLower, limitUpper);
uint256 fees0 = feesBase0.add(feesLimit0);
uint256 fees1 = feesBase1.add(feesLimit1);
_burnLiquidity(baseLower, baseUpper, baseLiquidity, address(this), true);
_burnLiquidity(limitLower, limitUpper, limitLiquidity, address(this), true);
if (fees1 > 0) token1.safeTransfer(feeRecipient, fees1.div(10));
emit Rebalance(
currentTick(),
token0.balanceOf(address(this)),
token1.balanceOf(address(this)),
fees0,
fees1,
totalSupply()
);
if (swapQuantity != 0) {
pool.swap(
address(this),
swapQuantity > 0,
swapQuantity > 0 ? swapQuantity : -swapQuantity,
swapQuantity > 0 ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1,
abi.encode(address(this))
);
}
baseLower = _baseLower;
baseUpper = _baseUpper;
baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
limitLower = _limitLower;
limitUpper = _limitUpper;
limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
(, uint256 feesLimit0, uint256 feesLimit1) = _position(baseLower, baseUpper);
if (fees0 > 0) token0.safeTransfer(feeRecipient, fees0.div(10));
function rebalance(
int24 _baseLower,
int24 _baseUpper,
int24 _limitLower,
int24 _limitUpper,
address feeRecipient,
int256 swapQuantity
) external override onlyOwner {
require(
_baseLower < _baseUpper &&
_baseLower % tickSpacing == 0 &&
_baseUpper % tickSpacing == 0,
"base position invalid"
);
require(
_limitLower < _limitUpper &&
_limitLower % tickSpacing == 0 &&
_limitUpper % tickSpacing == 0,
"limit position invalid"
);
(uint128 baseLiquidity, , ) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity, , ) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
(, uint256 feesBase0, uint256 feesBase1) = _position(limitLower, limitUpper);
uint256 fees0 = feesBase0.add(feesLimit0);
uint256 fees1 = feesBase1.add(feesLimit1);
_burnLiquidity(baseLower, baseUpper, baseLiquidity, address(this), true);
_burnLiquidity(limitLower, limitUpper, limitLiquidity, address(this), true);
if (fees1 > 0) token1.safeTransfer(feeRecipient, fees1.div(10));
emit Rebalance(
currentTick(),
token0.balanceOf(address(this)),
token1.balanceOf(address(this)),
fees0,
fees1,
totalSupply()
);
if (swapQuantity != 0) {
pool.swap(
address(this),
swapQuantity > 0,
swapQuantity > 0 ? swapQuantity : -swapQuantity,
swapQuantity > 0 ? TickMath.MIN_SQRT_RATIO + 1 : TickMath.MAX_SQRT_RATIO - 1,
abi.encode(address(this))
);
}
baseLower = _baseLower;
baseUpper = _baseUpper;
baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
limitLower = _limitLower;
limitUpper = _limitUpper;
limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
token0.balanceOf(address(this)),
token1.balanceOf(address(this))
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
function pendingFees() external onlyOwner returns (uint256 fees0, uint256 fees1) {
(uint128 baseLiquidity, , ) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity, , ) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
(, uint256 feesBase0, uint256 feesBase1) = _position(limitLower, limitUpper);
fees0 = feesBase0.add(feesLimit0);
fees1 = feesBase1.add(feesLimit1);
}
function pendingFees() external onlyOwner returns (uint256 fees0, uint256 fees1) {
(uint128 baseLiquidity, , ) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity, , ) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
(, uint256 feesBase0, uint256 feesBase1) = _position(limitLower, limitUpper);
fees0 = feesBase0.add(feesLimit0);
fees1 = feesBase1.add(feesLimit1);
}
function pendingFees() external onlyOwner returns (uint256 fees0, uint256 fees1) {
(uint128 baseLiquidity, , ) = _position(baseLower, baseUpper);
if (baseLiquidity > 0) {
pool.burn(baseLower, baseUpper, 0);
}
(uint128 limitLiquidity, , ) = _position(limitLower, limitUpper);
if (limitLiquidity > 0) {
pool.burn(limitLower, limitUpper, 0);
}
(, uint256 feesBase0, uint256 feesBase1) = _position(limitLower, limitUpper);
fees0 = feesBase0.add(feesLimit0);
fees1 = feesBase1.add(feesLimit1);
}
(, uint256 feesLimit0, uint256 feesLimit1) = _position(baseLower, baseUpper);
function addBaseLiquidity(uint256 amount0, uint256 amount1) external onlyOwner {
uint128 baseLiquidity = _liquidityForAmounts(
baseLower,
baseUpper,
amount0 == 0 && amount1 == 0 ? token0.balanceOf(address(this)) : amount0,
amount0 == 0 && amount1 == 0 ? token1.balanceOf(address(this)) : amount1
);
_mintLiquidity(baseLower, baseUpper, baseLiquidity, address(this));
}
function addLimitLiquidity(uint256 amount0, uint256 amount1) external onlyOwner {
uint128 limitLiquidity = _liquidityForAmounts(
limitLower,
limitUpper,
amount0 == 0 && amount1 == 0 ? token0.balanceOf(address(this)) : amount0,
amount0 == 0 && amount1 == 0 ? token1.balanceOf(address(this)) : amount1
);
_mintLiquidity(limitLower, limitUpper, limitLiquidity, address(this));
}
function _mintLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address payer
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
(amount0, amount1) = pool.mint(
address(this),
tickLower,
tickUpper,
liquidity,
abi.encode(payer)
);
}
}
function _mintLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address payer
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
(amount0, amount1) = pool.mint(
address(this),
tickLower,
tickUpper,
liquidity,
abi.encode(payer)
);
}
}
function _burnLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address to,
bool collectAll
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
(uint256 owed0, uint256 owed1) = pool.burn(tickLower, tickUpper, liquidity);
uint128 collect0 = collectAll ? type(uint128).max : _uint128Safe(owed0);
uint128 collect1 = collectAll ? type(uint128).max : _uint128Safe(owed1);
if (collect0 > 0 || collect1 > 0) {
(amount0, amount1) = pool.collect(to, tickLower, tickUpper, collect0, collect1);
}
}
}
function _burnLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address to,
bool collectAll
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
(uint256 owed0, uint256 owed1) = pool.burn(tickLower, tickUpper, liquidity);
uint128 collect0 = collectAll ? type(uint128).max : _uint128Safe(owed0);
uint128 collect1 = collectAll ? type(uint128).max : _uint128Safe(owed1);
if (collect0 > 0 || collect1 > 0) {
(amount0, amount1) = pool.collect(to, tickLower, tickUpper, collect0, collect1);
}
}
}
function _burnLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
address to,
bool collectAll
) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity > 0) {
(uint256 owed0, uint256 owed1) = pool.burn(tickLower, tickUpper, liquidity);
uint128 collect0 = collectAll ? type(uint128).max : _uint128Safe(owed0);
uint128 collect1 = collectAll ? type(uint128).max : _uint128Safe(owed1);
if (collect0 > 0 || collect1 > 0) {
(amount0, amount1) = pool.collect(to, tickLower, tickUpper, collect0, collect1);
}
}
}
function _liquidityForShares(
int24 tickLower,
int24 tickUpper,
uint256 shares
) internal view returns (uint128) {
(uint128 position, , ) = _position(tickLower, tickUpper);
return _uint128Safe(uint256(position).mul(shares).div(totalSupply()));
}
function _position(int24 tickLower, int24 tickUpper)
internal
view
returns (
uint128 liquidity,
uint128 tokensOwed0,
uint128 tokensOwed1
)
{
bytes32 positionKey = keccak256(abi.encodePacked(address(this), tickLower, tickUpper));
(liquidity, , , tokensOwed0, tokensOwed1) = pool.positions(positionKey);
}
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata data
) external override {
require(msg.sender == address(pool));
address payer = abi.decode(data, (address));
if (payer == address(this)) {
if (amount0 > 0) token0.safeTransfer(msg.sender, amount0);
if (amount1 > 0) token1.safeTransfer(msg.sender, amount1);
if (amount0 > 0) token0.safeTransferFrom(payer, msg.sender, amount0);
if (amount1 > 0) token1.safeTransferFrom(payer, msg.sender, amount1);
}
}
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata data
) external override {
require(msg.sender == address(pool));
address payer = abi.decode(data, (address));
if (payer == address(this)) {
if (amount0 > 0) token0.safeTransfer(msg.sender, amount0);
if (amount1 > 0) token1.safeTransfer(msg.sender, amount1);
if (amount0 > 0) token0.safeTransferFrom(payer, msg.sender, amount0);
if (amount1 > 0) token1.safeTransferFrom(payer, msg.sender, amount1);
}
}
} else {
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external override {
require(msg.sender == address(pool));
address payer = abi.decode(data, (address));
if (amount0Delta > 0) {
if (payer == address(this)) {
token0.safeTransfer(msg.sender, uint256(amount0Delta));
token0.safeTransferFrom(payer, msg.sender, uint256(amount0Delta));
}
if (payer == address(this)) {
token1.safeTransfer(msg.sender, uint256(amount1Delta));
token1.safeTransferFrom(payer, msg.sender, uint256(amount1Delta));
}
}
}
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external override {
require(msg.sender == address(pool));
address payer = abi.decode(data, (address));
if (amount0Delta > 0) {
if (payer == address(this)) {
token0.safeTransfer(msg.sender, uint256(amount0Delta));
token0.safeTransferFrom(payer, msg.sender, uint256(amount0Delta));
}
if (payer == address(this)) {
token1.safeTransfer(msg.sender, uint256(amount1Delta));
token1.safeTransferFrom(payer, msg.sender, uint256(amount1Delta));
}
}
}
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external override {
require(msg.sender == address(pool));
address payer = abi.decode(data, (address));
if (amount0Delta > 0) {
if (payer == address(this)) {
token0.safeTransfer(msg.sender, uint256(amount0Delta));
token0.safeTransferFrom(payer, msg.sender, uint256(amount0Delta));
}
if (payer == address(this)) {
token1.safeTransfer(msg.sender, uint256(amount1Delta));
token1.safeTransferFrom(payer, msg.sender, uint256(amount1Delta));
}
}
}
} else {
} else if (amount1Delta > 0) {
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external override {
require(msg.sender == address(pool));
address payer = abi.decode(data, (address));
if (amount0Delta > 0) {
if (payer == address(this)) {
token0.safeTransfer(msg.sender, uint256(amount0Delta));
token0.safeTransferFrom(payer, msg.sender, uint256(amount0Delta));
}
if (payer == address(this)) {
token1.safeTransfer(msg.sender, uint256(amount1Delta));
token1.safeTransferFrom(payer, msg.sender, uint256(amount1Delta));
}
}
}
} else {
function getTotalAmounts() public view override returns (uint256 total0, uint256 total1) {
(, uint256 base0, uint256 base1) = getBasePosition();
(, uint256 limit0, uint256 limit1) = getLimitPosition();
total0 = token0.balanceOf(address(this)).add(base0).add(limit0);
total1 = token1.balanceOf(address(this)).add(base1).add(limit1);
}
function getBasePosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position(
baseLower,
baseUpper
);
(amount0, amount1) = _amountsForLiquidity(baseLower, baseUpper, positionLiquidity);
amount0 = amount0.add(uint256(tokensOwed0));
amount1 = amount1.add(uint256(tokensOwed1));
liquidity = positionLiquidity;
}
function getLimitPosition()
public
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(uint128 positionLiquidity, uint128 tokensOwed0, uint128 tokensOwed1) = _position(
limitLower,
limitUpper
);
(amount0, amount1) = _amountsForLiquidity(limitLower, limitUpper, positionLiquidity);
amount0 = amount0.add(uint256(tokensOwed0));
amount1 = amount1.add(uint256(tokensOwed1));
liquidity = positionLiquidity;
}
function _amountsForLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal view returns (uint256, uint256) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
}
function _liquidityForAmounts(
int24 tickLower,
int24 tickUpper,
uint256 amount0,
uint256 amount1
) internal view returns (uint128) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amount0,
amount1
);
}
function currentTick() public view returns (int24 tick) {
(, tick, , , , , ) = pool.slot0();
}
function _uint128Safe(uint256 x) internal pure returns (uint128) {
assert(x <= type(uint128).max);
return uint128(x);
}
function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyOwner {
maxTotalSupply = _maxTotalSupply;
}
function setDepositMax(uint256 _deposit0Max, uint256 _deposit1Max) external onlyOwner {
deposit0Max = _deposit0Max;
deposit1Max = _deposit1Max;
}
function appendList(address[] memory listed) external onlyOwner {
for (uint8 i; i < listed.length; i++) {
list[listed[i]] = true;
}
}
function appendList(address[] memory listed) external onlyOwner {
for (uint8 i; i < listed.length; i++) {
list[listed[i]] = true;
}
}
function removeListed(address listed) external onlyOwner {
list[listed] = false;
}
function toggleWhitelist() external onlyOwner {
whitelisted = whitelisted ? false : true;
}
function toggleDirectDeposit() external onlyOwner {
directDeposit = directDeposit ? false : true;
}
function transferOwnership(address newOwner) external onlyOwner {
owner = newOwner;
}
modifier onlyOwner {
require(msg.sender == owner, "only owner");
_;
}
}
| 3,978,341 |
[
1,
15996,
10227,
225,
432,
1351,
291,
91,
438,
776,
22,
17,
5625,
1560,
598,
9831,
75,
1523,
4501,
372,
24237,
358,
1351,
291,
91,
438,
776,
23,
1492,
5360,
364,
11078,
4501,
372,
24237,
10595,
30,
1245,
17,
7722,
785,
16,
437,
84,
17,
7722,
785,
16,
471,
11013,
72,
225,
389,
6011,
1351,
291,
91,
438,
776,
23,
2845,
364,
1492,
4501,
372,
24237,
353,
7016,
225,
389,
8443,
16837,
434,
326,
18274,
10227,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
16351,
18274,
10227,
353,
467,
12003,
16,
467,
984,
291,
91,
438,
58,
23,
49,
474,
2428,
16,
467,
984,
291,
91,
438,
58,
23,
12521,
2428,
16,
4232,
39,
3462,
9123,
305,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
16724,
9890,
10477,
364,
509,
5034,
31,
203,
203,
565,
467,
984,
291,
91,
438,
58,
23,
2864,
1071,
2845,
31,
203,
565,
467,
654,
39,
3462,
1071,
1147,
20,
31,
203,
565,
467,
654,
39,
3462,
1071,
1147,
21,
31,
203,
565,
2254,
3247,
1071,
14036,
31,
203,
565,
509,
3247,
1071,
4024,
18006,
31,
203,
203,
565,
509,
3247,
1071,
1026,
4070,
31,
203,
565,
509,
3247,
1071,
1026,
5988,
31,
203,
565,
509,
3247,
1071,
1800,
4070,
31,
203,
565,
509,
3247,
1071,
1800,
5988,
31,
203,
203,
565,
1758,
1071,
3410,
31,
203,
565,
2254,
5034,
1071,
443,
1724,
20,
2747,
31,
203,
565,
2254,
5034,
1071,
443,
1724,
21,
2747,
31,
203,
565,
2254,
5034,
1071,
943,
5269,
3088,
1283,
31,
203,
565,
2874,
12,
2867,
516,
1426,
13,
1071,
666,
31,
203,
565,
1426,
1071,
26944,
31,
203,
565,
1426,
1071,
2657,
758,
1724,
31,
203,
203,
565,
2254,
5034,
1071,
5381,
7071,
26913,
273,
404,
73,
5718,
31,
203,
203,
565,
3885,
12,
203,
3639,
1758,
389,
6011,
16,
203,
3639,
1758,
389,
8443,
16,
203,
3639,
533,
3778,
508,
16,
203,
3639,
533,
3778,
3273,
203,
203,
2
] |
pragma solidity ^0.4.24;
/**
* Libraries
*/
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;
}
}
/**
* Helper contracts
*/
contract Ownable {
address public owner;
address public coowner;
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;
coowner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner || msg.sender == coowner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function setOwner(address newOwner) onlyOwner public {
require(newOwner != address(0));
emit OwnershipTransferred(coowner, newOwner);
coowner = newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract CrowdsaleToken is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 public totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_.sub(balances[address(0)]);
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract Burnable is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function burn(address account, uint256 value) internal {
require(account != address(0));
totalSupply_ = totalSupply_.sub(value);
balances[account] = balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function burnFrom(address account, uint256 value) internal {
allowed[account][msg.sender] = allowed[account][msg.sender].sub(value);
burn(account, value);
}
}
/**
* MSG Token / Crowdsale
*/
contract MSG is Ownable, Pausable, Burnable, CrowdsaleToken {
using SafeMath for uint256;
string name = "MoreStamps Global Token";
string symbol = "MSG";
uint8 decimals = 18;
// Manual kill switch
bool crowdsaleConcluded = false;
// start and end timestamps where investments are allowed (both inclusive)
uint256 public startTime;
uint256 public switchTime;
uint256 public endTime;
// minimum investment
uint256 minimumInvestPreSale = 10E17;
uint256 minimumInvestCrowdSale = 5E17;
// custom bonus amounts
uint256 public preSaleBonus = 15;
uint256 public crowdSaleBonus = 10;
// address where funds are collected
address public wallet;
// how many token units a buyer gets per wei
uint256 public preSaleRate = 1986;
uint256 public crowdSaleRate = 1420;
// how many token per each round
uint256 public preSaleLimit = 20248800E18;
uint256 public crowdSaleLimit = 73933200E18;
// amount of raised in wei
uint256 public weiRaised;
uint256 public tokensSold;
//token allocation addresses
address STRATEGIC_PARTNERS_WALLET = 0x19CFB0E3F83831b726273b81760AE556600785Ec;
// Initial token allocation (40%)
bool tokensAllocated = false;
uint256 public contributors = 0;
mapping(address => uint256) public contributions;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
constructor()
CrowdsaleToken(name, symbol, decimals) public {
totalSupply_ = 156970000E18;
//crowdsale allocation
balances[this] = totalSupply_;
startTime = 1543622400;
switchTime = 1547596800;
endTime = 1550275200;
wallet = msg.sender;
}
// fallback function can be used to buy tokens
function () external whenNotPaused payable {
buyTokens(msg.sender);
}
function envokeTokenAllocation() public onlyOwner {
require(!tokensAllocated);
this.transfer(STRATEGIC_PARTNERS_WALLET, 62788000E18); //40% of totalSupply_
tokensAllocated = true;
}
// low level token purchase function
function buyTokens(address _beneficiary) public whenNotPaused payable returns (uint256) {
require(!hasEnded());
require(_beneficiary != address(0));
require(validPurchase());
require(minimumInvest(msg.value));
address beneficiary = _beneficiary;
uint256 weiAmount = msg.value;
// calculate token amount to be sent
uint256 tokens = getTokenAmount(weiAmount);
// if we run out of tokens
bool isLess = false;
if (!hasEnoughTokensLeft(weiAmount)) {
isLess = true;
uint256 percentOfValue = tokensLeft().mul(100).div(tokens);
require(percentOfValue <= 100);
tokens = tokens.mul(percentOfValue).div(100);
weiAmount = weiAmount.mul(percentOfValue).div(100);
// send back unused ethers
beneficiary.transfer(msg.value.sub(weiAmount));
}
// update raised ETH amount
weiRaised = weiRaised.add(weiAmount);
tokensSold = tokensSold.add(tokens);
//check if new beneficiary
if(contributions[beneficiary] == 0) {
contributors = contributors.add(1);
}
//keep track of purchases per beneficiary;
contributions[beneficiary] = contributions[beneficiary].add(weiAmount);
//transfer purchased tokens
this.transfer(beneficiary, tokens);
//forwardFunds(weiAmount); //manual withdraw
emit TokenPurchase(msg.sender, beneficiary, weiAmount, tokens);
return (tokens);
}
/**
* Editors
*/
function setRate(uint256 _preSaleRate, uint256 _crowdSaleRate) onlyOwner public {
require(_preSaleRate >= 0);
require(_crowdSaleRate >= 0);
preSaleRate = _preSaleRate;
crowdSaleRate = _crowdSaleRate;
}
function setBonus(uint256 _preSaleBonus, uint256 _crowdSaleBonus) onlyOwner public {
require(_preSaleBonus >= 0);
require(_crowdSaleBonus >= 0);
preSaleBonus = _preSaleBonus;
crowdSaleBonus = _crowdSaleBonus;
}
function setMinInvestment(uint256 _investmentPreSale, uint256 _investmentCrowdSale) onlyOwner public {
require(_investmentPreSale > 0);
require(_investmentCrowdSale > 0);
minimumInvestPreSale = _investmentPreSale;
minimumInvestCrowdSale = _investmentCrowdSale;
}
function changeEndTime(uint256 _endTime) onlyOwner public {
require(_endTime > startTime);
endTime = _endTime;
}
function changeSwitchTime(uint256 _switchTime) onlyOwner public {
require(endTime > _switchTime);
require(_switchTime > startTime);
switchTime = _switchTime;
}
function changeStartTime(uint256 _startTime) onlyOwner public {
require(endTime > _startTime);
startTime = _startTime;
}
function setWallet(address _wallet) onlyOwner public {
require(_wallet != address(0));
wallet = _wallet;
}
/**
* End crowdsale manually
*/
function endSale() onlyOwner public {
// close crowdsale
crowdsaleConcluded = true;
}
function resumeSale() onlyOwner public {
// close crowdsale
crowdsaleConcluded = false;
}
/**
* When at risk, evacuate tokens
*/
function evacuateTokens(uint256 _amount) external onlyOwner {
owner.transfer(_amount);
}
function manualTransfer(ERC20 _tokenInstance, uint256 _tokens, address beneficiary) external onlyOwner returns (bool success) {
tokensSold = tokensSold.add(_tokens);
_tokenInstance.transfer(beneficiary, _tokens);
return true;
}
/**
* Calculations
*/
// @return true if crowdsale event has ended
function hasEnded() public view returns (bool) {
return now > endTime || this.balanceOf(this) == 0 || crowdsaleConcluded;
}
function getBaseAmount(uint256 _weiAmount) public view returns (uint256) {
uint256 currentRate = getCurrentRate();
return _weiAmount.mul(currentRate);
}
function getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
uint256 tokens = getBaseAmount(_weiAmount);
uint256 percentage = getCurrentBonus();
if (percentage > 0) {
tokens = tokens.add(tokens.mul(percentage).div(100));
}
assert(tokens > 0);
return (tokens);
}
// send ether to the fund collection wallet
function forwardFunds(uint256 _amount) external onlyOwner {
wallet.transfer(_amount);
}
// @return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool withinPeriod = now >= startTime && now <= endTime;
bool nonZeroPurchase = msg.value != 0;
return withinPeriod && nonZeroPurchase;
}
function minimumInvest(uint256 _weiAmount) internal view returns (bool) {
uint256 currentMinimum = getCurrentMinimum();
if(_weiAmount >= currentMinimum) return true;
return false;
}
function getCurrentMinimum() public view returns (uint256) {
if(now >= startTime && now <= switchTime) return minimumInvestPreSale;
if(now >= switchTime && now <= endTime) return minimumInvestCrowdSale;
return 0;
}
function getCurrentRate() public view returns (uint256) {
if(now >= startTime && now <= switchTime) return preSaleRate;
if(now >= switchTime && now <= endTime) return crowdSaleRate;
return 0;
}
function getCurrentBonus() public view returns (uint256) {
if(now >= startTime && now <= switchTime) return preSaleBonus;
if(now >= switchTime && now <= endTime) return crowdSaleBonus;
return 0;
}
function tokensLeft() public view returns (uint256) {
if(now >= startTime && now <= switchTime) return this.balanceOf(this).sub(crowdSaleLimit);
if(now >= switchTime && now <= endTime) return this.balanceOf(this);
return 0;
}
function hasEnoughTokensLeft(uint256 _weiAmount) public payable returns (bool) {
return tokensLeft().sub(_weiAmount) >= getBaseAmount(_weiAmount);
}
}
|
@return true if crowdsale event has ended
|
function hasEnded() public view returns (bool) {
return now > endTime || this.balanceOf(this) == 0 || crowdsaleConcluded;
}
| 13,135,270 |
[
1,
2463,
638,
309,
276,
492,
2377,
5349,
871,
711,
16926,
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,
711,
28362,
1435,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
2037,
405,
13859,
747,
333,
18,
12296,
951,
12,
2211,
13,
422,
374,
747,
276,
492,
2377,
5349,
442,
7908,
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
] |
./full_match/41/0xAcCD31E942C8B73a7d5040ca20BA4e0d59AE9579/sources/contracts/BunyERC6551Account.sol
|
Instantiate the CalendarOne interface Call the function on the external contract Create a new local event Update local data
|
function createTelosCalendarEvent(
string memory title,
uint256 startTime,
uint256 endTime,
string memory metadataURI,
address[] memory invitees
) public {
require(
msg.sender == owner(),
"Only NFT owner can create calendar events"
);
CalendarOne calendar = CalendarOne(calendarAddress);
calendar.createTelosCalendarEvent(
title,
startTime,
endTime,
metadataURI,
invitees
);
CalendarEvent memory newEvent;
newEvent.title = title;
newEvent.startTime = startTime;
newEvent.endTime = endTime;
newEvent.attendee = address(this);
newEvent.calendar = calendarAddress;
userEvents[msg.sender].push(newEvent);
uint256 eventID = userEvents[msg.sender].length - 1;
totalEvents++;
if (userEvents[msg.sender].length == 1) {
users.push(msg.sender);
eventCreators.push(msg.sender);
}
eventCount[msg.sender]++;
for (uint256 i = 0; i < invitees.length; i++) {
eventInvitations[eventID].push(invitees[i]);
emit UserInvited(eventID, title, invitees[i]);
}
emit NewEventCreated(
title,
msg.sender,
startTime,
endTime,
metadataURI,
block.timestamp
);
}
| 16,376,831 |
[
1,
22438,
326,
5542,
3335,
1560,
3049,
326,
445,
603,
326,
3903,
6835,
1788,
279,
394,
1191,
871,
2315,
1191,
501,
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,
752,
56,
292,
538,
7335,
1133,
12,
203,
3639,
533,
3778,
2077,
16,
203,
3639,
2254,
5034,
8657,
16,
203,
3639,
2254,
5034,
13859,
16,
203,
3639,
533,
3778,
1982,
3098,
16,
203,
3639,
1758,
8526,
3778,
19035,
281,
203,
565,
262,
1071,
288,
203,
3639,
2583,
12,
203,
5411,
1234,
18,
15330,
422,
3410,
9334,
203,
5411,
315,
3386,
423,
4464,
3410,
848,
752,
5686,
2641,
6,
203,
3639,
11272,
203,
203,
3639,
5542,
3335,
5686,
273,
5542,
3335,
12,
11650,
1887,
1769,
203,
203,
3639,
5686,
18,
2640,
56,
292,
538,
7335,
1133,
12,
203,
5411,
2077,
16,
203,
5411,
8657,
16,
203,
5411,
13859,
16,
203,
5411,
1982,
3098,
16,
203,
5411,
19035,
281,
203,
3639,
11272,
203,
203,
3639,
5542,
1133,
3778,
394,
1133,
31,
203,
3639,
394,
1133,
18,
2649,
273,
2077,
31,
203,
3639,
394,
1133,
18,
1937,
950,
273,
8657,
31,
203,
3639,
394,
1133,
18,
409,
950,
273,
13859,
31,
203,
3639,
394,
1133,
18,
10164,
20953,
273,
1758,
12,
2211,
1769,
203,
3639,
394,
1133,
18,
11650,
273,
5686,
1887,
31,
203,
203,
3639,
729,
3783,
63,
3576,
18,
15330,
8009,
6206,
12,
2704,
1133,
1769,
203,
3639,
2254,
5034,
871,
734,
273,
729,
3783,
63,
3576,
18,
15330,
8009,
2469,
300,
404,
31,
203,
3639,
2078,
3783,
9904,
31,
203,
203,
3639,
309,
261,
1355,
3783,
63,
3576,
18,
15330,
8009,
2469,
422,
404,
13,
288,
203,
5411,
3677,
18,
6206,
12,
3576,
18,
15330,
1769,
203,
5411,
871,
1996,
3062,
18,
2
] |
./full_match/43114/0x227Fc8441eFA68E4309D0D5e9A81BCb300711432/sources/contracts/PolyShibs.sol
|
RinkeBy address private ROUTER_ADDRESS = address(0x05AB63BeC9CfC3897a20dE62f5f812de10301FDf); RinkeBy address private XFUND_ADDRESS = address(0x245330351344F9301690D5D8De2A07f5F32e1149); Mainnet address private constant ROUTER_ADDRESS = address(0x9ac9AE20a17779c17b069b48A8788e3455fC6121); Mainnet address private constant XFUND_ADDRESS = address(0x892A6f9dF0147e5f079b0993F486F9acA3c87881);
|
contract MyDataConsumerForLeash is ConsumerBase, Ownable {
uint256 public price;
address NFTAddress;
event GotSomeData(bytes32 requestId, uint256 price);
modifier onlyNFTOrOwner() {
require(msg.sender == NFTAddress || msg.sender == owner(), "Price Can only be fetched by NFT contract or the Owner");
_;
}
constructor(address router, address xfund) ConsumerBase(router, xfund) {
price = 0;
}
function getData(address PROVIDER_ADDRESS, uint256 _fee, bytes32 _data) external onlyNFTOrOwner returns (bytes32) {
return _requestData(PROVIDER_ADDRESS, _fee, _data);
}
function increaseRouterAllowance(uint256 _amount) external onlyOwner {
}
function receiveData(uint256 _price, bytes32 _requestId) internal override {
price = _price;
emit GotSomeData(_requestId, _price);
}
function setNFTContract(address _nftAddress) external onlyOwner {
NFTAddress = _nftAddress;
}
}
| 4,552,679 |
[
1,
54,
754,
73,
858,
1758,
3238,
534,
5069,
654,
67,
15140,
273,
1758,
12,
20,
92,
6260,
2090,
4449,
1919,
39,
29,
39,
74,
39,
23,
6675,
27,
69,
3462,
72,
41,
8898,
74,
25,
74,
28,
2138,
323,
23494,
1611,
16894,
74,
1769,
534,
754,
73,
858,
1758,
3238,
1139,
42,
5240,
67,
15140,
273,
1758,
12,
20,
92,
3247,
25,
3707,
4630,
25,
3437,
6334,
42,
11180,
1611,
8148,
20,
40,
25,
40,
28,
758,
22,
37,
8642,
74,
25,
42,
1578,
73,
2499,
7616,
1769,
12740,
2758,
1758,
3238,
5381,
534,
5069,
654,
67,
15140,
273,
1758,
12,
20,
92,
29,
1077,
29,
16985,
3462,
69,
4033,
4700,
29,
71,
4033,
70,
7677,
29,
70,
8875,
37,
11035,
5482,
73,
5026,
2539,
74,
39,
26,
26009,
1769,
225,
12740,
2758,
1758,
3238,
5381,
1139,
42,
5240,
67,
15140,
273,
1758,
12,
20,
92,
6675,
22,
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,
16351,
8005,
751,
5869,
1290,
1682,
961,
353,
9326,
2171,
16,
14223,
6914,
288,
203,
565,
2254,
5034,
1071,
6205,
31,
203,
565,
1758,
423,
4464,
1887,
31,
203,
203,
565,
871,
19578,
17358,
751,
12,
3890,
1578,
14459,
16,
2254,
5034,
6205,
1769,
203,
203,
203,
203,
203,
203,
565,
9606,
1338,
50,
4464,
1162,
5541,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
423,
4464,
1887,
747,
1234,
18,
15330,
422,
3410,
9334,
315,
5147,
4480,
1338,
506,
12807,
635,
423,
4464,
6835,
578,
326,
16837,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
3885,
12,
2867,
4633,
16,
1758,
16128,
1074,
13,
9326,
2171,
12,
10717,
16,
16128,
1074,
13,
288,
203,
3639,
6205,
273,
374,
31,
203,
565,
289,
203,
203,
565,
445,
4303,
12,
2867,
4629,
20059,
67,
15140,
16,
2254,
5034,
389,
21386,
16,
1731,
1578,
389,
892,
13,
3903,
1338,
50,
4464,
1162,
5541,
1135,
261,
3890,
1578,
13,
288,
203,
203,
377,
203,
203,
203,
203,
3639,
327,
389,
2293,
751,
12,
26413,
67,
15140,
16,
389,
21386,
16,
389,
892,
1769,
203,
565,
289,
203,
203,
565,
445,
10929,
8259,
7009,
1359,
12,
11890,
5034,
389,
8949,
13,
3903,
1338,
5541,
288,
203,
565,
289,
203,
203,
565,
445,
6798,
751,
12,
11890,
5034,
389,
8694,
16,
1731,
1578,
389,
2293,
548,
13,
2713,
3849,
288,
203,
3639,
6205,
273,
389,
8694,
31,
203,
3639,
3626,
19578,
17358,
751,
24899,
2293,
548,
16,
389,
8694,
1769,
203,
565,
289,
203,
2
] |
pragma solidity ^0.4.4;
/**
* @title Queue
*/
contract Queue {
/* State variables */
uint8 size = 5;
uint8 spotsFilled;
uint limit;
address[] queueList;
mapping(address => Submission) submissionList;
struct Submission {
address worker;
bytes32 ipfs_hash;
uint256 time;
}
event limitReached();
function Queue(uint8 _size) {
spotsFilled = 0;
size = _size;
queueList = new address[](size);
}
/* Returns the number of people waiting in line */
function qsize() constant returns(uint8) {
return spotsFilled;
}
/* Returns whether the queue is empty or not */
function empty() constant returns(bool) {
return (spotsFilled == 0);
}
/* Returns whether the queue is full or not */
function isFull() constant returns(bool) {
return (spotsFilled == size);
}
/* Returns the address of the person in the front of the queue */
function getFirstAddress() constant returns(address) {
require(spotsFilled>0);
return queueList[0];
}
/* Returns the address of the person in the front of the queue */
function getFirstSubmission() constant returns(bytes32) {
require(spotsFilled>0);
return submissionList[queueList[0]].ipfs_hash;
}
/* Returns the timestamp of the person in the front of the queue */
function getFirstTime() constant returns(uint256) {
require(spotsFilled>0);
return submissionList[queueList[0]].time;
}
/* Allows `msg.sender` to check their position in the queue */
function checkPlace() constant returns(uint8) {
for (uint8 i = 0; i < spotsFilled; i++) {
if (submissionList[queueList[i]].worker == msg.sender) {
return i + 1;
}
}
return 0;
}
/* Removes the first person in line */
function dequeue() {
if (spotsFilled != 0) {
for (uint i = 1; i < spotsFilled; i++) {
queueList[i - 1] = queueList[i];
}
spotsFilled -= 1;
delete queueList[spotsFilled];
}
}
/* Places Submission in the first available position in queueList */
function enqueue(address addr, bytes32 submission) returns(bool){
if (spotsFilled < size) {
spotsFilled += 1;
queueList[spotsFilled - 1] = addr;
submissionList[addr] = Submission(addr, submission, now);
if (spotsFilled==size) {
limitReached();
}
return true;
} else {
return false;
}
}
}
|
Returns the number of people waiting in line */
|
function qsize() constant returns(uint8) {
return spotsFilled;
}
| 6,438,457 |
[
1,
1356,
326,
1300,
434,
16951,
7336,
316,
980,
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,
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,
202,
915,
1043,
1467,
1435,
5381,
1135,
12,
11890,
28,
13,
288,
203,
202,
202,
2463,
1694,
6968,
29754,
31,
203,
202,
97,
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
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./ERC721A.sol";
import "./CosmicVoucherSigner.sol";
import "./CosmicVoucher.sol";
// Cosmic Cats v1.3
contract CosmicCats is ERC721A, Ownable, CosmicVoucherSigner {
using Address for address;
using SafeMath for uint256;
// Sale Controls
bool public presaleActive = false;
bool public reducedPresaleActive = false;
bool public saleActive = false;
// Mint Price
uint256 public price = 0.04 ether;
uint256 public reducedPrice = 0.03 ether;
uint public MAX_SUPPLY = 8888;
uint public PUBLIC_SUPPLY = 8688;
uint public GIFT_SUPPLY = 200; // 200 Reserved For Collabs, Team & Giveaways
// Create New TokenURI
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
// Team Addresses
address public a1 = 0x65e682bDC103884c3Cb3e82288a9F65a8d80CA54; // Justin
address public a2 = 0xC033fCAa2Eb544A9873A8BF94C353E7620d74f0f; // Dontblink
address public a3 = 0x84B304015790df208B401DEf59ADd3685848A871; // Skelligore
// Community Multisig Wallet Address
address public a4 = 0xBF600B4339F3dBe86f70ad1B171FD4Da2D2BA841; // Community Wallet
// Presale Address List
mapping (uint => uint) public claimedVouchers;
// Base Link That Leads To Metadata
string public baseTokenURI;
// Contract Construction
constructor (
string memory newBaseURI,
address voucherSigner,
uint256 maxBatchSize_,
uint256 collectionSize_
)
ERC721A ("Cosmic Cats", "COSMIC", maxBatchSize_, collectionSize_)
CosmicVoucherSigner(voucherSigner) {
setBaseURI(newBaseURI);
}
// ================ Mint Functions ================ //
// Minting Function
function mintCosmicCats(uint256 _amount) external payable {
uint256 supply = totalSupply();
require( saleActive, "Public Sale Not Active" );
require( _amount > 0 && _amount <= maxBatchSize, "Can't Mint More Than 10" );
require( supply + _amount <= PUBLIC_SUPPLY, "Not Enough Supply" );
require( msg.value == price * _amount, "Incorrect Amount Of ETH Sent" );
_safeMint( msg.sender, _amount);
}
// Presale Minting
function mintPresale(uint256 _amount, CosmicVoucher.Voucher calldata v) public payable {
uint256 supply = totalSupply();
require(presaleActive, "Private Sale Not Active");
require(claimedVouchers[v.voucherId] + _amount <= 3, "Max 3 During Presale");
require(_amount <= 3, "Can't Mint More Than 3");
require(v.to == msg.sender, "You Are NOT Whitelisted");
require(CosmicVoucher.validateVoucher(v, getVoucherSigner()), "Invalid Voucher");
require( supply + _amount <= PUBLIC_SUPPLY, "Not Enough Supply" );
require( msg.value == price * _amount, "Incorrect Amount Of ETH Sent" );
claimedVouchers[v.voucherId] += _amount;
_safeMint( msg.sender, _amount);
}
// Presale Reduced Minting
function mintReducedPresale(uint256 _amount, CosmicVoucher.Voucher calldata v) public payable {
uint256 supply = totalSupply();
require(reducedPresaleActive, "Reduced Private Sale Not Active");
require(claimedVouchers[v.voucherId] + _amount <= 1, "Max 1 During Reduced Presale");
require(v.voucherId >= 6000, "Not Eligible For Reduced Mint");
require(_amount <= 1, "Can't Mint More Than 1");
require(v.to == msg.sender, "You Are NOT Whitelisted");
require(CosmicVoucher.validateVoucher(v, getVoucherSigner()), "Invalid Voucher");
require( supply + _amount <= PUBLIC_SUPPLY, "Not Enough Supply" );
require( msg.value == reducedPrice * _amount, "Incorrect Amount Of ETH Sent" );
claimedVouchers[v.voucherId] += _amount;
_safeMint( msg.sender, _amount);
}
// Validate Voucher
function validateVoucher(CosmicVoucher.Voucher calldata v) external view returns (bool) {
return CosmicVoucher.validateVoucher(v, getVoucherSigner());
}
// ================ Only Owner Functions ================ //
// Gift Function - Collabs & Giveaways
function gift(address _to, uint256 _amount) external onlyOwner() {
uint256 supply = totalSupply();
require( supply + _amount <= MAX_SUPPLY, "Not Enough Supply" );
_safeMint( _to, _amount );
}
// Incase ETH Price Rises Rapidly
function setPrice(uint256 newPrice) public onlyOwner() {
price = newPrice;
}
// Set New baseURI
function setBaseURI(string memory baseURI) public onlyOwner {
baseTokenURI = baseURI;
}
// ================ Sale Controls ================ //
// Pre Sale On/Off
function setPresaleActive(bool val) public onlyOwner {
presaleActive = val;
}
// Reduced Pre Sale On/Off
function setReducedPresaleActive(bool val) public onlyOwner {
reducedPresaleActive = val;
}
// Public Sale On/Off
function setSaleActive(bool val) public onlyOwner {
saleActive = val;
}
// ================ Withdraw Functions ================ //
// Team Withdraw Function
function withdrawTeam() public onlyOwner {
uint256 balance = address(this).balance;
require(balance > 0);
_widthdraw(a1, balance.mul(25).div(100)); // Justin
_widthdraw(a2, balance.mul(25).div(100)); // Dontblink
_widthdraw(a3, balance.mul(25).div(100)); // Skelligore
_widthdraw(a4, address(this).balance); // Community Wallet
}
// Private Function -- Only Accesible By Contract
function _widthdraw(address _address, uint256 _amount) private {
(bool success, ) = _address.call{value: _amount}("");
require(success, "Transfer failed.");
}
// Emergency Withdraw Function -- Sends to Multisig Wallet
function emergencyWithdraw() public onlyOwner {
uint256 balance = address(this).balance;
payable(a4).transfer(balance);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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/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
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Assumes the number of issuable tokens (collection size) is capped and fits in a uint128.
*
* 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 collectionSize;
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.
* `collectionSize_` refers to how many tokens are in the collection.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_,
uint256 collectionSize_
) {
require(
collectionSize_ > 0,
"ERC721A: collection must have a nonzero supply"
);
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
collectionSize = collectionSize_;
}
/**
* @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(collectionSize). 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:
*
* - there must be `quantity` tokens remaining unminted in the total collection.
* - `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 > collectionSize - 1) {
endIndex = collectionSize - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721A: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
abstract contract CosmicVoucherSigner is Ownable {
address private _voucherSigner;
event SetVoucherSigner(address prevVoucherSigner, address newVoucherSigner);
function setVoucherSigner(address newVoucherSigner) public onlyOwner {
require(newVoucherSigner != address(0), "Setting voucher signer to 0 address");
_voucherSigner = newVoucherSigner;
emit SetVoucherSigner(_voucherSigner, newVoucherSigner);
}
function getVoucherSigner() public view returns (address) {
return _voucherSigner;
}
constructor(address voucherSigner) {
setVoucherSigner(voucherSigner);
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library CosmicVoucher {
struct Sig {
bytes32 r;
bytes32 s;
uint8 v;
}
struct Voucher {
uint voucherId;
address to;
Sig sig;
}
function validateVoucher(Voucher calldata v, address signer)
internal pure returns (bool)
{
bytes32 h1 = keccak256(abi.encodePacked(v.voucherId, v.to));
bytes32 h2 = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", h1));
return ecrecover(h2, v.sig.v, v.sig.r, v.sig.s) == signer;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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
|
abstract contract CosmicVoucherSigner is Ownable {
address private _voucherSigner;
event SetVoucherSigner(address prevVoucherSigner, address newVoucherSigner);
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;
import "@openzeppelin/contracts/access/Ownable.sol";
function setVoucherSigner(address newVoucherSigner) public onlyOwner {
require(newVoucherSigner != address(0), "Setting voucher signer to 0 address");
_voucherSigner = newVoucherSigner;
emit SetVoucherSigner(_voucherSigner, newVoucherSigner);
}
function getVoucherSigner() public view returns (address) {
return _voucherSigner;
}
constructor(address voucherSigner) {
setVoucherSigner(voucherSigner);
}
}
| 6,147,151 |
[
1,
3118,
28826,
17,
13211,
17,
3004,
30,
490,
1285,
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,
17801,
6835,
385,
538,
27593,
19585,
15647,
353,
14223,
6914,
288,
203,
203,
225,
1758,
3238,
389,
90,
14329,
15647,
31,
203,
203,
225,
871,
1000,
19585,
15647,
12,
2867,
2807,
19585,
15647,
16,
1758,
394,
19585,
15647,
1769,
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,
203,
565,
2254,
5034,
10457,
203,
97,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
203,
5666,
8787,
3190,
94,
881,
84,
292,
267,
19,
16351,
87,
19,
3860,
19,
5460,
429,
18,
18281,
14432,
203,
203,
225,
445,
444,
19585,
15647,
12,
2867,
394,
19585,
15647,
13,
1071,
1338,
5541,
288,
203,
565,
2583,
12,
2704,
19585,
15647,
480,
1758,
12,
20,
3631,
315,
5568,
331,
14329,
10363,
358,
374,
1758,
8863,
203,
565,
389,
90,
14329,
15647,
273,
394,
19585,
15647,
31,
203,
565,
3626,
1000,
19585,
15647,
24899,
90,
14329,
15647,
16,
394,
19585,
15647,
1769,
203,
225,
289,
203,
203,
225,
445,
11031,
14329,
15647,
1435,
1071,
1476,
1135,
261,
2867,
13,
288,
203,
565,
327,
389,
90,
14329,
15647,
31,
203,
225,
289,
203,
203,
225,
3885,
12,
2867,
331,
14329,
15647,
13,
288,
203,
565,
444,
19585,
15647,
12,
90,
14329,
15647,
2
] |
./full_match/2222/0xB9a14EE1cd3417f3AcC988F61650895151abde24/sources/contracts/base/ApproveAndCall.sol
|
@title Approve and Call @notice Allows callers to approve the Uniswap V3 position manager from this contract, for any token, and then make calls into the position manager
|
abstract contract ApproveAndCall is IApproveAndCall, ImmutableState {
pragma solidity =0.7.6;
function tryApprove(address token, uint256 amount) private returns (bool) {
(bool success, bytes memory data) =
token.call(abi.encodeWithSelector(IERC20.approve.selector, positionManager, amount));
return success && (data.length == 0 || abi.decode(data, (bool)));
}
function getApprovalType(address token, uint256 amount) external override returns (ApprovalType) {
if (IERC20(token).allowance(address(this), positionManager) >= amount) return ApprovalType.NOT_REQUIRED;
if (tryApprove(token, type(uint256).max)) return ApprovalType.MAX;
if (tryApprove(token, type(uint256).max - 1)) return ApprovalType.MAX_MINUS_ONE;
require(tryApprove(token, 0));
if (tryApprove(token, type(uint256).max)) return ApprovalType.ZERO_THEN_MAX;
if (tryApprove(token, type(uint256).max - 1)) return ApprovalType.ZERO_THEN_MAX_MINUS_ONE;
revert();
}
function approveMax(address token) external payable override {
require(tryApprove(token, type(uint256).max));
}
function approveMaxMinusOne(address token) external payable override {
require(tryApprove(token, type(uint256).max - 1));
}
function approveZeroThenMax(address token) external payable override {
require(tryApprove(token, 0));
require(tryApprove(token, type(uint256).max));
}
function approveZeroThenMaxMinusOne(address token) external payable override {
require(tryApprove(token, 0));
require(tryApprove(token, type(uint256).max - 1));
}
function callPositionManager(bytes memory data) public payable override returns (bytes memory result) {
bool success;
(success, result) = positionManager.call(data);
if (!success) {
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
}
function callPositionManager(bytes memory data) public payable override returns (bytes memory result) {
bool success;
(success, result) = positionManager.call(data);
if (!success) {
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
}
function callPositionManager(bytes memory data) public payable override returns (bytes memory result) {
bool success;
(success, result) = positionManager.call(data);
if (!success) {
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
}
function balanceOf(address token) private view returns (uint256) {
return IERC20(token).balanceOf(address(this));
}
function mint(MintParams calldata params) external payable override returns (bytes memory result) {
return
callPositionManager(
abi.encodeWithSelector(
INonfungiblePositionManager.mint.selector,
INonfungiblePositionManager.MintParams({
token0: params.token0,
token1: params.token1,
fee: params.fee,
tickLower: params.tickLower,
tickUpper: params.tickUpper,
amount0Desired: balanceOf(params.token0),
amount1Desired: balanceOf(params.token1),
amount0Min: params.amount0Min,
amount1Min: params.amount1Min,
recipient: params.recipient,
})
)
);
}
function mint(MintParams calldata params) external payable override returns (bytes memory result) {
return
callPositionManager(
abi.encodeWithSelector(
INonfungiblePositionManager.mint.selector,
INonfungiblePositionManager.MintParams({
token0: params.token0,
token1: params.token1,
fee: params.fee,
tickLower: params.tickLower,
tickUpper: params.tickUpper,
amount0Desired: balanceOf(params.token0),
amount1Desired: balanceOf(params.token1),
amount0Min: params.amount0Min,
amount1Min: params.amount1Min,
recipient: params.recipient,
})
)
);
}
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
override
returns (bytes memory result)
{
return
callPositionManager(
abi.encodeWithSelector(
INonfungiblePositionManager.increaseLiquidity.selector,
INonfungiblePositionManager.IncreaseLiquidityParams({
tokenId: params.tokenId,
amount0Desired: balanceOf(params.token0),
amount1Desired: balanceOf(params.token1),
amount0Min: params.amount0Min,
amount1Min: params.amount1Min,
})
)
);
}
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
override
returns (bytes memory result)
{
return
callPositionManager(
abi.encodeWithSelector(
INonfungiblePositionManager.increaseLiquidity.selector,
INonfungiblePositionManager.IncreaseLiquidityParams({
tokenId: params.tokenId,
amount0Desired: balanceOf(params.token0),
amount1Desired: balanceOf(params.token1),
amount0Min: params.amount0Min,
amount1Min: params.amount1Min,
})
)
);
}
}
| 7,102,626 |
[
1,
12053,
537,
471,
3049,
225,
25619,
19932,
358,
6617,
537,
326,
1351,
291,
91,
438,
776,
23,
1754,
3301,
628,
333,
6835,
16,
364,
1281,
1147,
16,
471,
1508,
1221,
4097,
1368,
326,
1754,
3301,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
17801,
6835,
1716,
685,
537,
1876,
1477,
353,
467,
12053,
537,
1876,
1477,
16,
7252,
1119,
288,
203,
683,
9454,
18035,
560,
273,
20,
18,
27,
18,
26,
31,
203,
565,
445,
775,
12053,
537,
12,
2867,
1147,
16,
2254,
5034,
3844,
13,
3238,
1135,
261,
6430,
13,
288,
203,
3639,
261,
6430,
2216,
16,
1731,
3778,
501,
13,
273,
203,
5411,
1147,
18,
1991,
12,
21457,
18,
3015,
1190,
4320,
12,
45,
654,
39,
3462,
18,
12908,
537,
18,
9663,
16,
1754,
1318,
16,
3844,
10019,
203,
3639,
327,
2216,
597,
261,
892,
18,
2469,
422,
374,
747,
24126,
18,
3922,
12,
892,
16,
261,
6430,
3719,
1769,
203,
565,
289,
203,
203,
565,
445,
336,
23461,
559,
12,
2867,
1147,
16,
2254,
5034,
3844,
13,
3903,
3849,
1135,
261,
23461,
559,
13,
288,
203,
3639,
309,
261,
45,
654,
39,
3462,
12,
2316,
2934,
5965,
1359,
12,
2867,
12,
2211,
3631,
1754,
1318,
13,
1545,
3844,
13,
327,
1716,
685,
1125,
559,
18,
4400,
67,
14977,
31,
203,
203,
3639,
309,
261,
698,
12053,
537,
12,
2316,
16,
618,
12,
11890,
5034,
2934,
1896,
3719,
327,
1716,
685,
1125,
559,
18,
6694,
31,
203,
3639,
309,
261,
698,
12053,
537,
12,
2316,
16,
618,
12,
11890,
5034,
2934,
1896,
300,
404,
3719,
327,
1716,
685,
1125,
559,
18,
6694,
67,
6236,
3378,
67,
5998,
31,
203,
203,
3639,
2583,
12,
698,
12053,
537,
12,
2316,
16,
374,
10019,
203,
203,
3639,
309,
261,
698,
12053,
537,
12,
2316,
16,
618,
12,
11890,
2
] |
./partial_match/1/0xB224d609ec38E01d7CAAf731B2465f33b8105229/sources/HouseOfPanda.sol
|
* This function checks if the parameter 'account' is the owner of the contract. @param account The address of the account to be checked. @return {bool} A boolean indicating whether the account is the owner or not./
|
function _isOwner(address account) internal view returns (bool) {
return owner() == account;
}
| 15,645,082 |
[
1,
2503,
445,
4271,
309,
326,
1569,
296,
4631,
11,
353,
326,
3410,
434,
326,
6835,
18,
225,
2236,
1021,
1758,
434,
326,
2236,
358,
506,
5950,
18,
327,
288,
6430,
97,
432,
1250,
11193,
2856,
326,
2236,
353,
326,
3410,
578,
486,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
445,
389,
291,
5541,
12,
2867,
2236,
13,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
3410,
1435,
422,
2236,
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.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./FateToken.sol";
import "./RewardSchedule.sol";
interface IMigratorChef {
// Perform LP token migration from legacy UniswapV2 to FATEx DEX.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// FATEx DEX must mint EXACTLY the same amount of FATEx DEX LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
}
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once FATE is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract FateRewardController is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of FATEs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accumulatedFatePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accumulatedFatePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. FATEs to distribute per block.
uint256 lastRewardBlock; // Last block number that FATEs distribution occurs.
uint256 accumulatedFatePerShare; // Accumulated FATEs per share, times 1e12. See below.
}
FateToken public fate;
address public vault;
// The emission scheduler that calculates fate per block over a given period
RewardSchedule public emissionSchedule;
// Bonus multiplier for early fate LP deposits.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when FATE mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event ClaimRewards(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmissionScheduleSet(address indexed emissionSchedule);
event VaultSet(address indexed emissionSchedule);
constructor(
FateToken _fate,
RewardSchedule _emissionSchedule,
address _vault
) public {
fate = _fate;
emissionSchedule = _emissionSchedule;
vault = _vault;
startBlock = block.number;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken : _lpToken,
allocPoint : _allocPoint,
lastRewardBlock : lastRewardBlock,
accumulatedFatePerShare : 0
})
);
}
// Update the given pool's FATE allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// View function to see pending FATE tokens on frontend.
function pendingFate(uint256 _pid, address _user)
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accumulatedFatePerShare = pool.accumulatedFatePerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 fatePerBlock = emissionSchedule.getFatePerBlock(startBlock, pool.lastRewardBlock, block.number);
uint256 fateReward = fatePerBlock.mul(pool.allocPoint).div(totalAllocPoint);
accumulatedFatePerShare = accumulatedFatePerShare.add(fateReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accumulatedFatePerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function getNewRewardPerBlock(uint pid1) public view returns (uint) {
uint256 fatePerBlock = emissionSchedule.getFatePerBlock(startBlock, block.number - 1, block.number);
if (pid1 == 0) {
return fatePerBlock;
} else {
return fatePerBlock.mul(poolInfo[pid1 - 1].allocPoint).div(totalAllocPoint);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 fatePerBlock = emissionSchedule.getFatePerBlock(startBlock, pool.lastRewardBlock, block.number);
uint256 fateReward = fatePerBlock.mul(pool.allocPoint).div(totalAllocPoint);
if (fateReward > 0) {
fate.transferFrom(vault, address(this), fateReward);
pool.accumulatedFatePerShare = pool.accumulatedFatePerShare.add(fateReward.mul(1e12).div(lpSupply));
}
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for FATE allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accumulatedFatePerShare).div(1e12).sub(user.rewardDebt);
safeFateTransfer(msg.sender, pending);
emit ClaimRewards(msg.sender, _pid, pending);
}
pool.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accumulatedFatePerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accumulatedFatePerShare).div(1e12).sub(user.rewardDebt);
safeFateTransfer(msg.sender, pending);
emit ClaimRewards(msg.sender, _pid, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accumulatedFatePerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// claim any pending rewards from this pool, from msg.sender
function claimReward(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accumulatedFatePerShare).div(1e12).sub(user.rewardDebt);
safeFateTransfer(msg.sender, pending);
emit ClaimRewards(msg.sender, _pid, pending);
user.rewardDebt = user.amount.mul(pool.accumulatedFatePerShare).div(1e12);
}
// claim any pending rewards from this pool, from msg.sender
function claimRewards(uint256[] calldata _pids) external {
for (uint i = 0; i < _pids.length; i++) {
claimReward(_pids[i]);
}
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe fate transfer function, just in case if rounding error causes pool to not have enough FATEs.
function safeFateTransfer(address _to, uint256 _amount) internal {
uint256 fateBal = fate.balanceOf(address(this));
if (_amount > fateBal) {
fate.transfer(_to, fateBal);
} else {
fate.transfer(_to, _amount);
}
}
function setEmissionSchedule(
RewardSchedule _emissionSchedule
)
public
onlyOwner {
// pro-rate the pools to the current block, before changing the schedule
massUpdatePools();
emissionSchedule = _emissionSchedule;
emit EmissionScheduleSet(address(_emissionSchedule));
}
function setVault(
address _vault
)
public
onlyOwner {
// pro-rate the pools to the current block, before changing the schedule
vault = _vault;
emit VaultSet(_vault);
}
}
|
Add a new lp to the pool. Can only be called by the owner. XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
|
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
lpToken : _lpToken,
allocPoint : _allocPoint,
lastRewardBlock : lastRewardBlock,
accumulatedFatePerShare : 0
})
);
}
| 13,010,709 |
[
1,
986,
279,
394,
12423,
358,
326,
2845,
18,
4480,
1338,
506,
2566,
635,
326,
3410,
18,
11329,
5467,
4269,
527,
326,
1967,
511,
52,
1147,
1898,
2353,
3647,
18,
534,
359,
14727,
903,
506,
15216,
730,
731,
309,
1846,
741,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
527,
12,
203,
3639,
2254,
5034,
389,
9853,
2148,
16,
203,
3639,
467,
654,
39,
3462,
389,
9953,
1345,
16,
203,
3639,
1426,
389,
1918,
1891,
203,
565,
262,
1071,
1338,
5541,
288,
203,
3639,
309,
261,
67,
1918,
1891,
13,
288,
203,
5411,
8039,
1891,
16639,
5621,
203,
3639,
289,
203,
203,
3639,
2254,
5034,
1142,
17631,
1060,
1768,
273,
1203,
18,
2696,
405,
787,
1768,
692,
1203,
18,
2696,
294,
787,
1768,
31,
203,
3639,
2078,
8763,
2148,
273,
2078,
8763,
2148,
18,
1289,
24899,
9853,
2148,
1769,
203,
3639,
2845,
966,
18,
6206,
12,
203,
5411,
8828,
966,
12590,
203,
3639,
12423,
1345,
294,
389,
9953,
1345,
16,
203,
3639,
4767,
2148,
294,
389,
9853,
2148,
16,
203,
3639,
1142,
17631,
1060,
1768,
294,
1142,
17631,
1060,
1768,
16,
203,
3639,
24893,
42,
340,
2173,
9535,
294,
374,
203,
3639,
289,
13,
203,
3639,
11272,
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
] |
// SPDX-License-Identifier: UNLICENSE
// Rzucam worki w tłum w tłum .. kto łapie ten jara ... XD
/**
Apes Together Strong!
About BigShortBets DeFi project:
We are creating a social&trading p2p platform that guarantees encrypted interaction between investors.
Logging in is possible via a cryptocurrency wallet (e.g. Metamask).
The security level is one comparable to the Tor network.
https://bigsb.io/ - Our Tool
https://bigshortbets.com - Project&Team info
Video explainer:
https://youtu.be/wbhUo5IvKdk
Zaorski, You Son of a bitch I’m in …
*/
pragma solidity 0.8.7;
import "./interfaces.sol";
import "./owned.sol";
/**
BigShortBets.com BigSB token claiming contract
Contract need tokens on its address to send them to owners
*/
contract ClaimBigSB is Owned {
// presale contracts
address public immutable presale1;
address public immutable presale2;
address public immutable sale;
// BigSB token contract
address public immutable token;
// 1-year claiming window after which Owner can sweep remaining tokens
uint256 public immutable claimDateLimit;
// claiming process need to be enabled
bool public claimStarted;
// Presale2 is bugged in handling multiple ETH deposits
// we need handle that
mapping(address => uint256) internal buggedTokens;
// mark users that already claim tokens
mapping(address => bool) public isClaimed;
// handle ETH/tokens send from exchanges
mapping(address => address) internal _morty;
// AML-ed users address->tokens
mapping(address => uint256) internal _aml;
// events
event TokensClaimed(
address indexed from,
address indexed to,
uint256 amount
);
// useful constant
address internal constant ZERO = address(0x0);
uint256 internal immutable startRate;
/**
@dev contract constructor
@param _presale1 address of presale1 contract
@param _presale2 address of presale2 contract
@param _sale address of final sale contract
@param _token address of BigSB token contract
*/
constructor(
address _presale1,
address _presale2,
address _sale,
address _token
) {
presale1 = _presale1;
presale2 = _presale2;
sale = _sale;
token = _token;
claimDateLimit = block.timestamp + 365 days; //max 1 year to take tokens
startRate = IReflect(_token).getRate();
}
// count tokens from all pre/sale contracts
function _allTokens(address user) internal view returns (uint256) {
// presale2 need manual handle because of "multiple ETH send" error
// "tokensBoughtOf" is also flawed, so we do all math there
uint256 amt = buggedTokens[user];
if (amt == 0) {
// calculate tokens at sale price $2630/ETH, $0.95/token
// function is returning ETH value in wei
amt = (IPresale2(presale2).ethDepositOf(user) * 2630 * 100) / 95;
// calculate tokens for USD at $0.95/token
// contract is returning USD with 0 decimals
amt += (IPresale2(presale2).usdDepositOf(user) * 100 ether) / 95;
}
// presale1 reader is returning ETH amount in wei, $0.65 / token, $1530/ETH
// yes, there is a typo in function name
amt += (IPresale1(presale1).blanceOf(user) * 1530 * 100) / 65;
// sale returning tokens, $1/token, ETH price from oracle at buy time
amt += ISale(sale).tokensBoughtOf(user);
return amt;
}
/**
Reader that can check how many tokens can be claimed by given address
@param user address to check
@return number of tokens (18 decimals)
*/
function canClaim(address user) external view returns (uint256) {
return _recalculate(_allTokens(user));
}
// recalculate amount of tokens via start rate
function _recalculate(uint256 tokens) internal view returns (uint256) {
uint256 rate = IReflect(token).getRate();
return (tokens * rate) / startRate;
}
/**
@dev claim BigSB tokens bought on any pre/sale
*/
function claim() external {
require(_morty[msg.sender] == ZERO, "Use claimFrom");
_claim(msg.sender, msg.sender);
}
/// Claim tokens from AMLed list
function claimAML() external {
uint256 amt = _aml[msg.sender];
require(amt > 0, "Not on AML list");
_aml[msg.sender] = 0;
amt = _recalculate(amt);
IERC20(token).transfer(msg.sender, amt);
emit TokensClaimed(msg.sender, msg.sender, amt);
}
/**
@dev Claim BigSB tokens bought on any pre/sale to different address
@param to address to which tokens will be claimed
*/
function claimTo(address to) external {
require(_morty[msg.sender] == ZERO, "Use claimFromTo");
_claim(msg.sender, to);
}
/**
@dev Claim BigSB tokens bought on any pre/sale from exchange
@param from sender address that ETH was send to pre/sale contract
*/
function claimFrom(address from) external {
address to = _morty[from];
require(msg.sender == to, "Wrong Morty");
_claim(from, to);
}
/**
@dev Claim BigSB tokens by ETH send from exchange to another address
@param from sender address that ETH was send
@param to address to which send claimed tokens
*/
function claimFromTo(address from, address to) external {
require(msg.sender == _morty[from], "Wrong Morty");
_claim(from, to);
}
// internal claim function, validate claim and send tokens to given address
function _claim(address from, address to)
internal
claimStart
notZeroAddress(to)
{
require(!isClaimed[from], "Already claimed!");
isClaimed[from] = true;
uint256 amt = _recalculate(_allTokens(from));
require(IERC20(token).transfer(to, amt), "Token transfer failed");
emit TokensClaimed(from, to, amt);
}
//
// viewers
//
function isReplacedBy(address user) external view returns (address) {
return _morty[user];
}
//
// useful modifiers
//
modifier notZeroAddress(address user) {
require(user != ZERO, "Can not use address 0x0");
_;
}
modifier claimStart() {
require(claimStarted, "Claiming process not started!");
_;
}
modifier claimNotStarted() {
require(!claimStarted, "Claiming process already started!");
_;
}
//
// Rick mode
//
/**
@dev add single address that need to be changed in claim process
@param bad address to replace
@param good new address that can claim tokens bought by "bad" address
*/
function addMorty(address bad, address good)
external
onlyOwner
claimNotStarted
{
_addMorty(bad, good);
}
/// internal add replacement address function used in singe and multi add function
function _addMorty(address bad, address good)
internal
notZeroAddress(good)
{
require(_morty[bad] == ZERO, "Morty already on list");
_morty[bad] = good;
}
/**
@dev add addresses that need to be replaced in claiming precess, ie send ETH from exchange
@param bad list of wrong send addresses
@param good list of address replacements
*/
function addMortys(address[] calldata bad, address[] calldata good)
external
onlyOwner
claimNotStarted
{
uint256 dl = bad.length;
require(dl == good.length, "Data size mismatch");
uint256 i;
for (i; i < dl; i++) {
_addMorty(bad[i], good[i]);
}
}
/**
@dev add single "bugged" user
@param user affected user address
@param tokens counted tokens for user from presale2
*/
function addBugged(address user, uint256 tokens)
external
onlyOwner
claimNotStarted
{
buggedTokens[user] = tokens;
}
/**
@dev add list of users affected by "many ETH send" bug via list
@param user list of users
@param amt list of corresponding tokens amount
*/
function addBuggedList(address[] calldata user, uint256[] calldata amt)
external
onlyOwner
claimNotStarted
{
uint256 dl = user.length;
require(dl == amt.length, "Data size mismatch");
uint256 i;
for (i; i < dl; i++) {
buggedTokens[user[i]] = amt[i];
}
}
// add data to ALMed user list
function addAML(address[] calldata user, uint256[] calldata tokens)
external
onlyOwner
claimNotStarted
{
uint256 dl = user.length;
require(dl == tokens.length, "Data size mismatch");
uint256 i;
for (i; i < dl; i++) {
_aml[user[i]] = tokens[i];
}
}
/// Enable claiming process
function enableClaim() external onlyOwner claimNotStarted {
claimStarted = true;
}
/**
@dev Function to recover accidentally send ERC20 tokens
@param erc20 ERC20 token address
*/
function rescueERC20(address erc20) external onlyOwner {
if (erc20 == token) {
require(block.timestamp > claimDateLimit, "Too soon");
}
uint256 amt = IERC20(erc20).balanceOf(address(this));
require(amt > 0, "Nothing to rescue");
IUsdt(erc20).transfer(owner, amt);
}
/**
@dev Function to recover any ETH send to contract
*/
function rescueETH() external onlyOwner {
payable(owner).transfer(address(this).balance);
}
}
//This is fine!
|
Enable claiming process
|
function enableClaim() external onlyOwner claimNotStarted {
claimStarted = true;
}
@param erc20 ERC20 token address
| 1,105,500 |
[
1,
8317,
7516,
310,
1207,
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,
565,
445,
4237,
9762,
1435,
3903,
1338,
5541,
7516,
1248,
9217,
288,
203,
3639,
7516,
9217,
273,
638,
31,
203,
565,
289,
203,
203,
565,
632,
891,
6445,
71,
3462,
4232,
39,
3462,
1147,
1758,
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
] |
./full_match/56/0xF10582E78f4B7879AF5244827f1190D21162F964/sources/project_/contracts/StrategyCommonChefLP.sol
|
compounds earnings and charges performance fee chargeFees(); swapRewards();
|
function harvest() external whenNotPaused onlyEOA {
IRewardPool(rewardPool).getReward();
addLiquidity();
deposit();
emit StratHarvest(msg.sender);
}
| 3,234,848 |
[
1,
2919,
9284,
425,
1303,
899,
471,
1149,
2852,
9239,
14036,
13765,
2954,
281,
5621,
7720,
17631,
14727,
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
] |
[
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,
445,
17895,
26923,
1435,
3903,
1347,
1248,
28590,
1338,
41,
28202,
288,
203,
3639,
15908,
359,
1060,
2864,
12,
266,
2913,
2864,
2934,
588,
17631,
1060,
5621,
203,
3639,
527,
48,
18988,
24237,
5621,
203,
3639,
443,
1724,
5621,
203,
203,
3639,
3626,
3978,
270,
44,
297,
26923,
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
] |
pragma solidity >=0.4.21 <0.6.0;
contract HelloHari {
//uint constant COAP_JOB = 2;
string temp = "0";
function setTemp(string memory newTemp) public {
temp = newTemp;
}
function getTemp() public view returns (string memory) {
return temp;
}
function sayHello() public pure returns(string memory){
return("hello Hari");
}
// function coapExample() public {
// string memory coapServer = "eval:const coap = require('coap'); req = coap.request('coap://localhost:5683'); req.on('response', function(res) { res.pipe(process.stdout); }); req.end();";
// Run(DaysUntilNext15th_Id, coapServer, "", "coap", 2, DEFAULT_GAS_UNITS, DEFAULT_GAS_PRICE);
// Run(
// COAP_JOB, /* give the job a unique ID */
// /* JavaScript code I want to execute: */
// "module.exports = async function(CaptainJSIn) { const coap = require('coap'); req = coap.request('coap://localhost:5683'); req.on('response', function(res) { res.pipe(process.stdout); }); req.end();",
// Country, /* Input parameter which will result in CaptainJSIn (see above) */
// "coap", /* Nodejs libraries we need */
// 3, /* we need a maximum of 3 runtime slices */
// 200000, /* use 200,000 gas units */
// DEFAULT_GAS_PRICE /* use default gas price */
// );
// }
}
|
uint constant COAP_JOB = 2;
|
contract HelloHari {
string temp = "0";
function setTemp(string memory newTemp) public {
temp = newTemp;
}
function getTemp() public view returns (string memory) {
return temp;
}
function sayHello() public pure returns(string memory){
return("hello Hari");
}
}
| 5,400,399 |
[
1,
11890,
5381,
7910,
2203,
67,
18321,
273,
576,
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,
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,
20889,
44,
12954,
288,
203,
565,
533,
1906,
273,
315,
20,
14432,
203,
203,
565,
445,
444,
7185,
12,
1080,
3778,
394,
7185,
13,
1071,
288,
203,
203,
4202,
1906,
273,
394,
7185,
31,
203,
203,
282,
289,
203,
203,
27699,
203,
282,
445,
28988,
1435,
1071,
1476,
1135,
261,
1080,
3778,
13,
288,
203,
203,
4202,
327,
1906,
31,
203,
203,
282,
289,
203,
203,
565,
445,
12532,
18601,
1435,
1071,
16618,
1135,
12,
1080,
3778,
15329,
203,
3639,
327,
2932,
23711,
670,
12954,
8863,
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
] |
// Sources flattened with hardhat v2.6.1 https://hardhat.org
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/utils/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/utils/[email protected]
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File interfaces/IPreparable.sol
pragma solidity 0.8.9;
interface IPreparable {
event ConfigPreparedAddress(bytes32 indexed key, address value, uint256 delay);
event ConfigPreparedNumber(bytes32 indexed key, uint256 value, uint256 delay);
event ConfigUpdatedAddress(bytes32 indexed key, address oldValue, address newValue);
event ConfigUpdatedNumber(bytes32 indexed key, uint256 oldValue, uint256 newValue);
event ConfigReset(bytes32 indexed key);
}
// File interfaces/IStrategy.sol
pragma solidity 0.8.9;
interface IStrategy {
function name() external view returns (string memory);
function deposit() external payable returns (bool);
function balance() external view returns (uint256);
function withdraw(uint256 amount) external returns (bool);
function withdrawAll() external returns (uint256);
function harvestable() external view returns (uint256);
function harvest() external returns (uint256);
function strategist() external view returns (address);
function shutdown() external returns (bool);
function hasPendingFunds() external view returns (bool);
}
// File interfaces/IVault.sol
pragma solidity 0.8.9;
/**
* @title Interface for a Vault
*/
interface IVault is IPreparable {
event StrategyActivated(address indexed strategy);
event StrategyDeactivated(address indexed strategy);
/**
* @dev 'netProfit' is the profit after all fees have been deducted
*/
event Harvest(uint256 indexed netProfit, uint256 indexed loss);
function initialize(
address _pool,
uint256 _debtLimit,
uint256 _targetAllocation,
uint256 _bound
) external;
function withdrawFromStrategyWaitingForRemoval(address strategy) external returns (uint256);
function deposit() external payable;
function withdraw(uint256 amount) external returns (bool);
function initializeStrategy(address strategy_) external returns (bool);
function withdrawAll() external;
function withdrawFromReserve(uint256 amount) external;
function getStrategy() external view returns (IStrategy);
function getStrategiesWaitingForRemoval() external view returns (address[] memory);
function getAllocatedToStrategyWaitingForRemoval(address strategy)
external
view
returns (uint256);
function getTotalUnderlying() external view returns (uint256);
function getUnderlying() external view returns (address);
}
// File interfaces/pool/ILiquidityPool.sol
pragma solidity 0.8.9;
interface ILiquidityPool is IPreparable {
event Deposit(address indexed minter, uint256 depositAmount, uint256 mintedLpTokens);
event DepositFor(
address indexed minter,
address indexed mintee,
uint256 depositAmount,
uint256 mintedLpTokens
);
event Redeem(address indexed redeemer, uint256 redeemAmount, uint256 redeemTokens);
event LpTokenSet(address indexed lpToken);
event StakerVaultSet(address indexed stakerVault);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeem(uint256 redeemTokens, uint256 minRedeemAmount) external returns (uint256);
function calcRedeem(address account, uint256 underlyingAmount) external returns (uint256);
function deposit(uint256 mintAmount) external payable returns (uint256);
function deposit(uint256 mintAmount, uint256 minTokenAmount) external payable returns (uint256);
function depositAndStake(uint256 depositAmount, uint256 minTokenAmount)
external
payable
returns (uint256);
function depositFor(address account, uint256 depositAmount) external payable returns (uint256);
function depositFor(
address account,
uint256 depositAmount,
uint256 minTokenAmount
) external payable returns (uint256);
function unstakeAndRedeem(uint256 redeemLpTokens, uint256 minRedeemAmount)
external
returns (uint256);
function handleLpTokenTransfer(
address from,
address to,
uint256 amount
) external;
function executeNewVault() external returns (address);
function executeNewMaxWithdrawalFee() external returns (uint256);
function executeNewRequiredReserves() external returns (uint256);
function executeNewReserveDeviation() external returns (uint256);
function setLpToken(address _lpToken) external returns (bool);
function setStaker() external returns (bool);
function isCapped() external returns (bool);
function uncap() external returns (bool);
function updateDepositCap(uint256 _depositCap) external returns (bool);
function getUnderlying() external view returns (address);
function getLpToken() external view returns (address);
function getWithdrawalFee(address account, uint256 amount) external view returns (uint256);
function getVault() external view returns (IVault);
function exchangeRate() external view returns (uint256);
}
// File interfaces/IGasBank.sol
pragma solidity 0.8.9;
interface IGasBank {
event Deposit(address indexed account, uint256 value);
event Withdraw(address indexed account, address indexed receiver, uint256 value);
function depositFor(address account) external payable;
function withdrawUnused(address account) external;
function withdrawFrom(address account, uint256 amount) external;
function withdrawFrom(
address account,
address payable to,
uint256 amount
) external;
function balanceOf(address account) external view returns (uint256);
}
// File interfaces/oracles/IOracleProvider.sol
pragma solidity 0.8.9;
interface IOracleProvider {
/// @notice Quotes the USD price of `baseAsset`
/// @param baseAsset the asset of which the price is to be quoted
/// @return the USD price of the asset
function getPriceUSD(address baseAsset) external view returns (uint256);
/// @notice Quotes the ETH price of `baseAsset`
/// @param baseAsset the asset of which the price is to be quoted
/// @return the ETH price of the asset
function getPriceETH(address baseAsset) external view returns (uint256);
}
// File libraries/AddressProviderMeta.sol
pragma solidity 0.8.9;
library AddressProviderMeta {
struct Meta {
bool freezable;
bool frozen;
}
function fromUInt(uint256 value) internal pure returns (Meta memory) {
Meta memory meta;
meta.freezable = (value & 1) == 1;
meta.frozen = ((value >> 1) & 1) == 1;
return meta;
}
function toUInt(Meta memory meta) internal pure returns (uint256) {
uint256 value;
value |= meta.freezable ? 1 : 0;
value |= meta.frozen ? 1 << 1 : 0;
return value;
}
}
// File interfaces/IAddressProvider.sol
pragma solidity 0.8.9;
// solhint-disable ordering
interface IAddressProvider is IPreparable {
event KnownAddressKeyAdded(bytes32 indexed key);
event StakerVaultListed(address indexed stakerVault);
event StakerVaultDelisted(address indexed stakerVault);
event ActionListed(address indexed action);
event PoolListed(address indexed pool);
event PoolDelisted(address indexed pool);
event VaultUpdated(address indexed previousVault, address indexed newVault);
/** Key functions */
function getKnownAddressKeys() external view returns (bytes32[] memory);
function freezeAddress(bytes32 key) external;
/** Pool functions */
function allPools() external view returns (address[] memory);
function addPool(address pool) external;
function poolsCount() external view returns (uint256);
function getPoolAtIndex(uint256 index) external view returns (address);
function isPool(address pool) external view returns (bool);
function removePool(address pool) external returns (bool);
function getPoolForToken(address token) external view returns (ILiquidityPool);
function safeGetPoolForToken(address token) external view returns (address);
/** Vault functions */
function updateVault(address previousVault, address newVault) external;
function allVaults() external view returns (address[] memory);
function vaultsCount() external view returns (uint256);
function getVaultAtIndex(uint256 index) external view returns (address);
function isVault(address vault) external view returns (bool);
/** Action functions */
function allActions() external view returns (address[] memory);
function addAction(address action) external returns (bool);
function isAction(address action) external view returns (bool);
/** Address functions */
function initializeAddress(
bytes32 key,
address initialAddress,
bool frezable
) external;
function initializeAndFreezeAddress(bytes32 key, address initialAddress) external;
function getAddress(bytes32 key) external view returns (address);
function getAddress(bytes32 key, bool checkExists) external view returns (address);
function getAddressMeta(bytes32 key) external view returns (AddressProviderMeta.Meta memory);
function prepareAddress(bytes32 key, address newAddress) external returns (bool);
function executeAddress(bytes32 key) external returns (address);
function resetAddress(bytes32 key) external returns (bool);
/** Staker vault functions */
function allStakerVaults() external view returns (address[] memory);
function tryGetStakerVault(address token) external view returns (bool, address);
function getStakerVault(address token) external view returns (address);
function addStakerVault(address stakerVault) external returns (bool);
function isStakerVault(address stakerVault, address token) external view returns (bool);
function isStakerVaultRegistered(address stakerVault) external view returns (bool);
function isWhiteListedFeeHandler(address feeHandler) external view returns (bool);
}
// File interfaces/tokenomics/IInflationManager.sol
pragma solidity 0.8.9;
interface IInflationManager {
event KeeperGaugeListed(address indexed pool, address indexed keeperGauge);
event AmmGaugeListed(address indexed token, address indexed ammGauge);
event KeeperGaugeDelisted(address indexed pool, address indexed keeperGauge);
event AmmGaugeDelisted(address indexed token, address indexed ammGauge);
/** Pool functions */
function setKeeperGauge(address pool, address _keeperGauge) external returns (bool);
function setAmmGauge(address token, address _ammGauge) external returns (bool);
function getAllAmmGauges() external view returns (address[] memory);
function getLpRateForStakerVault(address stakerVault) external view returns (uint256);
function getKeeperRateForPool(address pool) external view returns (uint256);
function getAmmRateForToken(address token) external view returns (uint256);
function getKeeperWeightForPool(address pool) external view returns (uint256);
function getAmmWeightForToken(address pool) external view returns (uint256);
function getLpPoolWeight(address pool) external view returns (uint256);
function getKeeperGaugeForPool(address pool) external view returns (address);
function getAmmGaugeForToken(address token) external view returns (address);
function isInflationWeightManager(address account) external view returns (bool);
function removeStakerVaultFromInflation(address stakerVault, address lpToken) external;
function addGaugeForVault(address lpToken) external returns (bool);
function whitelistGauge(address gauge) external;
function checkpointAllGauges() external returns (bool);
function mintRewards(address beneficiary, uint256 amount) external;
function addStrategyToDepositStakerVault(address depositStakerVault, address strategyPool)
external
returns (bool);
/** Weight setter functions **/
function prepareLpPoolWeight(address lpToken, uint256 newPoolWeight) external returns (bool);
function prepareAmmTokenWeight(address token, uint256 newTokenWeight) external returns (bool);
function prepareKeeperPoolWeight(address pool, uint256 newPoolWeight) external returns (bool);
function executeLpPoolWeight(address lpToken) external returns (uint256);
function executeAmmTokenWeight(address token) external returns (uint256);
function executeKeeperPoolWeight(address pool) external returns (uint256);
function batchPrepareLpPoolWeights(address[] calldata lpTokens, uint256[] calldata weights)
external
returns (bool);
function batchPrepareAmmTokenWeights(address[] calldata tokens, uint256[] calldata weights)
external
returns (bool);
function batchPrepareKeeperPoolWeights(address[] calldata pools, uint256[] calldata weights)
external
returns (bool);
function batchExecuteLpPoolWeights(address[] calldata lpTokens) external returns (bool);
function batchExecuteAmmTokenWeights(address[] calldata tokens) external returns (bool);
function batchExecuteKeeperPoolWeights(address[] calldata pools) external returns (bool);
}
// File interfaces/IController.sol
pragma solidity 0.8.9;
// solhint-disable ordering
interface IController is IPreparable {
function addressProvider() external view returns (IAddressProvider);
function inflationManager() external view returns (IInflationManager);
function addStakerVault(address stakerVault) external returns (bool);
function removePool(address pool) external returns (bool);
/** Keeper functions */
function prepareKeeperRequiredStakedBKD(uint256 amount) external;
function executeKeeperRequiredStakedBKD() external;
function getKeeperRequiredStakedBKD() external view returns (uint256);
function canKeeperExecuteAction(address keeper) external view returns (bool);
/** Miscellaneous functions */
function getTotalEthRequiredForGas(address payer) external view returns (uint256);
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected]
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File interfaces/ILpToken.sol
pragma solidity 0.8.9;
interface ILpToken is IERC20Upgradeable {
function mint(address account, uint256 lpTokens) external;
function burn(address account, uint256 burnAmount) external returns (uint256);
function burn(uint256 burnAmount) external;
function minter() external view returns (address);
function initialize(
string memory name_,
string memory symbol_,
uint8 _decimals,
address _minter
) external returns (bool);
}
// File interfaces/IStakerVault.sol
pragma solidity 0.8.9;
interface IStakerVault {
event Staked(address indexed account, uint256 amount);
event Unstaked(address indexed account, uint256 amount);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function initialize(address _token) external;
function initializeLpGauge(address _lpGauge) external returns (bool);
function stake(uint256 amount) external returns (bool);
function stakeFor(address account, uint256 amount) external returns (bool);
function unstake(uint256 amount) external returns (bool);
function unstakeFor(
address src,
address dst,
uint256 amount
) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function transfer(address account, uint256 amount) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 amount
) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function getToken() external view returns (address);
function balanceOf(address account) external view returns (uint256);
function stakedAndActionLockedBalanceOf(address account) external view returns (uint256);
function actionLockedBalanceOf(address account) external view returns (uint256);
function increaseActionLockedBalance(address account, uint256 amount) external returns (bool);
function decreaseActionLockedBalance(address account, uint256 amount) external returns (bool);
function getStakedByActions() external view returns (uint256);
function addStrategy(address strategy) external returns (bool);
function getPoolTotalStaked() external view returns (uint256);
function prepareLpGauge(address _lpGauge) external returns (bool);
function executeLpGauge() external returns (bool);
function getLpGauge() external view returns (address);
function poolCheckpoint() external returns (bool);
function isStrategy(address user) external view returns (bool);
}
// File interfaces/IVaultReserve.sol
pragma solidity 0.8.9;
interface IVaultReserve {
event Deposit(address indexed vault, address indexed token, uint256 amount);
event Withdraw(address indexed vault, address indexed token, uint256 amount);
event VaultListed(address indexed vault);
function deposit(address token, uint256 amount) external payable returns (bool);
function withdraw(address token, uint256 amount) external returns (bool);
function getBalance(address vault, address token) external view returns (uint256);
function canWithdraw(address vault) external view returns (bool);
}
// File interfaces/IRoleManager.sol
pragma solidity 0.8.9;
interface IRoleManager {
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function hasRole(bytes32 role, address account) external view returns (bool);
function hasAnyRole(bytes32[] memory roles, address account) external view returns (bool);
function hasAnyRole(
bytes32 role1,
bytes32 role2,
address account
) external view returns (bool);
function hasAnyRole(
bytes32 role1,
bytes32 role2,
bytes32 role3,
address account
) external view returns (bool);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
}
// File interfaces/tokenomics/IBkdToken.sol
pragma solidity 0.8.9;
interface IBkdToken is IERC20 {
function mint(address account, uint256 amount) external;
}
// File libraries/AddressProviderKeys.sol
pragma solidity 0.8.9;
library AddressProviderKeys {
bytes32 internal constant _TREASURY_KEY = "treasury";
bytes32 internal constant _GAS_BANK_KEY = "gasBank";
bytes32 internal constant _VAULT_RESERVE_KEY = "vaultReserve";
bytes32 internal constant _SWAPPER_REGISTRY_KEY = "swapperRegistry";
bytes32 internal constant _ORACLE_PROVIDER_KEY = "oracleProvider";
bytes32 internal constant _POOL_FACTORY_KEY = "poolFactory";
bytes32 internal constant _CONTROLLER_KEY = "controller";
bytes32 internal constant _BKD_LOCKER_KEY = "bkdLocker";
bytes32 internal constant _ROLE_MANAGER_KEY = "roleManager";
}
// File libraries/AddressProviderHelpers.sol
pragma solidity 0.8.9;
library AddressProviderHelpers {
/**
* @return The address of the treasury.
*/
function getTreasury(IAddressProvider provider) internal view returns (address) {
return provider.getAddress(AddressProviderKeys._TREASURY_KEY);
}
/**
* @return The gas bank.
*/
function getGasBank(IAddressProvider provider) internal view returns (IGasBank) {
return IGasBank(provider.getAddress(AddressProviderKeys._GAS_BANK_KEY));
}
/**
* @return The address of the vault reserve.
*/
function getVaultReserve(IAddressProvider provider) internal view returns (IVaultReserve) {
return IVaultReserve(provider.getAddress(AddressProviderKeys._VAULT_RESERVE_KEY));
}
/**
* @return The address of the swapperRegistry.
*/
function getSwapperRegistry(IAddressProvider provider) internal view returns (address) {
return provider.getAddress(AddressProviderKeys._SWAPPER_REGISTRY_KEY);
}
/**
* @return The oracleProvider.
*/
function getOracleProvider(IAddressProvider provider) internal view returns (IOracleProvider) {
return IOracleProvider(provider.getAddress(AddressProviderKeys._ORACLE_PROVIDER_KEY));
}
/**
* @return the address of the BKD locker
*/
function getBKDLocker(IAddressProvider provider) internal view returns (address) {
return provider.getAddress(AddressProviderKeys._BKD_LOCKER_KEY);
}
/**
* @return the address of the BKD locker
*/
function getRoleManager(IAddressProvider provider) internal view returns (IRoleManager) {
return IRoleManager(provider.getAddress(AddressProviderKeys._ROLE_MANAGER_KEY));
}
/**
* @return the controller
*/
function getController(IAddressProvider provider) internal view returns (IController) {
return IController(provider.getAddress(AddressProviderKeys._CONTROLLER_KEY));
}
}
// File libraries/Errors.sol
pragma solidity 0.8.9;
// solhint-disable private-vars-leading-underscore
library Error {
string internal constant ADDRESS_WHITELISTED = "address already whitelisted";
string internal constant ADMIN_ALREADY_SET = "admin has already been set once";
string internal constant ADDRESS_NOT_WHITELISTED = "address not whitelisted";
string internal constant ADDRESS_NOT_FOUND = "address not found";
string internal constant CONTRACT_INITIALIZED = "contract can only be initialized once";
string internal constant CONTRACT_PAUSED = "contract is paused";
string internal constant INVALID_AMOUNT = "invalid amount";
string internal constant INVALID_INDEX = "invalid index";
string internal constant INVALID_VALUE = "invalid msg.value";
string internal constant INVALID_SENDER = "invalid msg.sender";
string internal constant INVALID_TOKEN = "token address does not match pool's LP token address";
string internal constant INVALID_DECIMALS = "incorrect number of decimals";
string internal constant INVALID_ARGUMENT = "invalid argument";
string internal constant INVALID_PARAMETER_VALUE = "invalid parameter value attempted";
string internal constant INVALID_IMPLEMENTATION = "invalid pool implementation for given coin";
string internal constant INVALID_POOL_IMPLEMENTATION =
"invalid pool implementation for given coin";
string internal constant INVALID_LP_TOKEN_IMPLEMENTATION =
"invalid LP Token implementation for given coin";
string internal constant INVALID_VAULT_IMPLEMENTATION =
"invalid vault implementation for given coin";
string internal constant INVALID_STAKER_VAULT_IMPLEMENTATION =
"invalid stakerVault implementation for given coin";
string internal constant INSUFFICIENT_BALANCE = "insufficient balance";
string internal constant ADDRESS_ALREADY_SET = "Address is already set";
string internal constant INSUFFICIENT_STRATEGY_BALANCE = "insufficient strategy balance";
string internal constant INSUFFICIENT_FUNDS_RECEIVED = "insufficient funds received";
string internal constant ADDRESS_DOES_NOT_EXIST = "address does not exist";
string internal constant ADDRESS_FROZEN = "address is frozen";
string internal constant ROLE_EXISTS = "role already exists";
string internal constant CANNOT_REVOKE_ROLE = "cannot revoke role";
string internal constant UNAUTHORIZED_ACCESS = "unauthorized access";
string internal constant SAME_ADDRESS_NOT_ALLOWED = "same address not allowed";
string internal constant SELF_TRANSFER_NOT_ALLOWED = "self-transfer not allowed";
string internal constant ZERO_ADDRESS_NOT_ALLOWED = "zero address not allowed";
string internal constant ZERO_TRANSFER_NOT_ALLOWED = "zero transfer not allowed";
string internal constant THRESHOLD_TOO_HIGH = "threshold is too high, must be under 10";
string internal constant INSUFFICIENT_THRESHOLD = "insufficient threshold";
string internal constant NO_POSITION_EXISTS = "no position exists";
string internal constant POSITION_ALREADY_EXISTS = "position already exists";
string internal constant PROTOCOL_NOT_FOUND = "protocol not found";
string internal constant TOP_UP_FAILED = "top up failed";
string internal constant SWAP_PATH_NOT_FOUND = "swap path not found";
string internal constant UNDERLYING_NOT_SUPPORTED = "underlying token not supported";
string internal constant NOT_ENOUGH_FUNDS_WITHDRAWN =
"not enough funds were withdrawn from the pool";
string internal constant FAILED_TRANSFER = "transfer failed";
string internal constant FAILED_MINT = "mint failed";
string internal constant FAILED_REPAY_BORROW = "repay borrow failed";
string internal constant FAILED_METHOD_CALL = "method call failed";
string internal constant NOTHING_TO_CLAIM = "there is no claimable balance";
string internal constant ERC20_BALANCE_EXCEEDED = "ERC20: transfer amount exceeds balance";
string internal constant INVALID_MINTER =
"the minter address of the LP token and the pool address do not match";
string internal constant STAKER_VAULT_EXISTS = "a staker vault already exists for the token";
string internal constant DEADLINE_NOT_ZERO = "deadline must be 0";
string internal constant DEADLINE_NOT_SET = "deadline is 0";
string internal constant DEADLINE_NOT_REACHED = "deadline has not been reached yet";
string internal constant DELAY_TOO_SHORT = "delay be at least 3 days";
string internal constant INSUFFICIENT_UPDATE_BALANCE =
"insufficient funds for updating the position";
string internal constant SAME_AS_CURRENT = "value must be different to existing value";
string internal constant NOT_CAPPED = "the pool is not currently capped";
string internal constant ALREADY_CAPPED = "the pool is already capped";
string internal constant EXCEEDS_DEPOSIT_CAP = "deposit exceeds deposit cap";
string internal constant VALUE_TOO_LOW_FOR_GAS = "value too low to cover gas";
string internal constant NOT_ENOUGH_FUNDS = "not enough funds to withdraw";
string internal constant ESTIMATED_GAS_TOO_HIGH = "too much ETH will be used for gas";
string internal constant DEPOSIT_FAILED = "deposit failed";
string internal constant GAS_TOO_HIGH = "too much ETH used for gas";
string internal constant GAS_BANK_BALANCE_TOO_LOW = "not enough ETH in gas bank to cover gas";
string internal constant INVALID_TOKEN_TO_ADD = "Invalid token to add";
string internal constant INVALID_TOKEN_TO_REMOVE = "token can not be removed";
string internal constant TIME_DELAY_NOT_EXPIRED = "time delay not expired yet";
string internal constant UNDERLYING_NOT_WITHDRAWABLE =
"pool does not support additional underlying coins to be withdrawn";
string internal constant STRATEGY_SHUT_DOWN = "Strategy is shut down";
string internal constant STRATEGY_DOES_NOT_EXIST = "Strategy does not exist";
string internal constant UNSUPPORTED_UNDERLYING = "Underlying not supported";
string internal constant NO_DEX_SET = "no dex has been set for token";
string internal constant INVALID_TOKEN_PAIR = "invalid token pair";
string internal constant TOKEN_NOT_USABLE = "token not usable for the specific action";
string internal constant ADDRESS_NOT_ACTION = "address is not registered action";
string internal constant INVALID_SLIPPAGE_TOLERANCE = "Invalid slippage tolerance";
string internal constant POOL_NOT_PAUSED = "Pool must be paused to withdraw from reserve";
string internal constant INTERACTION_LIMIT = "Max of one deposit and withdraw per block";
string internal constant GAUGE_EXISTS = "Gauge already exists";
string internal constant GAUGE_DOES_NOT_EXIST = "Gauge does not exist";
string internal constant EXCEEDS_MAX_BOOST = "Not allowed to exceed maximum boost on Convex";
string internal constant PREPARED_WITHDRAWAL =
"Cannot relock funds when withdrawal is being prepared";
string internal constant ASSET_NOT_SUPPORTED = "Asset not supported";
string internal constant STALE_PRICE = "Price is stale";
string internal constant NEGATIVE_PRICE = "Price is negative";
string internal constant NOT_ENOUGH_BKD_STAKED = "Not enough BKD tokens staked";
string internal constant RESERVE_ACCESS_EXCEEDED = "Reserve access exceeded";
}
// File libraries/ScaledMath.sol
pragma solidity 0.8.9;
/*
* @dev To use functions of this contract, at least one of the numbers must
* be scaled to `DECIMAL_SCALE`. The result will scaled to `DECIMAL_SCALE`
* if both numbers are scaled to `DECIMAL_SCALE`, otherwise to the scale
* of the number not scaled by `DECIMAL_SCALE`
*/
library ScaledMath {
// solhint-disable-next-line private-vars-leading-underscore
uint256 internal constant DECIMAL_SCALE = 1e18;
// solhint-disable-next-line private-vars-leading-underscore
uint256 internal constant ONE = 1e18;
/**
* @notice Performs a multiplication between two scaled numbers
*/
function scaledMul(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * b) / DECIMAL_SCALE;
}
/**
* @notice Performs a division between two scaled numbers
*/
function scaledDiv(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * DECIMAL_SCALE) / b;
}
/**
* @notice Performs a division between two numbers, rounding up the result
*/
function scaledDivRoundUp(uint256 a, uint256 b) internal pure returns (uint256) {
return (a * DECIMAL_SCALE + b - 1) / b;
}
/**
* @notice Performs a division between two numbers, ignoring any scaling and rounding up the result
*/
function divRoundUp(uint256 a, uint256 b) internal pure returns (uint256) {
return (a + b - 1) / b;
}
}
// File libraries/Roles.sol
pragma solidity 0.8.9;
// solhint-disable private-vars-leading-underscore
library Roles {
bytes32 internal constant GOVERNANCE = "governance";
bytes32 internal constant ADDRESS_PROVIDER = "address_provider";
bytes32 internal constant POOL_FACTORY = "pool_factory";
bytes32 internal constant CONTROLLER = "controller";
bytes32 internal constant GAUGE_ZAP = "gauge_zap";
bytes32 internal constant MAINTENANCE = "maintenance";
bytes32 internal constant INFLATION_MANAGER = "inflation_manager";
bytes32 internal constant POOL = "pool";
bytes32 internal constant VAULT = "vault";
}
// File contracts/access/AuthorizationBase.sol
pragma solidity 0.8.9;
/**
* @notice Provides modifiers for authorization
*/
abstract contract AuthorizationBase {
/**
* @notice Only allows a sender with `role` to perform the given action
*/
modifier onlyRole(bytes32 role) {
require(_roleManager().hasRole(role, msg.sender), Error.UNAUTHORIZED_ACCESS);
_;
}
/**
* @notice Only allows a sender with GOVERNANCE role to perform the given action
*/
modifier onlyGovernance() {
require(_roleManager().hasRole(Roles.GOVERNANCE, msg.sender), Error.UNAUTHORIZED_ACCESS);
_;
}
/**
* @notice Only allows a sender with any of `roles` to perform the given action
*/
modifier onlyRoles2(bytes32 role1, bytes32 role2) {
require(_roleManager().hasAnyRole(role1, role2, msg.sender), Error.UNAUTHORIZED_ACCESS);
_;
}
/**
* @notice Only allows a sender with any of `roles` to perform the given action
*/
modifier onlyRoles3(
bytes32 role1,
bytes32 role2,
bytes32 role3
) {
require(
_roleManager().hasAnyRole(role1, role2, role3, msg.sender),
Error.UNAUTHORIZED_ACCESS
);
_;
}
function roleManager() external view virtual returns (IRoleManager) {
return _roleManager();
}
function _roleManager() internal view virtual returns (IRoleManager);
}
// File contracts/access/Authorization.sol
pragma solidity 0.8.9;
contract Authorization is AuthorizationBase {
IRoleManager internal immutable __roleManager;
constructor(IRoleManager roleManager) {
__roleManager = roleManager;
}
function _roleManager() internal view override returns (IRoleManager) {
return __roleManager;
}
}
// File contracts/utils/Preparable.sol
pragma solidity 0.8.9;
/**
* @notice Implements the base logic for a two-phase commit
* @dev This does not implements any access-control so publicly exposed
* callers should make sure to have the proper checks in palce
*/
contract Preparable is IPreparable {
uint256 private constant _MIN_DELAY = 3 days;
mapping(bytes32 => address) public pendingAddresses;
mapping(bytes32 => uint256) public pendingUInts256;
mapping(bytes32 => address) public currentAddresses;
mapping(bytes32 => uint256) public currentUInts256;
/**
* @dev Deadlines shares the same namespace regardless of the type
* of the pending variable so this needs to be enforced in the caller
*/
mapping(bytes32 => uint256) public deadlines;
function _prepareDeadline(bytes32 key, uint256 delay) internal {
require(deadlines[key] == 0, Error.DEADLINE_NOT_ZERO);
require(delay >= _MIN_DELAY, Error.DELAY_TOO_SHORT);
deadlines[key] = block.timestamp + delay;
}
/**
* @notice Prepares an uint256 that should be commited to the contract
* after `_MIN_DELAY` elapsed
* @param value The value to prepare
* @return `true` if success.
*/
function _prepare(
bytes32 key,
uint256 value,
uint256 delay
) internal returns (bool) {
_prepareDeadline(key, delay);
pendingUInts256[key] = value;
emit ConfigPreparedNumber(key, value, delay);
return true;
}
/**
* @notice Same as `_prepare(bytes32,uint256,uint256)` but uses a default delay
*/
function _prepare(bytes32 key, uint256 value) internal returns (bool) {
return _prepare(key, value, _MIN_DELAY);
}
/**
* @notice Prepares an address that should be commited to the contract
* after `_MIN_DELAY` elapsed
* @param value The value to prepare
* @return `true` if success.
*/
function _prepare(
bytes32 key,
address value,
uint256 delay
) internal returns (bool) {
_prepareDeadline(key, delay);
pendingAddresses[key] = value;
emit ConfigPreparedAddress(key, value, delay);
return true;
}
/**
* @notice Same as `_prepare(bytes32,address,uint256)` but uses a default delay
*/
function _prepare(bytes32 key, address value) internal returns (bool) {
return _prepare(key, value, _MIN_DELAY);
}
/**
* @notice Reset a uint256 key
* @return `true` if success.
*/
function _resetUInt256Config(bytes32 key) internal returns (bool) {
require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO);
deadlines[key] = 0;
pendingUInts256[key] = 0;
emit ConfigReset(key);
return true;
}
/**
* @notice Reset an address key
* @return `true` if success.
*/
function _resetAddressConfig(bytes32 key) internal returns (bool) {
require(deadlines[key] != 0, Error.DEADLINE_NOT_ZERO);
deadlines[key] = 0;
pendingAddresses[key] = address(0);
emit ConfigReset(key);
return true;
}
/**
* @dev Checks the deadline of the key and reset it
*/
function _executeDeadline(bytes32 key) internal {
uint256 deadline = deadlines[key];
require(block.timestamp >= deadline, Error.DEADLINE_NOT_REACHED);
require(deadline != 0, Error.DEADLINE_NOT_SET);
deadlines[key] = 0;
}
/**
* @notice Execute uint256 config update (with time delay enforced).
* @dev Needs to be called after the update was prepared. Fails if called before time delay is met.
* @return New value.
*/
function _executeUInt256(bytes32 key) internal returns (uint256) {
_executeDeadline(key);
uint256 newValue = pendingUInts256[key];
_setConfig(key, newValue);
return newValue;
}
/**
* @notice Execute address config update (with time delay enforced).
* @dev Needs to be called after the update was prepared. Fails if called before time delay is met.
* @return New value.
*/
function _executeAddress(bytes32 key) internal returns (address) {
_executeDeadline(key);
address newValue = pendingAddresses[key];
_setConfig(key, newValue);
return newValue;
}
function _setConfig(bytes32 key, address value) internal returns (address) {
address oldValue = currentAddresses[key];
currentAddresses[key] = value;
pendingAddresses[key] = address(0);
deadlines[key] = 0;
emit ConfigUpdatedAddress(key, oldValue, value);
return value;
}
function _setConfig(bytes32 key, uint256 value) internal returns (uint256) {
uint256 oldValue = currentUInts256[key];
currentUInts256[key] = value;
pendingUInts256[key] = 0;
deadlines[key] = 0;
emit ConfigUpdatedNumber(key, oldValue, value);
return value;
}
}
// File contracts/utils/Pausable.sol
pragma solidity 0.8.9;
abstract contract Pausable {
bool public isPaused;
modifier notPaused() {
require(!isPaused, Error.CONTRACT_PAUSED);
_;
}
modifier onlyAuthorizedToPause() {
require(_isAuthorizedToPause(msg.sender), Error.CONTRACT_PAUSED);
_;
}
/**
* @notice Pause the contract.
* @return `true` if success.
*/
function pause() external onlyAuthorizedToPause returns (bool) {
isPaused = true;
return true;
}
/**
* @notice Unpause the contract.
* @return `true` if success.
*/
function unpause() external onlyAuthorizedToPause returns (bool) {
isPaused = false;
return true;
}
/**
* @notice Returns true if `account` is authorized to pause the contract
* @dev This should be implemented in contracts inheriting `Pausable`
* to provide proper access control
*/
function _isAuthorizedToPause(address account) internal view virtual returns (bool);
}
// File contracts/pool/LiquidityPool.sol
pragma solidity 0.8.9;
/**
* @dev Pausing/unpausing the pool will disable/re-enable deposits.
*/
abstract contract LiquidityPool is
ILiquidityPool,
Authorization,
Preparable,
Pausable,
Initializable
{
using AddressProviderHelpers for IAddressProvider;
using ScaledMath for uint256;
using SafeERC20 for IERC20;
struct WithdrawalFeeMeta {
uint64 timeToWait;
uint64 feeRatio;
uint64 lastActionTimestamp;
}
bytes32 internal constant _VAULT_KEY = "Vault";
bytes32 internal constant _RESERVE_DEVIATION_KEY = "ReserveDeviation";
bytes32 internal constant _REQUIRED_RESERVES_KEY = "RequiredReserves";
bytes32 internal constant _MAX_WITHDRAWAL_FEE_KEY = "MaxWithdrawalFee";
bytes32 internal constant _MIN_WITHDRAWAL_FEE_KEY = "MinWithdrawalFee";
bytes32 internal constant _WITHDRAWAL_FEE_DECREASE_PERIOD_KEY = "WithdrawalFeeDecreasePeriod";
uint256 internal constant _INITIAL_RESERVE_DEVIATION = 0.005e18; // 0.5%
uint256 internal constant _INITIAL_FEE_DECREASE_PERIOD = 1 weeks;
uint256 internal constant _INITIAL_MAX_WITHDRAWAL_FEE = 0.03e18; // 3%
/**
* @notice even through admin votes and later governance, the withdrawal
* fee will never be able to go above this value
*/
uint256 internal constant _MAX_WITHDRAWAL_FEE = 0.05e18;
/**
* @notice Keeps track of the withdrawal fees on a per-address basis
*/
mapping(address => WithdrawalFeeMeta) public withdrawalFeeMetas;
IController public immutable controller;
IAddressProvider public immutable addressProvider;
uint256 public depositCap;
IStakerVault public staker;
ILpToken public lpToken;
string public name;
constructor(IController _controller)
Authorization(_controller.addressProvider().getRoleManager())
{
require(address(_controller) != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED);
controller = IController(_controller);
addressProvider = IController(_controller).addressProvider();
}
/**
* @notice Deposit funds into liquidity pool and mint LP tokens in exchange.
* @param depositAmount Amount of the underlying asset to supply.
* @return The actual amount minted.
*/
function deposit(uint256 depositAmount) external payable override returns (uint256) {
return depositFor(msg.sender, depositAmount, 0);
}
/**
* @notice Deposit funds into liquidity pool and mint LP tokens in exchange.
* @param depositAmount Amount of the underlying asset to supply.
* @param minTokenAmount Minimum amount of LP tokens that should be minted.
* @return The actual amount minted.
*/
function deposit(uint256 depositAmount, uint256 minTokenAmount)
external
payable
override
returns (uint256)
{
return depositFor(msg.sender, depositAmount, minTokenAmount);
}
/**
* @notice Deposit funds into liquidity pool and stake LP Tokens in Staker Vault.
* @param depositAmount Amount of the underlying asset to supply.
* @param minTokenAmount Minimum amount of LP tokens that should be minted.
* @return The actual amount minted and staked.
*/
function depositAndStake(uint256 depositAmount, uint256 minTokenAmount)
external
payable
override
returns (uint256)
{
uint256 amountMinted_ = depositFor(address(this), depositAmount, minTokenAmount);
staker.stakeFor(msg.sender, amountMinted_);
return amountMinted_;
}
/**
* @notice Withdraws all funds from vault.
* @dev Should be called in case of emergencies.
*/
function withdrawAll() external onlyGovernance {
getVault().withdrawAll();
}
function setLpToken(address _lpToken)
external
override
onlyRoles2(Roles.GOVERNANCE, Roles.POOL_FACTORY)
returns (bool)
{
require(address(lpToken) == address(0), Error.ADDRESS_ALREADY_SET);
require(ILpToken(_lpToken).minter() == address(this), Error.INVALID_MINTER);
lpToken = ILpToken(_lpToken);
_approveStakerVaultSpendingLpTokens();
emit LpTokenSet(_lpToken);
return true;
}
/**
* @notice Checkpoint function to update a user's withdrawal fees on deposit and redeem
* @param from Address sending from
* @param to Address sending to
* @param amount Amount to redeem or deposit
*/
function handleLpTokenTransfer(
address from,
address to,
uint256 amount
) external override {
require(
msg.sender == address(lpToken) || msg.sender == address(staker),
Error.UNAUTHORIZED_ACCESS
);
if (
addressProvider.isStakerVault(to, address(lpToken)) ||
addressProvider.isStakerVault(from, address(lpToken)) ||
addressProvider.isAction(to) ||
addressProvider.isAction(from)
) {
return;
}
if (to != address(0)) {
_updateUserFeesOnDeposit(to, from, amount);
}
}
/**
* @notice Prepare update of required reserve ratio (with time delay enforced).
* @param _newRatio New required reserve ratio.
* @return `true` if success.
*/
function prepareNewRequiredReserves(uint256 _newRatio) external onlyGovernance returns (bool) {
require(_newRatio <= ScaledMath.ONE, Error.INVALID_AMOUNT);
return _prepare(_REQUIRED_RESERVES_KEY, _newRatio);
}
/**
* @notice Execute required reserve ratio update (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return New required reserve ratio.
*/
function executeNewRequiredReserves() external override returns (uint256) {
uint256 requiredReserveRatio = _executeUInt256(_REQUIRED_RESERVES_KEY);
_rebalanceVault();
return requiredReserveRatio;
}
/**
* @notice Reset the prepared required reserves.
* @return `true` if success.
*/
function resetRequiredReserves() external onlyGovernance returns (bool) {
return _resetUInt256Config(_REQUIRED_RESERVES_KEY);
}
/**
* @notice Prepare update of reserve deviation ratio (with time delay enforced).
* @param newRatio New reserve deviation ratio.
* @return `true` if success.
*/
function prepareNewReserveDeviation(uint256 newRatio) external onlyGovernance returns (bool) {
require(newRatio <= (ScaledMath.DECIMAL_SCALE * 50) / 100, Error.INVALID_AMOUNT);
return _prepare(_RESERVE_DEVIATION_KEY, newRatio);
}
/**
* @notice Execute reserve deviation ratio update (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return New reserve deviation ratio.
*/
function executeNewReserveDeviation() external override returns (uint256) {
uint256 reserveDeviation = _executeUInt256(_RESERVE_DEVIATION_KEY);
_rebalanceVault();
return reserveDeviation;
}
/**
* @notice Reset the prepared reserve deviation.
* @return `true` if success.
*/
function resetNewReserveDeviation() external onlyGovernance returns (bool) {
return _resetUInt256Config(_RESERVE_DEVIATION_KEY);
}
/**
* @notice Prepare update of min withdrawal fee (with time delay enforced).
* @param newFee New min withdrawal fee.
* @return `true` if success.
*/
function prepareNewMinWithdrawalFee(uint256 newFee) external onlyGovernance returns (bool) {
_checkFeeInvariants(newFee, getMaxWithdrawalFee());
return _prepare(_MIN_WITHDRAWAL_FEE_KEY, newFee);
}
/**
* @notice Execute min withdrawal fee update (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return New withdrawal fee.
*/
function executeNewMinWithdrawalFee() external returns (uint256) {
uint256 newFee = _executeUInt256(_MIN_WITHDRAWAL_FEE_KEY);
_checkFeeInvariants(newFee, getMaxWithdrawalFee());
return newFee;
}
/**
* @notice Reset the prepared min withdrawal fee
* @return `true` if success.
*/
function resetNewMinWithdrawalFee() external onlyGovernance returns (bool) {
return _resetUInt256Config(_MIN_WITHDRAWAL_FEE_KEY);
}
/**
* @notice Prepare update of max withdrawal fee (with time delay enforced).
* @param newFee New max withdrawal fee.
* @return `true` if success.
*/
function prepareNewMaxWithdrawalFee(uint256 newFee) external onlyGovernance returns (bool) {
_checkFeeInvariants(getMinWithdrawalFee(), newFee);
return _prepare(_MAX_WITHDRAWAL_FEE_KEY, newFee);
}
/**
* @notice Execute max withdrawal fee update (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return New max withdrawal fee.
*/
function executeNewMaxWithdrawalFee() external override returns (uint256) {
uint256 newFee = _executeUInt256(_MAX_WITHDRAWAL_FEE_KEY);
_checkFeeInvariants(getMinWithdrawalFee(), newFee);
return newFee;
}
/**
* @notice Reset the prepared max fee.
* @return `true` if success.
*/
function resetNewMaxWithdrawalFee() external onlyGovernance returns (bool) {
return _resetUInt256Config(_MAX_WITHDRAWAL_FEE_KEY);
}
/**
* @notice Prepare update of withdrawal decrease fee period (with time delay enforced).
* @param newPeriod New withdrawal fee decrease period.
* @return `true` if success.
*/
function prepareNewWithdrawalFeeDecreasePeriod(uint256 newPeriod)
external
onlyGovernance
returns (bool)
{
return _prepare(_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY, newPeriod);
}
/**
* @notice Execute withdrawal fee decrease period update (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return New withdrawal fee decrease period.
*/
function executeNewWithdrawalFeeDecreasePeriod() external returns (uint256) {
return _executeUInt256(_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY);
}
/**
* @notice Reset the prepared withdrawal fee decrease period update.
* @return `true` if success.
*/
function resetNewWithdrawalFeeDecreasePeriod() external onlyGovernance returns (bool) {
return _resetUInt256Config(_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY);
}
/**
* @notice Set the staker vault for this pool's LP token
* @dev Staker vault and LP token pairs are immutable and the staker vault can only be set once for a pool.
* Only one vault exists per LP token. This information will be retrieved from the controller of the pool.
* @return Address of the new staker vault for the pool.
*/
function setStaker()
external
override
onlyRoles2(Roles.GOVERNANCE, Roles.POOL_FACTORY)
returns (bool)
{
require(address(staker) == address(0), Error.ADDRESS_ALREADY_SET);
address stakerVault = addressProvider.getStakerVault(address(lpToken));
require(stakerVault != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED);
staker = IStakerVault(stakerVault);
_approveStakerVaultSpendingLpTokens();
emit StakerVaultSet(stakerVault);
return true;
}
/**
* @notice Prepare setting a new Vault (with time delay enforced).
* @param _vault Address of new Vault contract.
* @return `true` if success.
*/
function prepareNewVault(address _vault) external onlyGovernance returns (bool) {
_prepare(_VAULT_KEY, _vault);
return true;
}
/**
* @notice Execute Vault update (with time delay enforced).
* @dev Needs to be called after the update was prepraed. Fails if called before time delay is met.
* @return Address of new Vault contract.
*/
function executeNewVault() external override returns (address) {
IVault vault = getVault();
if (address(vault) != address(0)) {
vault.withdrawAll();
}
address newVault = _executeAddress(_VAULT_KEY);
addressProvider.updateVault(address(vault), newVault);
return newVault;
}
/**
* @notice Reset the vault deadline.
* @return `true` if success.
*/
function resetNewVault() external onlyGovernance returns (bool) {
return _resetAddressConfig(_VAULT_KEY);
}
/**
* @notice Redeems the underlying asset by burning LP tokens.
* @param redeemLpTokens Number of tokens to burn for redeeming the underlying.
* @return Actual amount of the underlying redeemed.
*/
function redeem(uint256 redeemLpTokens) external override returns (uint256) {
return redeem(redeemLpTokens, 0);
}
/**
* @notice Uncap the pool to remove the deposit limit.
* @return `true` if success.
*/
function uncap() external override onlyGovernance returns (bool) {
require(isCapped(), Error.NOT_CAPPED);
depositCap = 0;
return true;
}
/**
* @notice Update the deposit cap value.
* @param _depositCap The maximum allowed deposits per address in the pool
* @return `true` if success.
*/
function updateDepositCap(uint256 _depositCap) external override onlyGovernance returns (bool) {
require(isCapped(), Error.NOT_CAPPED);
require(depositCap != _depositCap, Error.SAME_AS_CURRENT);
require(_depositCap > 0, Error.INVALID_AMOUNT);
depositCap = _depositCap;
return true;
}
/**
* @notice Rebalance vault according to required underlying backing reserves.
*/
function rebalanceVault() external onlyGovernance {
_rebalanceVault();
}
/**
* @notice Deposit funds for an address into liquidity pool and mint LP tokens in exchange.
* @param account Account to deposit for.
* @param depositAmount Amount of the underlying asset to supply.
* @return Actual amount minted.
*/
function depositFor(address account, uint256 depositAmount)
external
payable
override
returns (uint256)
{
return depositFor(account, depositAmount, 0);
}
/**
* @notice Redeems the underlying asset by burning LP tokens, unstaking any LP tokens needed.
* @param redeemLpTokens Number of tokens to unstake and/or burn for redeeming the underlying.
* @param minRedeemAmount Minimum amount of underlying that should be received.
* @return Actual amount of the underlying redeemed.
*/
function unstakeAndRedeem(uint256 redeemLpTokens, uint256 minRedeemAmount)
external
override
returns (uint256)
{
uint256 lpBalance_ = lpToken.balanceOf(msg.sender);
require(
lpBalance_ + staker.balanceOf(msg.sender) >= redeemLpTokens,
Error.INSUFFICIENT_BALANCE
);
if (lpBalance_ < redeemLpTokens) {
staker.unstakeFor(msg.sender, msg.sender, redeemLpTokens - lpBalance_);
}
return redeem(redeemLpTokens, minRedeemAmount);
}
/**
* @notice Returns the address of the LP token of this pool
* @return The address of the LP token
*/
function getLpToken() external view override returns (address) {
return address(lpToken);
}
/**
* @notice Calculates the amount of LP tokens that need to be redeemed to get a certain amount of underlying (includes fees and exchange rate)
* @param account Address of the account redeeming.
* @param underlyingAmount The amount of underlying desired.
* @return Amount of LP tokens that need to be redeemed.
*/
function calcRedeem(address account, uint256 underlyingAmount)
external
view
override
returns (uint256)
{
require(underlyingAmount > 0, Error.INVALID_AMOUNT);
ILpToken lpToken_ = lpToken;
require(lpToken_.balanceOf(account) > 0, Error.INSUFFICIENT_BALANCE);
uint256 currentExchangeRate = exchangeRate();
uint256 withoutFeesLpAmount = underlyingAmount.scaledDiv(currentExchangeRate);
if (withoutFeesLpAmount == lpToken_.totalSupply()) {
return withoutFeesLpAmount;
}
WithdrawalFeeMeta memory meta = withdrawalFeeMetas[account];
uint256 currentFeeRatio = 0;
if (!addressProvider.isAction(account)) {
currentFeeRatio = getNewCurrentFees(
meta.timeToWait,
meta.lastActionTimestamp,
meta.feeRatio
);
}
uint256 scalingFactor = currentExchangeRate.scaledMul((ScaledMath.ONE - currentFeeRatio));
uint256 neededLpTokens = underlyingAmount.scaledDivRoundUp(scalingFactor);
return neededLpTokens;
}
function getUnderlying() external view virtual override returns (address);
/**
* @notice Deposit funds for an address into liquidity pool and mint LP tokens in exchange.
* @param account Account to deposit for.
* @param depositAmount Amount of the underlying asset to supply.
* @param minTokenAmount Minimum amount of LP tokens that should be minted.
* @return Actual amount minted.
*/
function depositFor(
address account,
uint256 depositAmount,
uint256 minTokenAmount
) public payable override notPaused returns (uint256) {
uint256 rate = exchangeRate();
if (isCapped()) {
uint256 lpBalance = lpToken.balanceOf(account);
uint256 stakedAndLockedBalance = staker.stakedAndActionLockedBalanceOf(account);
uint256 currentUnderlyingBalance = (lpBalance + stakedAndLockedBalance).scaledMul(rate);
require(
currentUnderlyingBalance + depositAmount <= depositCap,
Error.EXCEEDS_DEPOSIT_CAP
);
}
_doTransferIn(msg.sender, depositAmount);
uint256 mintedLp = depositAmount.scaledDiv(rate);
require(mintedLp >= minTokenAmount, Error.INVALID_AMOUNT);
lpToken.mint(account, mintedLp);
_rebalanceVault();
if (msg.sender == account || address(this) == account) {
emit Deposit(msg.sender, depositAmount, mintedLp);
} else {
emit DepositFor(msg.sender, account, depositAmount, mintedLp);
}
return mintedLp;
}
/**
* @notice Redeems the underlying asset by burning LP tokens.
* @param redeemLpTokens Number of tokens to burn for redeeming the underlying.
* @param minRedeemAmount Minimum amount of underlying that should be received.
* @return Actual amount of the underlying redeemed.
*/
function redeem(uint256 redeemLpTokens, uint256 minRedeemAmount)
public
override
returns (uint256)
{
require(redeemLpTokens > 0, Error.INVALID_AMOUNT);
ILpToken lpToken_ = lpToken;
require(lpToken_.balanceOf(msg.sender) >= redeemLpTokens, Error.INSUFFICIENT_BALANCE);
uint256 withdrawalFee = addressProvider.isAction(msg.sender)
? 0
: getWithdrawalFee(msg.sender, redeemLpTokens);
uint256 redeemMinusFees = redeemLpTokens - withdrawalFee;
// Pay no fees on the last withdrawal (avoid locking funds in the pool)
if (redeemLpTokens == lpToken_.totalSupply()) {
redeemMinusFees = redeemLpTokens;
}
uint256 redeemUnderlying = redeemMinusFees.scaledMul(exchangeRate());
require(redeemUnderlying >= minRedeemAmount, Error.NOT_ENOUGH_FUNDS_WITHDRAWN);
_rebalanceVault(redeemUnderlying);
lpToken_.burn(msg.sender, redeemLpTokens);
_doTransferOut(payable(msg.sender), redeemUnderlying);
emit Redeem(msg.sender, redeemUnderlying, redeemLpTokens);
return redeemUnderlying;
}
/**
* @return the current required reserves ratio
*/
function getRequiredReserveRatio() public view virtual returns (uint256) {
return currentUInts256[_REQUIRED_RESERVES_KEY];
}
/**
* @return the current maximum reserve deviation ratio
*/
function getMaxReserveDeviationRatio() public view virtual returns (uint256) {
return currentUInts256[_RESERVE_DEVIATION_KEY];
}
/**
* @notice Returns the current minimum withdrawal fee
*/
function getMinWithdrawalFee() public view returns (uint256) {
return currentUInts256[_MIN_WITHDRAWAL_FEE_KEY];
}
/**
* @notice Returns the current maximum withdrawal fee
*/
function getMaxWithdrawalFee() public view returns (uint256) {
return currentUInts256[_MAX_WITHDRAWAL_FEE_KEY];
}
/**
* @notice Returns the current withdrawal fee decrease period
*/
function getWithdrawalFeeDecreasePeriod() public view returns (uint256) {
return currentUInts256[_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY];
}
/**
* @return the current vault of the liquidity pool
*/
function getVault() public view virtual override returns (IVault) {
return IVault(currentAddresses[_VAULT_KEY]);
}
/**
* @notice Compute current exchange rate of LP tokens to underlying scaled to 1e18.
* @dev Exchange rate means: underlying = LP token * exchangeRate
* @return Current exchange rate.
*/
function exchangeRate() public view override returns (uint256) {
uint256 totalUnderlying_ = totalUnderlying();
uint256 totalSupply = lpToken.totalSupply();
if (totalSupply == 0 || totalUnderlying_ == 0) {
return ScaledMath.ONE;
}
return totalUnderlying_.scaledDiv(totalSupply);
}
/**
* @notice Compute total amount of underlying tokens for this pool.
* @return Total amount of underlying in pool.
*/
function totalUnderlying() public view returns (uint256) {
IVault vault = getVault();
uint256 balanceUnderlying = _getBalanceUnderlying();
if (address(vault) == address(0)) {
return balanceUnderlying;
}
uint256 investedUnderlying = vault.getTotalUnderlying();
return investedUnderlying + balanceUnderlying;
}
/**
* @notice Retuns if the pool has an active deposit limit
* @return `true` if there is currently a deposit limit
*/
function isCapped() public view override returns (bool) {
return depositCap != 0;
}
/**
* @notice Returns the withdrawal fee for `account`
* @param account Address to get the withdrawal fee for
* @param amount Amount to calculate the withdrawal fee for
* @return Withdrawal fee in LP tokens
*/
function getWithdrawalFee(address account, uint256 amount)
public
view
override
returns (uint256)
{
WithdrawalFeeMeta memory meta = withdrawalFeeMetas[account];
if (lpToken.balanceOf(account) == 0) {
return 0;
}
uint256 currentFee = getNewCurrentFees(
meta.timeToWait,
meta.lastActionTimestamp,
meta.feeRatio
);
return amount.scaledMul(currentFee);
}
/**
* @notice Calculates the withdrawal fee a user would currently need to pay on currentBalance.
* @param timeToWait The total time to wait until the withdrawal fee reached the min. fee
* @param lastActionTimestamp Timestamp of the last fee update
* @param feeRatio Fees that would currently be paid on the user's entire balance
* @return Updated fee amount on the currentBalance
*/
function getNewCurrentFees(
uint256 timeToWait,
uint256 lastActionTimestamp,
uint256 feeRatio
) public view returns (uint256) {
uint256 timeElapsed = _getTime() - lastActionTimestamp;
uint256 minFeePercentage = getMinWithdrawalFee();
if (timeElapsed >= timeToWait) {
return minFeePercentage;
}
uint256 elapsedShare = timeElapsed.scaledDiv(timeToWait);
return feeRatio - (feeRatio - minFeePercentage).scaledMul(elapsedShare);
}
function _rebalanceVault() internal {
_rebalanceVault(0);
}
function _initialize(
string memory name_,
uint256 depositCap_,
address vault_
) internal initializer returns (bool) {
name = name_;
depositCap = depositCap_;
_setConfig(_WITHDRAWAL_FEE_DECREASE_PERIOD_KEY, _INITIAL_FEE_DECREASE_PERIOD);
_setConfig(_MAX_WITHDRAWAL_FEE_KEY, _INITIAL_MAX_WITHDRAWAL_FEE);
_setConfig(_REQUIRED_RESERVES_KEY, ScaledMath.ONE);
_setConfig(_RESERVE_DEVIATION_KEY, _INITIAL_RESERVE_DEVIATION);
_setConfig(_VAULT_KEY, vault_);
return true;
}
function _approveStakerVaultSpendingLpTokens() internal {
address staker_ = address(staker);
address lpToken_ = address(lpToken);
if (staker_ == address(0) || lpToken_ == address(0)) return;
IERC20(lpToken_).safeApprove(staker_, type(uint256).max);
}
function _doTransferIn(address from, uint256 amount) internal virtual;
function _doTransferOut(address payable to, uint256 amount) internal virtual;
/**
* @dev Rebalances the pool's allocations to the vault
* @param underlyingToWithdraw Amount of underlying to withdraw such that after the withdrawal the pool and vault allocations are correctly balanced.
*/
function _rebalanceVault(uint256 underlyingToWithdraw) internal {
IVault vault = getVault();
if (address(vault) == address(0)) return;
uint256 lockedLp = staker.getStakedByActions();
uint256 totalUnderlyingStaked = lockedLp.scaledMul(exchangeRate());
uint256 underlyingBalance = _getBalanceUnderlying(true);
uint256 maximumDeviation = totalUnderlyingStaked.scaledMul(getMaxReserveDeviationRatio());
uint256 nextTargetBalance = totalUnderlyingStaked.scaledMul(getRequiredReserveRatio());
if (
underlyingToWithdraw > underlyingBalance ||
(underlyingBalance - underlyingToWithdraw) + maximumDeviation < nextTargetBalance
) {
uint256 requiredDeposits = nextTargetBalance + underlyingToWithdraw - underlyingBalance;
vault.withdraw(requiredDeposits);
} else {
uint256 nextBalance = underlyingBalance - underlyingToWithdraw;
if (nextBalance > nextTargetBalance + maximumDeviation) {
uint256 excessDeposits = nextBalance - nextTargetBalance;
_doTransferOut(payable(address(vault)), excessDeposits);
vault.deposit();
}
}
}
function _updateUserFeesOnDeposit(
address account,
address from,
uint256 amountAdded
) internal {
WithdrawalFeeMeta storage meta = withdrawalFeeMetas[account];
uint256 balance = lpToken.balanceOf(account) +
staker.stakedAndActionLockedBalanceOf(account);
uint256 newCurrentFeeRatio = getNewCurrentFees(
meta.timeToWait,
meta.lastActionTimestamp,
meta.feeRatio
);
uint256 shareAdded = amountAdded.scaledDiv(amountAdded + balance);
uint256 shareExisting = ScaledMath.ONE - shareAdded;
uint256 feeOnDeposit;
if (from == address(0)) {
feeOnDeposit = getMaxWithdrawalFee();
} else {
WithdrawalFeeMeta storage fromMeta = withdrawalFeeMetas[from];
feeOnDeposit = getNewCurrentFees(
fromMeta.timeToWait,
fromMeta.lastActionTimestamp,
fromMeta.feeRatio
);
}
uint256 newFeeRatio = shareExisting.scaledMul(newCurrentFeeRatio) +
shareAdded.scaledMul(feeOnDeposit);
meta.feeRatio = uint64(newFeeRatio);
meta.timeToWait = uint64(getWithdrawalFeeDecreasePeriod());
meta.lastActionTimestamp = uint64(_getTime());
}
function _getBalanceUnderlying() internal view virtual returns (uint256);
function _getBalanceUnderlying(bool transferInDone) internal view virtual returns (uint256);
function _isAuthorizedToPause(address account) internal view override returns (bool) {
return _roleManager().hasRole(Roles.GOVERNANCE, account);
}
/**
* @dev Overriden for testing
*/
function _getTime() internal view virtual returns (uint256) {
return block.timestamp;
}
function _checkFeeInvariants(uint256 minFee, uint256 maxFee) internal pure {
require(maxFee >= minFee, Error.INVALID_AMOUNT);
require(maxFee <= _MAX_WITHDRAWAL_FEE, Error.INVALID_AMOUNT);
}
}
// File interfaces/pool/IErc20Pool.sol
pragma solidity 0.8.9;
interface IErc20Pool {
function initialize(
string memory name_,
address underlying_,
uint256 depositCap_,
address vault_
) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0-or-later
// File contracts/pool/Erc20Pool.sol
pragma solidity 0.8.9;
contract Erc20Pool is LiquidityPool, IErc20Pool {
using SafeERC20 for IERC20;
address private _underlying;
constructor(IController _controller) LiquidityPool(_controller) {}
function initialize(
string memory name_,
address underlying_,
uint256 depositCap_,
address vault_
) public override returns (bool) {
require(underlying_ != address(0), Error.ZERO_ADDRESS_NOT_ALLOWED);
_underlying = underlying_;
return _initialize(name_, depositCap_, vault_);
}
function getUnderlying() public view override returns (address) {
return _underlying;
}
function _doTransferIn(address from, uint256 amount) internal override {
require(msg.value == 0, Error.INVALID_VALUE);
IERC20(_underlying).safeTransferFrom(from, address(this), amount);
}
function _doTransferOut(address payable to, uint256 amount) internal override {
IERC20(_underlying).safeTransfer(to, amount);
}
function _getBalanceUnderlying() internal view override returns (uint256) {
return IERC20(_underlying).balanceOf(address(this));
}
function _getBalanceUnderlying(bool) internal view override returns (uint256) {
return _getBalanceUnderlying();
}
}
|
* @notice Compute current exchange rate of LP tokens to underlying scaled to 1e18. @dev Exchange rate means: underlying = LP token exchangeRate @return Current exchange rate./
|
function exchangeRate() public view override returns (uint256) {
uint256 totalUnderlying_ = totalUnderlying();
uint256 totalSupply = lpToken.totalSupply();
if (totalSupply == 0 || totalUnderlying_ == 0) {
return ScaledMath.ONE;
}
return totalUnderlying_.scaledDiv(totalSupply);
}
| 10,436,109 |
[
1,
7018,
783,
7829,
4993,
434,
511,
52,
2430,
358,
6808,
12304,
358,
404,
73,
2643,
18,
225,
18903,
4993,
4696,
30,
6808,
273,
511,
52,
1147,
225,
7829,
4727,
327,
6562,
7829,
4993,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
7829,
4727,
1435,
1071,
1476,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
2254,
5034,
2078,
14655,
6291,
67,
273,
2078,
14655,
6291,
5621,
203,
3639,
2254,
5034,
2078,
3088,
1283,
273,
12423,
1345,
18,
4963,
3088,
1283,
5621,
203,
3639,
309,
261,
4963,
3088,
1283,
422,
374,
747,
2078,
14655,
6291,
67,
422,
374,
13,
288,
203,
5411,
327,
348,
12825,
10477,
18,
5998,
31,
203,
3639,
289,
203,
203,
3639,
327,
2078,
14655,
6291,
27799,
20665,
7244,
12,
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
] |
./partial_match/1/0xC4b3fD5dB1BcDeb8CB56E6530c52F2ae5265dAE0/sources/EasyCowboy.sol
|
@dev : this works as a wrapper to handle the call if function is calledd with an argument//
|
function mint() external payable {
mint(1);
}
| 3,949,934 |
[
1,
30,
333,
6330,
487,
279,
4053,
358,
1640,
326,
745,
309,
445,
353,
1443,
298,
449,
598,
392,
1237,
759,
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,
312,
474,
1435,
3903,
8843,
429,
288,
203,
3639,
312,
474,
12,
21,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/draft-IERC20PermitUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../interfaces/IFeeDistributor.sol";
import "../interfaces/ILiquidityGauge.sol";
import "../interfaces/ISanToken.sol";
import "../interfaces/IStableMaster.sol";
import "../interfaces/IStableMasterFront.sol";
import "../interfaces/IVeANGLE.sol";
import "../interfaces/external/IWETH9.sol";
import "../interfaces/external/uniswap/IUniswapRouter.sol";
/// @title Angle Router
/// @author Angle Core Team
/// @notice The `AngleRouter` contract facilitates interactions for users with the protocol. It was built to reduce the number
/// of approvals required to users and the number of transactions needed to perform some complex actions: like deposit and stake
/// in just one transaction
/// @dev Interfaces were designed for both advanced users which know the addresses of the protocol's contract, but most of the time
/// users which only know addresses of the stablecoins and collateral types of the protocol can perform the actions they want without
/// needing to understand what's happening under the hood
contract AngleRouter is Initializable, ReentrancyGuardUpgradeable {
using SafeERC20 for IERC20;
/// @notice Base used for params
uint256 public constant BASE_PARAMS = 10**9;
/// @notice Base used for params
uint256 private constant _MAX_TOKENS = 10;
// @notice Wrapped ETH contract
IWETH9 public constant WETH9 = IWETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
// @notice ANGLE contract
IERC20 public constant ANGLE = IERC20(0x31429d1856aD1377A8A0079410B297e1a9e214c2);
// @notice veANGLE contract
IVeANGLE public constant VEANGLE = IVeANGLE(0x0C462Dbb9EC8cD1630f1728B2CFD2769d09f0dd5);
// =========================== Structs and Enums ===============================
/// @notice Action types
enum ActionType {
claimRewards,
claimWeeklyInterest,
gaugeDeposit,
withdraw,
mint,
deposit,
openPerpetual,
addToPerpetual,
veANGLEDeposit
}
/// @notice All possible swaps
enum SwapType {
UniswapV3,
oneINCH
}
/// @notice Params for swaps
/// @param inToken Token to swap
/// @param collateral Token to swap for
/// @param amountIn Amount of token to sell
/// @param minAmountOut Minimum amount of collateral to receive for the swap to not revert
/// @param args Either the path for Uniswap or the payload for 1Inch
/// @param swapType Which swap route to take
struct ParamsSwapType {
IERC20 inToken;
address collateral;
uint256 amountIn;
uint256 minAmountOut;
bytes args;
SwapType swapType;
}
/// @notice Params for direct collateral transfer
/// @param inToken Token to transfer
/// @param amountIn Amount of token transfer
struct TransferType {
IERC20 inToken;
uint256 amountIn;
}
/// @notice References to the contracts associated to a collateral for a stablecoin
struct Pairs {
IPoolManager poolManager;
IPerpetualManagerFrontWithClaim perpetualManager;
ISanToken sanToken;
ILiquidityGauge gauge;
}
/// @notice Data needed to get permits
struct PermitType {
address token;
address owner;
uint256 value;
uint256 deadline;
uint8 v;
bytes32 r;
bytes32 s;
}
// =============================== Events ======================================
event AdminChanged(address indexed admin, bool setGovernor);
event StablecoinAdded(address indexed stableMaster);
event StablecoinRemoved(address indexed stableMaster);
event CollateralToggled(address indexed stableMaster, address indexed poolManager, address indexed liquidityGauge);
event SanTokenLiquidityGaugeUpdated(address indexed sanToken, address indexed newLiquidityGauge);
event Recovered(address indexed tokenAddress, address indexed to, uint256 amount);
// =============================== Mappings ====================================
/// @notice Maps an agToken to its counterpart `StableMaster`
mapping(IERC20 => IStableMasterFront) public mapStableMasters;
/// @notice Maps a `StableMaster` to a mapping of collateral token to its counterpart `PoolManager`
mapping(IStableMasterFront => mapping(IERC20 => Pairs)) public mapPoolManagers;
/// @notice Whether the token was already approved on Uniswap router
mapping(IERC20 => bool) public uniAllowedToken;
/// @notice Whether the token was already approved on 1Inch
mapping(IERC20 => bool) public oneInchAllowedToken;
// =============================== References ==================================
/// @notice Governor address
address public governor;
/// @notice Guardian address
address public guardian;
/// @notice Address of the router used for swaps
IUniswapV3Router public uniswapV3Router;
/// @notice Address of 1Inch router used for swaps
address public oneInch;
uint256[50] private __gap;
constructor() initializer {}
/// @notice Deploys the `AngleRouter` contract
/// @param _governor Governor address
/// @param _guardian Guardian address
/// @param _uniswapV3Router UniswapV3 router address
/// @param _oneInch 1Inch aggregator address
/// @param existingStableMaster Address of the existing `StableMaster`
/// @param existingPoolManagers Addresses of the associated poolManagers
/// @param existingLiquidityGauges Addresses of liquidity gauge contracts associated to sanTokens
/// @dev Be cautious with safe approvals, all tokens will have unlimited approvals within the protocol or
/// UniswapV3 and 1Inch
function initialize(
address _governor,
address _guardian,
IUniswapV3Router _uniswapV3Router,
address _oneInch,
IStableMasterFront existingStableMaster,
IPoolManager[] calldata existingPoolManagers,
ILiquidityGauge[] calldata existingLiquidityGauges
) public initializer {
// Checking the parameters passed
require(
address(_uniswapV3Router) != address(0) &&
_oneInch != address(0) &&
_governor != address(0) &&
_guardian != address(0),
"0"
);
require(_governor != _guardian, "49");
require(existingPoolManagers.length == existingLiquidityGauges.length, "104");
// Fetching the stablecoin and mapping it to the `StableMaster`
mapStableMasters[
IERC20(address(IStableMaster(address(existingStableMaster)).agToken()))
] = existingStableMaster;
// Setting roles
governor = _governor;
guardian = _guardian;
uniswapV3Router = _uniswapV3Router;
oneInch = _oneInch;
// for veANGLEDeposit action
ANGLE.safeApprove(address(VEANGLE), type(uint256).max);
for (uint256 i = 0; i < existingPoolManagers.length; i++) {
_addPair(existingStableMaster, existingPoolManagers[i], existingLiquidityGauges[i]);
}
}
// ============================== Modifiers ====================================
/// @notice Checks to see if it is the `governor` or `guardian` calling this contract
/// @dev There is no Access Control here, because it can be handled cheaply through this modifier
/// @dev In this contract, the `governor` and the `guardian` address have exactly similar rights
modifier onlyGovernorOrGuardian() {
require(msg.sender == governor || msg.sender == guardian, "115");
_;
}
// =========================== Governance utilities ============================
/// @notice Changes the guardian or the governor address
/// @param admin New guardian or guardian address
/// @param setGovernor Whether to set Governor if true, or Guardian if false
/// @dev There can only be one guardian and one governor address in the router
/// and both need to be different
function setGovernorOrGuardian(address admin, bool setGovernor) external onlyGovernorOrGuardian {
require(admin != address(0), "0");
require(guardian != admin && governor != admin, "49");
if (setGovernor) governor = admin;
else guardian = admin;
emit AdminChanged(admin, setGovernor);
}
/// @notice Adds a new `StableMaster`
/// @param stablecoin Address of the new stablecoin
/// @param stableMaster Address of the new `StableMaster`
function addStableMaster(IERC20 stablecoin, IStableMasterFront stableMaster) external onlyGovernorOrGuardian {
// No need to check if the `stableMaster` address is a zero address as otherwise the call to `stableMaster.agToken()`
// would revert
require(address(stablecoin) != address(0), "0");
require(address(mapStableMasters[stablecoin]) == address(0), "114");
require(stableMaster.agToken() == address(stablecoin), "20");
mapStableMasters[stablecoin] = stableMaster;
emit StablecoinAdded(address(stableMaster));
}
/// @notice Removes a `StableMaster`
/// @param stablecoin Address of the associated stablecoin
/// @dev Before calling this function, governor or guardian should remove first all pairs
/// from the `mapPoolManagers[stableMaster]`. It is assumed that the governor or guardian calling this function
/// will act correctly here, it indeed avoids storing a list of all pairs for each `StableMaster`
function removeStableMaster(IERC20 stablecoin) external onlyGovernorOrGuardian {
IStableMasterFront stableMaster = mapStableMasters[stablecoin];
delete mapStableMasters[stablecoin];
emit StablecoinRemoved(address(stableMaster));
}
/// @notice Adds new collateral types to specific stablecoins
/// @param stablecoins Addresses of the stablecoins associated to the `StableMaster` of interest
/// @param poolManagers Addresses of the `PoolManager` contracts associated to the pair (stablecoin,collateral)
/// @param liquidityGauges Addresses of liquidity gauges contract associated to sanToken
function addPairs(
IERC20[] calldata stablecoins,
IPoolManager[] calldata poolManagers,
ILiquidityGauge[] calldata liquidityGauges
) external onlyGovernorOrGuardian {
require(poolManagers.length == stablecoins.length && liquidityGauges.length == stablecoins.length, "104");
for (uint256 i = 0; i < stablecoins.length; i++) {
IStableMasterFront stableMaster = mapStableMasters[stablecoins[i]];
_addPair(stableMaster, poolManagers[i], liquidityGauges[i]);
}
}
/// @notice Removes collateral types from specific `StableMaster` contracts using the address
/// of the associated stablecoins
/// @param stablecoins Addresses of the stablecoins
/// @param collaterals Addresses of the collaterals
/// @param stableMasters List of the associated `StableMaster` contracts
/// @dev In the lists, if a `stableMaster` address is null in `stableMasters` then this means that the associated
/// `stablecoins` address (at the same index) should be non null
function removePairs(
IERC20[] calldata stablecoins,
IERC20[] calldata collaterals,
IStableMasterFront[] calldata stableMasters
) external onlyGovernorOrGuardian {
require(collaterals.length == stablecoins.length && stableMasters.length == collaterals.length, "104");
Pairs memory pairs;
IStableMasterFront stableMaster;
for (uint256 i = 0; i < stablecoins.length; i++) {
if (address(stableMasters[i]) == address(0))
// In this case `collaterals[i]` is a collateral address
(stableMaster, pairs) = _getInternalContracts(stablecoins[i], collaterals[i]);
else {
// In this case `collaterals[i]` is a `PoolManager` address
stableMaster = stableMasters[i];
pairs = mapPoolManagers[stableMaster][collaterals[i]];
}
delete mapPoolManagers[stableMaster][collaterals[i]];
_changeAllowance(collaterals[i], address(stableMaster), 0);
_changeAllowance(collaterals[i], address(pairs.perpetualManager), 0);
if (address(pairs.gauge) != address(0)) pairs.sanToken.approve(address(pairs.gauge), 0);
emit CollateralToggled(address(stableMaster), address(pairs.poolManager), address(pairs.gauge));
}
}
/// @notice Sets new `liquidityGauge` contract for the associated sanTokens
/// @param stablecoins Addresses of the stablecoins
/// @param collaterals Addresses of the collaterals
/// @param newLiquidityGauges Addresses of the new liquidity gauges contract
/// @dev If `newLiquidityGauge` is null, this means that there is no liquidity gauge for this pair
/// @dev This function could be used to simply revoke the approval to a liquidity gauge
function setLiquidityGauges(
IERC20[] calldata stablecoins,
IERC20[] calldata collaterals,
ILiquidityGauge[] calldata newLiquidityGauges
) external onlyGovernorOrGuardian {
require(collaterals.length == stablecoins.length && newLiquidityGauges.length == stablecoins.length, "104");
for (uint256 i = 0; i < stablecoins.length; i++) {
IStableMasterFront stableMaster = mapStableMasters[stablecoins[i]];
Pairs storage pairs = mapPoolManagers[stableMaster][collaterals[i]];
ILiquidityGauge gauge = pairs.gauge;
ISanToken sanToken = pairs.sanToken;
require(address(stableMaster) != address(0) && address(pairs.poolManager) != address(0), "0");
pairs.gauge = newLiquidityGauges[i];
if (address(gauge) != address(0)) {
sanToken.approve(address(gauge), 0);
}
if (address(newLiquidityGauges[i]) != address(0)) {
// Checking compatibility of the staking token: it should be the sanToken
require(address(newLiquidityGauges[i].staking_token()) == address(sanToken), "20");
sanToken.approve(address(newLiquidityGauges[i]), type(uint256).max);
}
emit SanTokenLiquidityGaugeUpdated(address(sanToken), address(newLiquidityGauges[i]));
}
}
/// @notice Change allowance for a contract.
/// @param tokens Addresses of the tokens to allow
/// @param spenders Addresses to allow transfer
/// @param amounts Amounts to allow
/// @dev Approvals are normally given in the `addGauges` method, in the initializer and in
/// the internal functions to process swaps with Uniswap and 1Inch
function changeAllowance(
IERC20[] calldata tokens,
address[] calldata spenders,
uint256[] calldata amounts
) external onlyGovernorOrGuardian {
require(tokens.length == spenders.length && tokens.length == amounts.length, "104");
for (uint256 i = 0; i < tokens.length; i++) {
_changeAllowance(tokens[i], spenders[i], amounts[i]);
}
}
/// @notice Supports recovering any tokens as the router does not own any other tokens than
/// the one mistakenly sent
/// @param tokenAddress Address of the token to transfer
/// @param to Address to give tokens to
/// @param tokenAmount Amount of tokens to transfer
/// @dev If tokens are mistakenly sent to this contract, any address can take advantage of the `mixer` function
/// below to get the funds back
function recoverERC20(
address tokenAddress,
address to,
uint256 tokenAmount
) external onlyGovernorOrGuardian {
IERC20(tokenAddress).safeTransfer(to, tokenAmount);
emit Recovered(tokenAddress, to, tokenAmount);
}
// =========================== Router Functionalities =========================
/// @notice Wrapper n°1 built on top of the _claimRewards function
/// Allows to claim rewards for multiple gauges and perpetuals at once
/// @param gaugeUser Address for which to fetch the rewards from the gauges
/// @param liquidityGauges Gauges to claim on
/// @param perpetualIDs Perpetual IDs to claim rewards for
/// @param stablecoins Stablecoin contracts linked to the perpetualsIDs
/// @param collaterals Collateral contracts linked to the perpetualsIDs or `perpetualManager`
/// @dev If the caller wants to send the rewards to another account it first needs to
/// call `set_rewards_receiver(otherAccount)` on each `liquidityGauge`
function claimRewards(
address gaugeUser,
address[] memory liquidityGauges,
uint256[] memory perpetualIDs,
address[] memory stablecoins,
address[] memory collaterals
) external nonReentrant {
_claimRewards(gaugeUser, liquidityGauges, perpetualIDs, false, stablecoins, collaterals);
}
/// @notice Wrapper n°2 (a little more gas efficient than n°1) built on top of the _claimRewards function
/// Allows to claim rewards for multiple gauges and perpetuals at once
/// @param user Address to which the contract should send the rewards from gauges (not perpetuals)
/// @param liquidityGauges Contracts to claim for
/// @param perpetualIDs Perpetual IDs to claim rewards for
/// @param perpetualManagers `perpetualManager` contracts for every perp to claim
/// @dev If the caller wants to send the rewards to another account it first needs to
/// call `set_rewards_receiver(otherAccount)` on each `liquidityGauge`
function claimRewards(
address user,
address[] memory liquidityGauges,
uint256[] memory perpetualIDs,
address[] memory perpetualManagers
) external nonReentrant {
_claimRewards(user, liquidityGauges, perpetualIDs, true, new address[](perpetualIDs.length), perpetualManagers);
}
/// @notice Wrapper built on top of the `_gaugeDeposit` method to deposit collateral in a gauge
/// @param token On top of the parameters of the internal function, users need to specify the token associated
/// to the gauge they want to deposit in
/// @dev The function will revert if the token does not correspond to the gauge
function gaugeDeposit(
address user,
uint256 amount,
ILiquidityGauge gauge,
bool shouldClaimRewards,
IERC20 token
) external nonReentrant {
token.safeTransferFrom(msg.sender, address(this), amount);
_gaugeDeposit(user, amount, gauge, shouldClaimRewards);
}
/// @notice Wrapper n°1 built on top of the `_mint` method to mint stablecoins
/// @param user Address to send the stablecoins to
/// @param amount Amount of collateral to use for the mint
/// @param minStableAmount Minimum stablecoin minted for the tx not to revert
/// @param stablecoin Address of the stablecoin to mint
/// @param collateral Collateral to mint from
function mint(
address user,
uint256 amount,
uint256 minStableAmount,
address stablecoin,
address collateral
) external nonReentrant {
IERC20(collateral).safeTransferFrom(msg.sender, address(this), amount);
_mint(user, amount, minStableAmount, false, stablecoin, collateral, IPoolManager(address(0)));
}
/// @notice Wrapper n°2 (a little more gas efficient than n°1) built on top of the `_mint` method to mint stablecoins
/// @param user Address to send the stablecoins to
/// @param amount Amount of collateral to use for the mint
/// @param minStableAmount Minimum stablecoin minted for the tx not to revert
/// @param stableMaster Address of the stableMaster managing the stablecoin to mint
/// @param collateral Collateral to mint from
/// @param poolManager PoolManager associated to the `collateral`
function mint(
address user,
uint256 amount,
uint256 minStableAmount,
address stableMaster,
address collateral,
address poolManager
) external nonReentrant {
IERC20(collateral).safeTransferFrom(msg.sender, address(this), amount);
_mint(user, amount, minStableAmount, true, stableMaster, collateral, IPoolManager(poolManager));
}
/// @notice Wrapper built on top of the `_burn` method to burn stablecoins
/// @param dest Address to send the collateral to
/// @param amount Amount of stablecoins to use for the burn
/// @param minCollatAmount Minimum collateral amount received for the tx not to revert
/// @param stablecoin Address of the stablecoin to mint
/// @param collateral Collateral to mint from
function burn(
address dest,
uint256 amount,
uint256 minCollatAmount,
address stablecoin,
address collateral
) external nonReentrant {
_burn(dest, amount, minCollatAmount, false, stablecoin, collateral, IPoolManager(address(0)));
}
/// @notice Wrapper n°1 built on top of the `_deposit` method to deposit collateral as a SLP in the protocol
/// Allows to deposit a collateral within the protocol
/// @param user Address where to send the resulting sanTokens, if this address is the router address then it means
/// that the intention is to stake the sanTokens obtained in a subsequent `gaugeDeposit` action
/// @param amount Amount of collateral to deposit
/// @param stablecoin `StableMaster` associated to the sanToken
/// @param collateral Token to deposit
/// @dev Contrary to the `mint` action, the `deposit` action can be used in composition with other actions, like
/// `deposit` and then `stake
function deposit(
address user,
uint256 amount,
address stablecoin,
address collateral
) external nonReentrant {
IERC20(collateral).safeTransferFrom(msg.sender, address(this), amount);
_deposit(user, amount, false, stablecoin, collateral, IPoolManager(address(0)), ISanToken(address(0)));
}
/// @notice Wrapper n°2 (a little more gas efficient than n°1) built on top of the `_deposit` method to deposit collateral as a SLP in the protocol
/// Allows to deposit a collateral within the protocol
/// @param user Address where to send the resulting sanTokens, if this address is the router address then it means
/// that the intention is to stake the sanTokens obtained in a subsequent `gaugeDeposit` action
/// @param amount Amount of collateral to deposit
/// @param stableMaster `StableMaster` associated to the sanToken
/// @param collateral Token to deposit
/// @param poolManager PoolManager associated to the sanToken
/// @param sanToken SanToken associated to the `collateral` and `stableMaster`
/// @dev Contrary to the `mint` action, the `deposit` action can be used in composition with other actions, like
/// `deposit` and then `stake`
function deposit(
address user,
uint256 amount,
address stableMaster,
address collateral,
IPoolManager poolManager,
ISanToken sanToken
) external nonReentrant {
IERC20(collateral).safeTransferFrom(msg.sender, address(this), amount);
_deposit(user, amount, true, stableMaster, collateral, poolManager, sanToken);
}
/// @notice Wrapper built on top of the `_openPerpetual` method to open a perpetual with the protocol
/// @param collateral Here the collateral should not be null (even if `addressProcessed` is true) for the router
/// to be able to know how to deposit collateral
/// @dev `stablecoinOrPerpetualManager` should be the address of the agToken (= stablecoin) is `addressProcessed` is false
/// and the associated `perpetualManager` otherwise
function openPerpetual(
address owner,
uint256 margin,
uint256 amountCommitted,
uint256 maxOracleRate,
uint256 minNetMargin,
bool addressProcessed,
address stablecoinOrPerpetualManager,
address collateral
) external nonReentrant {
IERC20(collateral).safeTransferFrom(msg.sender, address(this), margin);
_openPerpetual(
owner,
margin,
amountCommitted,
maxOracleRate,
minNetMargin,
addressProcessed,
stablecoinOrPerpetualManager,
collateral
);
}
/// @notice Wrapper built on top of the `_addToPerpetual` method to add collateral to a perpetual with the protocol
/// @param collateral Here the collateral should not be null (even if `addressProcessed is true) for the router
/// to be able to know how to deposit collateral
/// @dev `stablecoinOrPerpetualManager` should be the address of the agToken is `addressProcessed` is false and the associated
/// `perpetualManager` otherwise
function addToPerpetual(
uint256 margin,
uint256 perpetualID,
bool addressProcessed,
address stablecoinOrPerpetualManager,
address collateral
) external nonReentrant {
IERC20(collateral).safeTransferFrom(msg.sender, address(this), margin);
_addToPerpetual(margin, perpetualID, addressProcessed, stablecoinOrPerpetualManager, collateral);
}
/// @notice Allows composable calls to different functions within the protocol
/// @param paramsPermit Array of params `PermitType` used to do a 1 tx to approve the router on each token (can be done once by
/// setting high approved amounts) which supports the `permit` standard. Users willing to interact with the contract
/// with tokens that do not support permit should approve the contract for these tokens prior to interacting with it
/// @param paramsTransfer Array of params `TransferType` used to transfer tokens to the router
/// @param paramsSwap Array of params `ParamsSwapType` used to swap tokens
/// @param actions List of actions to be performed by the router (in order of execution): make sure to read for each action the
/// associated internal function
/// @param datas Array of encoded data for each of the actions performed in this mixer. This is where the bytes-encoded parameters
/// for a given action are stored
/// @dev This function first fills the router balances via transfers and swaps. It then proceeds with each
/// action in the order at which they are given
/// @dev With this function, users can specify paths to swap tokens to the desired token of their choice. Yet the protocol
/// does not verify the payload given and cannot check that the swap performed by users actually gives the desired
/// out token: in this case funds will be lost by the user
/// @dev For some actions (`mint`, `deposit`, `openPerpetual`, `addToPerpetual`, `withdraw`), users are
/// required to give a proportion of the amount of token they have brought to the router within the transaction (through
/// a direct transfer or a swap) they want to use for the operation. If you want to use all the USDC you have brought (through an ETH -> USDC)
/// swap to mint stablecoins for instance, you should use `BASE_PARAMS` as a proportion.
/// @dev The proportion that is specified for an action is a proportion of what is left. If you want to use 50% of your USDC for a `mint`
/// and the rest for an `openPerpetual`, proportion used for the `mint` should be 50% (that is `BASE_PARAMS/2`), and proportion
/// for the `openPerpetual` should be all that is left that is 100% (= `BASE_PARAMS`).
/// @dev For each action here, make sure to read the documentation of the associated internal function to know how to correctly
/// specify parameters
function mixer(
PermitType[] memory paramsPermit,
TransferType[] memory paramsTransfer,
ParamsSwapType[] memory paramsSwap,
ActionType[] memory actions,
bytes[] calldata datas
) external payable nonReentrant {
// Do all the permits once for all: if all tokens have already been approved, there's no need for this step
for (uint256 i = 0; i < paramsPermit.length; i++) {
IERC20PermitUpgradeable(paramsPermit[i].token).permit(
paramsPermit[i].owner,
address(this),
paramsPermit[i].value,
paramsPermit[i].deadline,
paramsPermit[i].v,
paramsPermit[i].r,
paramsPermit[i].s
);
}
// Then, do all the transfer to load all needed funds into the router
// This function is limited to 10 different assets to be spent on the protocol (agTokens, collaterals, sanTokens)
address[_MAX_TOKENS] memory listTokens;
uint256[_MAX_TOKENS] memory balanceTokens;
for (uint256 i = 0; i < paramsTransfer.length; i++) {
paramsTransfer[i].inToken.safeTransferFrom(msg.sender, address(this), paramsTransfer[i].amountIn);
_addToList(listTokens, balanceTokens, address(paramsTransfer[i].inToken), paramsTransfer[i].amountIn);
}
for (uint256 i = 0; i < paramsSwap.length; i++) {
// Caution here: if the args are not set such that end token is the params `paramsSwap[i].collateral`,
// then the funds will be lost, and any user could take advantage of it to fetch the funds
uint256 amountOut = _transferAndSwap(
paramsSwap[i].inToken,
paramsSwap[i].amountIn,
paramsSwap[i].minAmountOut,
paramsSwap[i].swapType,
paramsSwap[i].args
);
_addToList(listTokens, balanceTokens, address(paramsSwap[i].collateral), amountOut);
}
// Performing actions one after the others
for (uint256 i = 0; i < actions.length; i++) {
if (actions[i] == ActionType.claimRewards) {
(
address user,
uint256 proportionToBeTransferred,
address[] memory claimLiquidityGauges,
uint256[] memory claimPerpetualIDs,
bool addressProcessed,
address[] memory stablecoins,
address[] memory collateralsOrPerpetualManagers
) = abi.decode(datas[i], (address, uint256, address[], uint256[], bool, address[], address[]));
uint256 amount = ANGLE.balanceOf(user);
_claimRewards(
user,
claimLiquidityGauges,
claimPerpetualIDs,
addressProcessed,
stablecoins,
collateralsOrPerpetualManagers
);
if (proportionToBeTransferred > 0) {
amount = ANGLE.balanceOf(user) - amount;
amount = (amount * proportionToBeTransferred) / BASE_PARAMS;
ANGLE.safeTransferFrom(msg.sender, address(this), amount);
_addToList(listTokens, balanceTokens, address(ANGLE), amount);
}
} else if (actions[i] == ActionType.claimWeeklyInterest) {
(address user, address feeDistributor, bool letInContract) = abi.decode(
datas[i],
(address, address, bool)
);
(uint256 amount, IERC20 token) = _claimWeeklyInterest(
user,
IFeeDistributorFront(feeDistributor),
letInContract
);
if (address(token) != address(0)) _addToList(listTokens, balanceTokens, address(token), amount);
// In all the following action, the `amount` variable represents the proportion of the
// balance that needs to be used for this action (in `BASE_PARAMS`)
// We name it `amount` here to save some new variable declaration costs
} else if (actions[i] == ActionType.veANGLEDeposit) {
(address user, uint256 amount) = abi.decode(datas[i], (address, uint256));
amount = _computeProportion(amount, listTokens, balanceTokens, address(ANGLE));
_depositOnLocker(user, amount);
} else if (actions[i] == ActionType.gaugeDeposit) {
(address user, uint256 amount, address stakedToken, address gauge, bool shouldClaimRewards) = abi
.decode(datas[i], (address, uint256, address, address, bool));
amount = _computeProportion(amount, listTokens, balanceTokens, stakedToken);
_gaugeDeposit(user, amount, ILiquidityGauge(gauge), shouldClaimRewards);
} else if (actions[i] == ActionType.deposit) {
(
address user,
uint256 amount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateral,
address poolManager,
address sanToken
) = abi.decode(datas[i], (address, uint256, bool, address, address, address, address));
amount = _computeProportion(amount, listTokens, balanceTokens, collateral);
(amount, sanToken) = _deposit(
user,
amount,
addressProcessed,
stablecoinOrStableMaster,
collateral,
IPoolManager(poolManager),
ISanToken(sanToken)
);
if (amount > 0) _addToList(listTokens, balanceTokens, sanToken, amount);
} else if (actions[i] == ActionType.withdraw) {
(
uint256 amount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateralOrPoolManager,
address sanToken
) = abi.decode(datas[i], (uint256, bool, address, address, address));
amount = _computeProportion(amount, listTokens, balanceTokens, sanToken);
// Reusing the `collateralOrPoolManager` variable to save some variable declarations
(amount, collateralOrPoolManager) = _withdraw(
amount,
addressProcessed,
stablecoinOrStableMaster,
collateralOrPoolManager
);
_addToList(listTokens, balanceTokens, collateralOrPoolManager, amount);
} else if (actions[i] == ActionType.mint) {
(
address user,
uint256 amount,
uint256 minStableAmount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateral,
address poolManager
) = abi.decode(datas[i], (address, uint256, uint256, bool, address, address, address));
amount = _computeProportion(amount, listTokens, balanceTokens, collateral);
_mint(
user,
amount,
minStableAmount,
addressProcessed,
stablecoinOrStableMaster,
collateral,
IPoolManager(poolManager)
);
} else if (actions[i] == ActionType.openPerpetual) {
(
address user,
uint256 amount,
uint256 amountCommitted,
uint256 extremeRateOracle,
uint256 minNetMargin,
bool addressProcessed,
address stablecoinOrPerpetualManager,
address collateral
) = abi.decode(datas[i], (address, uint256, uint256, uint256, uint256, bool, address, address));
amount = _computeProportion(amount, listTokens, balanceTokens, collateral);
_openPerpetual(
user,
amount,
amountCommitted,
extremeRateOracle,
minNetMargin,
addressProcessed,
stablecoinOrPerpetualManager,
collateral
);
} else if (actions[i] == ActionType.addToPerpetual) {
(
uint256 amount,
uint256 perpetualID,
bool addressProcessed,
address stablecoinOrPerpetualManager,
address collateral
) = abi.decode(datas[i], (uint256, uint256, bool, address, address));
amount = _computeProportion(amount, listTokens, balanceTokens, collateral);
_addToPerpetual(amount, perpetualID, addressProcessed, stablecoinOrPerpetualManager, collateral);
}
}
// Once all actions have been performed, the router sends back the unused funds from users
// If a user sends funds (through a swap) but specifies incorrectly the collateral associated to it, then the mixer will revert
// When trying to send remaining funds back
for (uint256 i = 0; i < balanceTokens.length; i++) {
if (balanceTokens[i] > 0) IERC20(listTokens[i]).safeTransfer(msg.sender, balanceTokens[i]);
}
}
receive() external payable {}
// ======================== Internal Utility Functions =========================
// Most internal utility functions have a wrapper built on top of it
/// @notice Internal version of the `claimRewards` function
/// Allows to claim rewards for multiple gauges and perpetuals at once
/// @param gaugeUser Address for which to fetch the rewards from the gauges
/// @param liquidityGauges Gauges to claim on
/// @param perpetualIDs Perpetual IDs to claim rewards for
/// @param addressProcessed Whether `PerpetualManager` list is already accessible in `collateralsOrPerpetualManagers`vor if it should be
/// retrieved from `stablecoins` and `collateralsOrPerpetualManagers`
/// @param stablecoins Stablecoin contracts linked to the perpetualsIDs. Array of zero addresses if addressProcessed is true
/// @param collateralsOrPerpetualManagers Collateral contracts linked to the perpetualsIDs or `perpetualManager` contracts if
/// `addressProcessed` is true
/// @dev If the caller wants to send the rewards to another account than `gaugeUser` it first needs to
/// call `set_rewards_receiver(otherAccount)` on each `liquidityGauge`
/// @dev The function only takes rewards received by users,
function _claimRewards(
address gaugeUser,
address[] memory liquidityGauges,
uint256[] memory perpetualIDs,
bool addressProcessed,
address[] memory stablecoins,
address[] memory collateralsOrPerpetualManagers
) internal {
require(
stablecoins.length == perpetualIDs.length && collateralsOrPerpetualManagers.length == perpetualIDs.length,
"104"
);
for (uint256 i = 0; i < liquidityGauges.length; i++) {
ILiquidityGauge(liquidityGauges[i]).claim_rewards(gaugeUser);
}
for (uint256 i = 0; i < perpetualIDs.length; i++) {
IPerpetualManagerFrontWithClaim perpManager;
if (addressProcessed) perpManager = IPerpetualManagerFrontWithClaim(collateralsOrPerpetualManagers[i]);
else {
(, Pairs memory pairs) = _getInternalContracts(
IERC20(stablecoins[i]),
IERC20(collateralsOrPerpetualManagers[i])
);
perpManager = pairs.perpetualManager;
}
perpManager.getReward(perpetualIDs[i]);
}
}
/// @notice Allows to deposit ANGLE on an existing locker
/// @param user Address to deposit for
/// @param amount Amount to deposit
function _depositOnLocker(address user, uint256 amount) internal {
VEANGLE.deposit_for(user, amount);
}
/// @notice Allows to claim weekly interest distribution and if wanted to transfer it to the `angleRouter` for future use
/// @param user Address to claim for
/// @param _feeDistributor Address of the fee distributor to claim to
/// @dev If funds are transferred to the router, this action cannot be an end in itself, otherwise funds will be lost:
/// typically we expect people to call for this action before doing a deposit
/// @dev If `letInContract` (and hence if funds are transferred to the router), you should approve the `angleRouter` to
/// transfer the token claimed from the `feeDistributor`
function _claimWeeklyInterest(
address user,
IFeeDistributorFront _feeDistributor,
bool letInContract
) internal returns (uint256 amount, IERC20 token) {
amount = _feeDistributor.claim(user);
if (letInContract) {
// Fetching info from the `FeeDistributor` to process correctly the withdrawal
token = IERC20(_feeDistributor.token());
token.safeTransferFrom(msg.sender, address(this), amount);
} else {
amount = 0;
}
}
/// @notice Internal version of the `gaugeDeposit` function
/// Allows to deposit tokens into a gauge
/// @param user Address on behalf of which deposit should be made in the gauge
/// @param amount Amount to stake
/// @param gauge LiquidityGauge to stake in
/// @param shouldClaimRewards Whether to claim or not previously accumulated rewards
/// @dev You should be cautious on who will receive the rewards (if `shouldClaimRewards` is true)
/// It can be set on each gauge
/// @dev In the `mixer`, before calling for this action, user should have made sure to get in the router
/// the associated token (by like a `deposit` action)
/// @dev The function will revert if the gauge has not already been approved by the contract
function _gaugeDeposit(
address user,
uint256 amount,
ILiquidityGauge gauge,
bool shouldClaimRewards
) internal {
gauge.deposit(amount, user, shouldClaimRewards);
}
/// @notice Internal version of the `mint` functions
/// Mints stablecoins from the protocol
/// @param user Address to send the stablecoins to
/// @param amount Amount of collateral to use for the mint
/// @param minStableAmount Minimum stablecoin minted for the tx not to revert
/// @param addressProcessed Whether `msg.sender` provided the contracts address or the tokens one
/// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false)
/// or directly the `StableMaster` contract if `addressProcessed`
/// @param collateral Collateral to mint from: it can be null if `addressProcessed` is true but in the corresponding
/// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the mint
/// @param poolManager PoolManager associated to the `collateral` (null if `addressProcessed` is not true)
/// @dev This function is not designed to be composable with other actions of the router after it's called: like
/// stablecoins obtained from it cannot be used for other operations: as such the `user` address should not be the router
/// address
function _mint(
address user,
uint256 amount,
uint256 minStableAmount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateral,
IPoolManager poolManager
) internal {
IStableMasterFront stableMaster;
(stableMaster, poolManager) = _mintBurnContracts(
addressProcessed,
stablecoinOrStableMaster,
collateral,
poolManager
);
stableMaster.mint(amount, user, poolManager, minStableAmount);
}
/// @notice Burns stablecoins from the protocol
/// @param dest Address who will receive the proceeds
/// @param amount Amount of collateral to use for the mint
/// @param minCollatAmount Minimum Collateral minted for the tx not to revert
/// @param addressProcessed Whether `msg.sender` provided the contracts address or the tokens one
/// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false)
/// or directly the `StableMaster` contract if `addressProcessed`
/// @param collateral Collateral to mint from: it can be null if `addressProcessed` is true but in the corresponding
/// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the mint
/// @param poolManager PoolManager associated to the `collateral` (null if `addressProcessed` is not true)
function _burn(
address dest,
uint256 amount,
uint256 minCollatAmount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateral,
IPoolManager poolManager
) internal {
IStableMasterFront stableMaster;
(stableMaster, poolManager) = _mintBurnContracts(
addressProcessed,
stablecoinOrStableMaster,
collateral,
poolManager
);
stableMaster.burn(amount, msg.sender, dest, poolManager, minCollatAmount);
}
/// @notice Internal version of the `deposit` functions
/// Allows to deposit a collateral within the protocol
/// @param user Address where to send the resulting sanTokens, if this address is the router address then it means
/// that the intention is to stake the sanTokens obtained in a subsequent `gaugeDeposit` action
/// @param amount Amount of collateral to deposit
/// @param addressProcessed Whether `msg.sender` provided the contracts addresses or the tokens ones
/// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false)
/// or directly the `StableMaster` contract if `addressProcessed`
/// @param collateral Token to deposit: it can be null if `addressProcessed` is true but in the corresponding
/// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the deposit
/// @param poolManager PoolManager associated to the `collateral` (null if `addressProcessed` is not true)
/// @param sanToken SanToken associated to the `collateral` (null if `addressProcessed` is not true)
/// @dev Contrary to the `mint` action, the `deposit` action can be used in composition with other actions, like
/// `deposit` and then `stake`
function _deposit(
address user,
uint256 amount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateral,
IPoolManager poolManager,
ISanToken sanToken
) internal returns (uint256 addedAmount, address) {
IStableMasterFront stableMaster;
if (addressProcessed) {
stableMaster = IStableMasterFront(stablecoinOrStableMaster);
} else {
Pairs memory pairs;
(stableMaster, pairs) = _getInternalContracts(IERC20(stablecoinOrStableMaster), IERC20(collateral));
poolManager = pairs.poolManager;
sanToken = pairs.sanToken;
}
if (user == address(this)) {
// Computing the amount of sanTokens obtained
addedAmount = sanToken.balanceOf(address(this));
stableMaster.deposit(amount, address(this), poolManager);
addedAmount = sanToken.balanceOf(address(this)) - addedAmount;
} else {
stableMaster.deposit(amount, user, poolManager);
}
return (addedAmount, address(sanToken));
}
/// @notice Withdraws sanTokens from the protocol
/// @param amount Amount of sanTokens to withdraw
/// @param addressProcessed Whether `msg.sender` provided the contracts addresses or the tokens ones
/// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false)
/// or directly the `StableMaster` contract if `addressProcessed`
/// @param collateralOrPoolManager Collateral to withdraw (if `addressProcessed` is false) or directly
/// the `PoolManager` contract if `addressProcessed`
function _withdraw(
uint256 amount,
bool addressProcessed,
address stablecoinOrStableMaster,
address collateralOrPoolManager
) internal returns (uint256 withdrawnAmount, address) {
IStableMasterFront stableMaster;
// Stores the address of the `poolManager`, while `collateralOrPoolManager` is used in the function
// to store the `collateral` address
IPoolManager poolManager;
if (addressProcessed) {
stableMaster = IStableMasterFront(stablecoinOrStableMaster);
poolManager = IPoolManager(collateralOrPoolManager);
collateralOrPoolManager = poolManager.token();
} else {
Pairs memory pairs;
(stableMaster, pairs) = _getInternalContracts(
IERC20(stablecoinOrStableMaster),
IERC20(collateralOrPoolManager)
);
poolManager = pairs.poolManager;
}
// Here reusing the `withdrawnAmount` variable to avoid a stack too deep problem
withdrawnAmount = IERC20(collateralOrPoolManager).balanceOf(address(this));
// This call will increase our collateral balance
stableMaster.withdraw(amount, address(this), address(this), poolManager);
// We compute the difference between our collateral balance after and before the `withdraw` call
withdrawnAmount = IERC20(collateralOrPoolManager).balanceOf(address(this)) - withdrawnAmount;
return (withdrawnAmount, collateralOrPoolManager);
}
/// @notice Internal version of the `openPerpetual` function
/// Opens a perpetual within Angle
/// @param owner Address to mint perpetual for
/// @param margin Margin to open the perpetual with
/// @param amountCommitted Commit amount in the perpetual
/// @param maxOracleRate Maximum oracle rate required to have a leverage position opened
/// @param minNetMargin Minimum net margin required to have a leverage position opened
/// @param addressProcessed Whether msg.sender provided the contracts addresses or the tokens ones
/// @param stablecoinOrPerpetualManager Token associated to the `StableMaster` (iif `addressProcessed` is false)
/// or address of the desired `PerpetualManager` (if `addressProcessed` is true)
/// @param collateral Collateral to mint from (it can be null if `addressProcessed` is true): it can be null if `addressProcessed` is true but in the corresponding
/// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the deposit
function _openPerpetual(
address owner,
uint256 margin,
uint256 amountCommitted,
uint256 maxOracleRate,
uint256 minNetMargin,
bool addressProcessed,
address stablecoinOrPerpetualManager,
address collateral
) internal returns (uint256 perpetualID) {
if (!addressProcessed) {
(, Pairs memory pairs) = _getInternalContracts(IERC20(stablecoinOrPerpetualManager), IERC20(collateral));
stablecoinOrPerpetualManager = address(pairs.perpetualManager);
}
return
IPerpetualManagerFrontWithClaim(stablecoinOrPerpetualManager).openPerpetual(
owner,
margin,
amountCommitted,
maxOracleRate,
minNetMargin
);
}
/// @notice Internal version of the `addToPerpetual` function
/// Adds collateral to a perpetual
/// @param margin Amount of collateral to add
/// @param perpetualID Perpetual to add collateral to
/// @param addressProcessed Whether msg.sender provided the contracts addresses or the tokens ones
/// @param stablecoinOrPerpetualManager Token associated to the `StableMaster` (iif `addressProcessed` is false)
/// or address of the desired `PerpetualManager` (if `addressProcessed` is true)
/// @param collateral Collateral to mint from (it can be null if `addressProcessed` is true): it can be null if `addressProcessed` is true but in the corresponding
/// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the deposit
function _addToPerpetual(
uint256 margin,
uint256 perpetualID,
bool addressProcessed,
address stablecoinOrPerpetualManager,
address collateral
) internal {
if (!addressProcessed) {
(, Pairs memory pairs) = _getInternalContracts(IERC20(stablecoinOrPerpetualManager), IERC20(collateral));
stablecoinOrPerpetualManager = address(pairs.perpetualManager);
}
IPerpetualManagerFrontWithClaim(stablecoinOrPerpetualManager).addToPerpetual(perpetualID, margin);
}
// ======================== Internal Utility Functions =========================
/// @notice Checks if collateral in the list
/// @param list List of addresses
/// @param searchFor Address of interest
/// @return index Place of the address in the list if it is in or current length otherwise
function _searchList(address[_MAX_TOKENS] memory list, address searchFor) internal pure returns (uint256 index) {
uint256 i;
while (i < list.length && list[i] != address(0)) {
if (list[i] == searchFor) return i;
i++;
}
return i;
}
/// @notice Modifies stored balances for a given collateral
/// @param list List of collateral addresses
/// @param balances List of balances for the different supported collateral types
/// @param searchFor Address of the collateral of interest
/// @param amount Amount to add in the balance for this collateral
function _addToList(
address[_MAX_TOKENS] memory list,
uint256[_MAX_TOKENS] memory balances,
address searchFor,
uint256 amount
) internal pure {
uint256 index = _searchList(list, searchFor);
// add it to the list if non existent and we add tokens
if (list[index] == address(0)) list[index] = searchFor;
balances[index] += amount;
}
/// @notice Computes the proportion of the collateral leftover balance to use for a given action
/// @param proportion Ratio to take from balance
/// @param list Collateral list
/// @param balances Balances of each collateral asset in the collateral list
/// @param searchFor Collateral to look for
/// @return amount Amount to use for the action (based on the proportion given)
/// @dev To use all the collateral balance available for an action, users should give `proportion` a value of
/// `BASE_PARAMS`
function _computeProportion(
uint256 proportion,
address[_MAX_TOKENS] memory list,
uint256[_MAX_TOKENS] memory balances,
address searchFor
) internal pure returns (uint256 amount) {
uint256 index = _searchList(list, searchFor);
// Reverts if the index was not found
require(list[index] != address(0), "33");
amount = (proportion * balances[index]) / BASE_PARAMS;
balances[index] -= amount;
}
/// @notice Gets Angle contracts associated to a pair (stablecoin, collateral)
/// @param stablecoin Token associated to a `StableMaster`
/// @param collateral Collateral to mint/deposit/open perpetual or add collateral from
/// @dev This function is used to check that the parameters passed by people calling some of the main
/// router functions are correct
function _getInternalContracts(IERC20 stablecoin, IERC20 collateral)
internal
view
returns (IStableMasterFront stableMaster, Pairs memory pairs)
{
stableMaster = mapStableMasters[stablecoin];
pairs = mapPoolManagers[stableMaster][collateral];
// If `stablecoin` is zero then this necessarily means that `stableMaster` here will be 0
// Similarly, if `collateral` is zero, then this means that `pairs.perpetualManager`, `pairs.poolManager`
// and `pairs.sanToken` will be zero
// Last, if any of `pairs.perpetualManager`, `pairs.poolManager` or `pairs.sanToken` is zero, this means
// that all others should be null from the `addPairs` and `removePairs` functions which keep this invariant
require(address(stableMaster) != address(0) && address(pairs.poolManager) != address(0), "0");
return (stableMaster, pairs);
}
/// @notice Get contracts for mint and burn actions
/// @param addressProcessed Whether `msg.sender` provided the contracts address or the tokens one
/// @param stablecoinOrStableMaster Token associated to a `StableMaster` (if `addressProcessed` is false)
/// or directly the `StableMaster` contract if `addressProcessed`
/// @param collateral Collateral to mint from: it can be null if `addressProcessed` is true but in the corresponding
/// action, the `mixer` needs to get a correct address to compute the amount of tokens to use for the mint
/// @param poolManager PoolManager associated to the `collateral` (null if `addressProcessed` is not true)
function _mintBurnContracts(
bool addressProcessed,
address stablecoinOrStableMaster,
address collateral,
IPoolManager poolManager
) internal view returns (IStableMasterFront, IPoolManager) {
IStableMasterFront stableMaster;
if (addressProcessed) {
stableMaster = IStableMasterFront(stablecoinOrStableMaster);
} else {
Pairs memory pairs;
(stableMaster, pairs) = _getInternalContracts(IERC20(stablecoinOrStableMaster), IERC20(collateral));
poolManager = pairs.poolManager;
}
return (stableMaster, poolManager);
}
/// @notice Adds new collateral type to specific stablecoin
/// @param stableMaster Address of the `StableMaster` associated to the stablecoin of interest
/// @param poolManager Address of the `PoolManager` contract associated to the pair (stablecoin,collateral)
/// @param liquidityGauge Address of liquidity gauge contract associated to sanToken
function _addPair(
IStableMasterFront stableMaster,
IPoolManager poolManager,
ILiquidityGauge liquidityGauge
) internal {
// Fetching the associated `sanToken` and `perpetualManager` from the contract
(IERC20 collateral, ISanToken sanToken, IPerpetualManager perpetualManager, , , , , , ) = IStableMaster(
address(stableMaster)
).collateralMap(poolManager);
Pairs storage _pairs = mapPoolManagers[stableMaster][collateral];
// Checking if the pair has not already been initialized: if yes we need to make the function revert
// otherwise we could end up with still approved `PoolManager` and `PerpetualManager` contracts
require(address(_pairs.poolManager) == address(0), "114");
_pairs.poolManager = poolManager;
_pairs.perpetualManager = IPerpetualManagerFrontWithClaim(address(perpetualManager));
_pairs.sanToken = sanToken;
// In the future, it is possible that sanTokens do not have an associated liquidity gauge
if (address(liquidityGauge) != address(0)) {
require(address(sanToken) == liquidityGauge.staking_token(), "20");
_pairs.gauge = liquidityGauge;
sanToken.approve(address(liquidityGauge), type(uint256).max);
}
_changeAllowance(collateral, address(stableMaster), type(uint256).max);
_changeAllowance(collateral, address(perpetualManager), type(uint256).max);
emit CollateralToggled(address(stableMaster), address(poolManager), address(liquidityGauge));
}
/// @notice Changes allowance of this contract for a given token
/// @param token Address of the token to change allowance
/// @param spender Address to change the allowance of
/// @param amount Amount allowed
function _changeAllowance(
IERC20 token,
address spender,
uint256 amount
) internal {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < amount) {
token.safeIncreaseAllowance(spender, amount - currentAllowance);
} else if (currentAllowance > amount) {
token.safeDecreaseAllowance(spender, currentAllowance - amount);
}
}
/// @notice Transfers collateral or an arbitrary token which is then swapped on UniswapV3 or on 1Inch
/// @param inToken Token to swap for the collateral
/// @param amount Amount of in token to swap for the collateral
/// @param minAmountOut Minimum amount accepted for the swap to happen
/// @param swapType Choice on which contracts to swap
/// @param args Bytes representing either the path to swap your input token to the accepted collateral on Uniswap or payload for 1Inch
/// @dev The `path` provided is not checked, meaning people could swap for a token A and declare that they've swapped for another token B.
/// However, the mixer manipulates its token balance only through the addresses registered in `listTokens`, so any subsequent mixer action
/// trying to transfer funds B will do it through address of token A and revert as A is not actually funded.
/// In case there is not subsequent action, `mixer` will revert when trying to send back what appears to be remaining tokens A.
function _transferAndSwap(
IERC20 inToken,
uint256 amount,
uint256 minAmountOut,
SwapType swapType,
bytes memory args
) internal returns (uint256 amountOut) {
if (address(inToken) == address(WETH9) && address(this).balance >= amount) {
WETH9.deposit{ value: amount }(); // wrap only what is needed to pay
} else {
inToken.safeTransferFrom(msg.sender, address(this), amount);
}
if (swapType == SwapType.UniswapV3) amountOut = _swapOnUniswapV3(inToken, amount, minAmountOut, args);
else if (swapType == SwapType.oneINCH) amountOut = _swapOn1Inch(inToken, minAmountOut, args);
else require(false, "3");
return amountOut;
}
/// @notice Allows to swap any token to an accepted collateral via UniswapV3 (if there is a path)
/// @param inToken Address token used as entrance of the swap
/// @param amount Amount of in token to swap for the accepted collateral
/// @param minAmountOut Minimum amount accepted for the swap to happen
/// @param path Bytes representing the path to swap your input token to the accepted collateral
function _swapOnUniswapV3(
IERC20 inToken,
uint256 amount,
uint256 minAmountOut,
bytes memory path
) internal returns (uint256 amountOut) {
// Approve transfer to the `uniswapV3Router` if it is the first time that the token is used
if (!uniAllowedToken[inToken]) {
inToken.safeIncreaseAllowance(address(uniswapV3Router), type(uint256).max);
uniAllowedToken[inToken] = true;
}
amountOut = uniswapV3Router.exactInput(
ExactInputParams(path, address(this), block.timestamp, amount, minAmountOut)
);
}
/// @notice Allows to swap any token to an accepted collateral via 1Inch API
/// @param minAmountOut Minimum amount accepted for the swap to happen
/// @param payload Bytes needed for 1Inch API
function _swapOn1Inch(
IERC20 inToken,
uint256 minAmountOut,
bytes memory payload
) internal returns (uint256 amountOut) {
// Approve transfer to the `oneInch` router if it is the first time the token is used
if (!oneInchAllowedToken[inToken]) {
inToken.safeIncreaseAllowance(address(oneInch), type(uint256).max);
oneInchAllowedToken[inToken] = true;
}
//solhint-disable-next-line
(bool success, bytes memory result) = oneInch.call(payload);
if (!success) _revertBytes(result);
amountOut = abi.decode(result, (uint256));
require(amountOut >= minAmountOut, "15");
}
/// @notice Internal function used for error handling
function _revertBytes(bytes memory errMsg) internal pure {
if (errMsg.length > 0) {
//solhint-disable-next-line
assembly {
revert(add(32, errMsg), mload(errMsg))
}
}
revert("117");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
/// @title IFeeDistributor
/// @author Interface of the `FeeDistributor` contract
/// @dev This interface is used by the `SurplusConverter` contract to send funds to the `FeeDistributor`
interface IFeeDistributor {
function burn(address token) external;
}
/// @title IFeeDistributorFront
/// @author Interface for public use of the `FeeDistributor` contract
/// @dev This interface is used for user related function
interface IFeeDistributorFront {
function token() external returns (address);
function claim(address _addr) external returns (uint256);
function claim(address[20] memory _addr) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
interface ILiquidityGauge {
// solhint-disable-next-line
function staking_token() external returns (address stakingToken);
// solhint-disable-next-line
function deposit_reward_token(address _rewardToken, uint256 _amount) external;
function deposit(
uint256 _value,
address _addr,
// solhint-disable-next-line
bool _claim_rewards
) external;
// solhint-disable-next-line
function claim_rewards(address _addr) external;
// solhint-disable-next-line
function claim_rewards(address _addr, address _receiver) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
/// @title ISanToken
/// @author Angle Core Team
/// @notice Interface for Angle's `SanToken` contract that handles sanTokens, tokens that are given to SLPs
/// contributing to a collateral for a given stablecoin
interface ISanToken is IERC20Upgradeable {
// ================================== StableMaster =============================
function mint(address account, uint256 amount) external;
function burnFrom(
uint256 amount,
address burner,
address sender
) external;
function burnSelf(uint256 amount, address burner) external;
function stableMaster() external view returns (address);
function poolManager() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// Normally just importing `IPoolManager` should be sufficient, but for clarity here
// we prefer to import all concerned interfaces
import "./IPoolManager.sol";
import "./IOracle.sol";
import "./IPerpetualManager.sol";
import "./ISanToken.sol";
// Struct to handle all the parameters to manage the fees
// related to a given collateral pool (associated to the stablecoin)
struct MintBurnData {
// Values of the thresholds to compute the minting fees
// depending on HA hedge (scaled by `BASE_PARAMS`)
uint64[] xFeeMint;
// Values of the fees at thresholds (scaled by `BASE_PARAMS`)
uint64[] yFeeMint;
// Values of the thresholds to compute the burning fees
// depending on HA hedge (scaled by `BASE_PARAMS`)
uint64[] xFeeBurn;
// Values of the fees at thresholds (scaled by `BASE_PARAMS`)
uint64[] yFeeBurn;
// Max proportion of collateral from users that can be covered by HAs
// It is exactly the same as the parameter of the same name in `PerpetualManager`, whenever one is updated
// the other changes accordingly
uint64 targetHAHedge;
// Minting fees correction set by the `FeeManager` contract: they are going to be multiplied
// to the value of the fees computed using the hedge curve
// Scaled by `BASE_PARAMS`
uint64 bonusMalusMint;
// Burning fees correction set by the `FeeManager` contract: they are going to be multiplied
// to the value of the fees computed using the hedge curve
// Scaled by `BASE_PARAMS`
uint64 bonusMalusBurn;
// Parameter used to limit the number of stablecoins that can be issued using the concerned collateral
uint256 capOnStableMinted;
}
// Struct to handle all the variables and parameters to handle SLPs in the protocol
// including the fraction of interests they receive or the fees to be distributed to
// them
struct SLPData {
// Last timestamp at which the `sanRate` has been updated for SLPs
uint256 lastBlockUpdated;
// Fees accumulated from previous blocks and to be distributed to SLPs
uint256 lockedInterests;
// Max interests used to update the `sanRate` in a single block
// Should be in collateral token base
uint256 maxInterestsDistributed;
// Amount of fees left aside for SLPs and that will be distributed
// when the protocol is collateralized back again
uint256 feesAside;
// Part of the fees normally going to SLPs that is left aside
// before the protocol is collateralized back again (depends on collateral ratio)
// Updated by keepers and scaled by `BASE_PARAMS`
uint64 slippageFee;
// Portion of the fees from users minting and burning
// that goes to SLPs (the rest goes to surplus)
uint64 feesForSLPs;
// Slippage factor that's applied to SLPs exiting (depends on collateral ratio)
// If `slippage = BASE_PARAMS`, SLPs can get nothing, if `slippage = 0` they get their full claim
// Updated by keepers and scaled by `BASE_PARAMS`
uint64 slippage;
// Portion of the interests from lending
// that goes to SLPs (the rest goes to surplus)
uint64 interestsForSLPs;
}
/// @title IStableMasterFunctions
/// @author Angle Core Team
/// @notice Interface for the `StableMaster` contract
interface IStableMasterFunctions {
function deploy(
address[] memory _governorList,
address _guardian,
address _agToken
) external;
// ============================== Lending ======================================
function accumulateInterest(uint256 gain) external;
function signalLoss(uint256 loss) external;
// ============================== HAs ==========================================
function getStocksUsers() external view returns (uint256 maxCAmountInStable);
function convertToSLP(uint256 amount, address user) external;
// ============================== Keepers ======================================
function getCollateralRatio() external returns (uint256);
function setFeeKeeper(
uint64 feeMint,
uint64 feeBurn,
uint64 _slippage,
uint64 _slippageFee
) external;
// ============================== AgToken ======================================
function updateStocksUsers(uint256 amount, address poolManager) external;
// ============================= Governance ====================================
function setCore(address newCore) external;
function addGovernor(address _governor) external;
function removeGovernor(address _governor) external;
function setGuardian(address newGuardian, address oldGuardian) external;
function revokeGuardian(address oldGuardian) external;
function setCapOnStableAndMaxInterests(
uint256 _capOnStableMinted,
uint256 _maxInterestsDistributed,
IPoolManager poolManager
) external;
function setIncentivesForSLPs(
uint64 _feesForSLPs,
uint64 _interestsForSLPs,
IPoolManager poolManager
) external;
function setUserFees(
IPoolManager poolManager,
uint64[] memory _xFee,
uint64[] memory _yFee,
uint8 _mint
) external;
function setTargetHAHedge(uint64 _targetHAHedge) external;
function pause(bytes32 agent, IPoolManager poolManager) external;
function unpause(bytes32 agent, IPoolManager poolManager) external;
}
/// @title IStableMaster
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
interface IStableMaster is IStableMasterFunctions {
function agToken() external view returns (address);
function collateralMap(IPoolManager poolManager)
external
view
returns (
IERC20 token,
ISanToken sanToken,
IPerpetualManager perpetualManager,
IOracle oracle,
uint256 stocksUsers,
uint256 sanRate,
uint256 collatBase,
SLPData memory slpData,
MintBurnData memory feeData
);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "../interfaces/IPoolManager.sol";
/// @title IStableMasterFront
/// @author Angle Core Team
/// @dev Front interface, meaning only user-facing functions
interface IStableMasterFront {
function mint(
uint256 amount,
address user,
IPoolManager poolManager,
uint256 minStableAmount
) external;
function burn(
uint256 amount,
address burner,
address dest,
IPoolManager poolManager,
uint256 minCollatAmount
) external;
function deposit(
uint256 amount,
address user,
IPoolManager poolManager
) external;
function withdraw(
uint256 amount,
address burner,
address dest,
IPoolManager poolManager
) external;
function agToken() external returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
/// @title IVeANGLE
/// @author Angle Core Team
/// @notice Interface for the `VeANGLE` contract
interface IVeANGLE {
// solhint-disable-next-line func-name-mixedcase
function deposit_for(address addr, uint256 amount) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title Interface for WETH9
interface IWETH9 is IERC20 {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface IUniswapV3Router {
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
}
/// @title Router for price estimation functionality
/// @notice Functions for getting the price of one token with respect to another using Uniswap V2
/// @dev This interface is only used for non critical elements of the protocol
interface IUniswapV2Router {
/// @notice Given an input asset amount, returns the maximum output amount of the
/// other asset (accounting for fees) given reserves.
/// @param path Addresses of the pools used to get prices
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 swapAmount,
uint256 minExpected,
address[] calldata path,
address receiver,
uint256 swapDeadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "./IFeeManager.sol";
import "./IPerpetualManager.sol";
import "./IOracle.sol";
// Struct for the parameters associated to a strategy interacting with a collateral `PoolManager`
// contract
struct StrategyParams {
// Timestamp of last report made by this strategy
// It is also used to check if a strategy has been initialized
uint256 lastReport;
// Total amount the strategy is expected to have
uint256 totalStrategyDebt;
// The share of the total assets in the `PoolManager` contract that the `strategy` can access to.
uint256 debtRatio;
}
/// @title IPoolManagerFunctions
/// @author Angle Core Team
/// @notice Interface for the collateral poolManager contracts handling each one type of collateral for
/// a given stablecoin
/// @dev Only the functions used in other contracts of the protocol are left here
interface IPoolManagerFunctions {
// ============================ Constructor ====================================
function deployCollateral(
address[] memory governorList,
address guardian,
IPerpetualManager _perpetualManager,
IFeeManager feeManager,
IOracle oracle
) external;
// ============================ Yield Farming ==================================
function creditAvailable() external view returns (uint256);
function debtOutstanding() external view returns (uint256);
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external;
// ============================ Governance =====================================
function addGovernor(address _governor) external;
function removeGovernor(address _governor) external;
function setGuardian(address _guardian, address guardian) external;
function revokeGuardian(address guardian) external;
function setFeeManager(IFeeManager _feeManager) external;
// ============================= Getters =======================================
function getBalance() external view returns (uint256);
function getTotalAsset() external view returns (uint256);
}
/// @title IPoolManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
/// @dev Used in other contracts of the protocol
interface IPoolManager is IPoolManagerFunctions {
function stableMaster() external view returns (address);
function perpetualManager() external view returns (address);
function token() external view returns (address);
function feeManager() external view returns (address);
function totalDebt() external view returns (uint256);
function strategies(address _strategy) external view returns (StrategyParams memory);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
/// @title IOracle
/// @author Angle Core Team
/// @notice Interface for Angle's oracle contracts reading oracle rates from both UniswapV3 and Chainlink
/// from just UniswapV3 or from just Chainlink
interface IOracle {
function read() external view returns (uint256);
function readAll() external view returns (uint256 lowerRate, uint256 upperRate);
function readLower() external view returns (uint256);
function readUpper() external view returns (uint256);
function readQuote(uint256 baseAmount) external view returns (uint256);
function readQuoteLower(uint256 baseAmount) external view returns (uint256);
function inBase() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "./IERC721.sol";
import "./IFeeManager.sol";
import "./IOracle.sol";
import "./IAccessControl.sol";
/// @title Interface of the contract managing perpetuals
/// @author Angle Core Team
/// @dev Front interface, meaning only user-facing functions
interface IPerpetualManagerFront is IERC721Metadata {
function openPerpetual(
address owner,
uint256 amountBrought,
uint256 amountCommitted,
uint256 maxOracleRate,
uint256 minNetMargin
) external returns (uint256 perpetualID);
function closePerpetual(
uint256 perpetualID,
address to,
uint256 minCashOutAmount
) external;
function addToPerpetual(uint256 perpetualID, uint256 amount) external;
function removeFromPerpetual(
uint256 perpetualID,
uint256 amount,
address to
) external;
function liquidatePerpetuals(uint256[] memory perpetualIDs) external;
function forceClosePerpetuals(uint256[] memory perpetualIDs) external;
// ========================= External View Functions =============================
function getCashOutAmount(uint256 perpetualID, uint256 rate) external view returns (uint256, uint256);
function isApprovedOrOwner(address spender, uint256 perpetualID) external view returns (bool);
}
/// @title Interface of the contract managing perpetuals
/// @author Angle Core Team
/// @dev This interface does not contain user facing functions, it just has functions that are
/// interacted with in other parts of the protocol
interface IPerpetualManagerFunctions is IAccessControl {
// ================================= Governance ================================
function deployCollateral(
address[] memory governorList,
address guardian,
IFeeManager feeManager,
IOracle oracle_
) external;
function setFeeManager(IFeeManager feeManager_) external;
function setHAFees(
uint64[] memory _xHAFees,
uint64[] memory _yHAFees,
uint8 deposit
) external;
function setTargetAndLimitHAHedge(uint64 _targetHAHedge, uint64 _limitHAHedge) external;
function setKeeperFeesLiquidationRatio(uint64 _keeperFeesLiquidationRatio) external;
function setKeeperFeesCap(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap) external;
function setKeeperFeesClosing(uint64[] memory _xKeeperFeesClosing, uint64[] memory _yKeeperFeesClosing) external;
function setLockTime(uint64 _lockTime) external;
function setBoundsPerpetual(uint64 _maxLeverage, uint64 _maintenanceMargin) external;
function pause() external;
function unpause() external;
// ==================================== Keepers ================================
function setFeeKeeper(uint64 feeDeposit, uint64 feesWithdraw) external;
// =============================== StableMaster ================================
function setOracle(IOracle _oracle) external;
}
/// @title IPerpetualManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables
interface IPerpetualManager is IPerpetualManagerFunctions {
function poolManager() external view returns (address);
function oracle() external view returns (address);
function targetHAHedge() external view returns (uint64);
function totalHedgeAmount() external view returns (uint256);
}
/// @title Interface of the contract managing perpetuals with claim function
/// @author Angle Core Team
/// @dev Front interface with rewards function, meaning only user-facing functions
interface IPerpetualManagerFrontWithClaim is IPerpetualManagerFront, IPerpetualManager {
function getReward(uint256 perpetualID) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "./IAccessControl.sol";
/// @title IFeeManagerFunctions
/// @author Angle Core Team
/// @dev Interface for the `FeeManager` contract
interface IFeeManagerFunctions is IAccessControl {
// ================================= Keepers ===================================
function updateUsersSLP() external;
function updateHA() external;
// ================================= Governance ================================
function deployCollateral(
address[] memory governorList,
address guardian,
address _perpetualManager
) external;
function setFees(
uint256[] memory xArray,
uint64[] memory yArray,
uint8 typeChange
) external;
function setHAFees(uint64 _haFeeDeposit, uint64 _haFeeWithdraw) external;
}
/// @title IFeeManager
/// @author Angle Core Team
/// @notice Previous interface with additionnal getters for public variables and mappings
/// @dev We need these getters as they are used in other contracts of the protocol
interface IFeeManager is IFeeManagerFunctions {
function stableMaster() external view returns (address);
function perpetualManager() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
/// @title IAccessControl
/// @author Forked from OpenZeppelin
/// @notice Interface for `AccessControl` contracts
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.7;
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
interface IERC721 is IERC165 {
function balanceOf(address owner) external view returns (uint256 balance);
function ownerOf(uint256 tokenId) external view returns (address owner);
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
@notice Params for direct collateral transfer @param inToken Token to transfer @param amountIn Amount of token transfer
|
struct TransferType {
IERC20 inToken;
uint256 amountIn;
}
| 6,009,052 |
[
1,
1370,
364,
2657,
4508,
2045,
287,
7412,
225,
316,
1345,
3155,
358,
7412,
225,
3844,
382,
16811,
434,
1147,
7412,
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,
1958,
12279,
559,
288,
203,
3639,
467,
654,
39,
3462,
316,
1345,
31,
203,
3639,
2254,
5034,
3844,
382,
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
] |
./partial_match/42/0xe9363F8752b7D743426EB6D93F726B528B0a4225/sources/Clerk.sol
|
max amount of DAI that can be brawn from MKR tinlake contracts MKR contracts buffer to add on top of mat to avoid cdp liquidation => default 1% adapter functions can only be active if the tinlake pool is currently not in epoch closing/submissions/execution state
|
contract Clerk is Auth, Math {
uint public creditline;
CoordinatorLike_1 coordinator;
AssessorLike_1 assessor;
ReserveLike_1 reserve;
TrancheLike_1 tranche;
ManagerLike mgr;
VatLike vat;
SpotterLike spotter;
ERC20Like_1 dai;
ERC20Like_1 collateral;
uint matBuffer = 0.01 * 10**27;
modifier active() { require(activated(), "epoch-closing"); _; }
function activated() public view returns(bool) {
return coordinator.submissionPeriod() == false && mkrActive();
}
function mkrActive() public view returns (bool) {
return mgr.safe() && mgr.glad() && mgr.live();
}
constructor(address dai_, address collateral_) public {
wards[msg.sender] = 1;
dai = ERC20Like_1(dai_);
collateral = ERC20Like_1(collateral_);
}
function depend(bytes32 contractName, address addr) public auth {
if (contractName == "mgr") {
mgr = ManagerLike(addr);
coordinator = CoordinatorLike_1(addr);
assessor = AssessorLike_1(addr);
reserve = ReserveLike_1(addr);
tranche = TrancheLike_1(addr);
collateral = ERC20Like_1(addr);
spotter = SpotterLike(addr);
vat = VatLike(addr);
} else revert();
}
function depend(bytes32 contractName, address addr) public auth {
if (contractName == "mgr") {
mgr = ManagerLike(addr);
coordinator = CoordinatorLike_1(addr);
assessor = AssessorLike_1(addr);
reserve = ReserveLike_1(addr);
tranche = TrancheLike_1(addr);
collateral = ERC20Like_1(addr);
spotter = SpotterLike(addr);
vat = VatLike(addr);
} else revert();
}
} else if (contractName == "coordinator") {
} else if (contractName == "assessor") {
} else if (contractName == "reserve") {
} else if (contractName == "tranche") {
} else if (contractName == "collateral") {
} else if (contractName == "spotter") {
} else if (contractName == "vat") {
function file(bytes32 what, uint value) public auth {
if (what == "buffer") {
matBuffer = value;
}
}
function file(bytes32 what, uint value) public auth {
if (what == "buffer") {
matBuffer = value;
}
}
function remainingCredit() public returns (uint) {
if (creditline <= (cdptab()) || mkrActive() == false) {
return 0;
}
return safeSub(creditline, cdptab());
}
function remainingCredit() public returns (uint) {
if (creditline <= (cdptab()) || mkrActive() == false) {
return 0;
}
return safeSub(creditline, cdptab());
}
function collatDeficit() public returns (uint) {
uint lockedCollateralDAI = rmul(cdpink(), assessor.calcSeniorTokenPrice());
uint requiredCollateralDAI = calcOvercollAmount(cdptab());
if (requiredCollateralDAI > lockedCollateralDAI) {
return safeSub(requiredCollateralDAI, lockedCollateralDAI);
}
return 0;
}
function collatDeficit() public returns (uint) {
uint lockedCollateralDAI = rmul(cdpink(), assessor.calcSeniorTokenPrice());
uint requiredCollateralDAI = calcOvercollAmount(cdptab());
if (requiredCollateralDAI > lockedCollateralDAI) {
return safeSub(requiredCollateralDAI, lockedCollateralDAI);
}
return 0;
}
function remainingOvercollCredit() public returns (uint) {
return calcOvercollAmount(remainingCredit());
}
function juniorStake() public view returns (uint) {
if (mkrActive() == false) {
return 0;
}
return safeSub(rmul(cdpink(), assessor.calcSeniorTokenPrice()), cdptab());
}
function juniorStake() public view returns (uint) {
if (mkrActive() == false) {
return 0;
}
return safeSub(rmul(cdpink(), assessor.calcSeniorTokenPrice()), cdptab());
}
function raise(uint amountDAI) public auth active {
uint overcollAmountDAI = calcOvercollAmount(amountDAI);
uint protectionDAI = safeSub(overcollAmountDAI, amountDAI);
require((validate(0, protectionDAI, overcollAmountDAI, 0) == 0), "supply not possible, pool constraints violated");
creditline = safeAdd(creditline, amountDAI);
assessor.changeBorrowAmountEpoch(safeAdd(assessor.borrowAmountEpoch(), amountDAI));
}
function draw(uint amountDAI) public auth active {
require(amountDAI <= remainingCredit(), "not enough credit left");
uint collateralDAI = calcOvercollAmount(amountDAI);
uint collateralDROP = rdiv(collateralDAI, assessor.calcSeniorTokenPrice());
tranche.mint(address(this), collateralDROP);
collateral.approve(address(mgr), collateralDROP);
mgr.join(collateralDROP);
mgr.draw(amountDAI, address(this));
dai.approve(address(reserve), amountDAI);
reserve.hardDeposit(amountDAI);
updateSeniorAsset(0, collateralDAI);
}
function wipe(uint amountDAI) public auth active {
require((cdptab() > 0), "cdp debt already repaid");
if (amountDAI > cdptab()) {
amountDAI = cdptab();
}
mgr.wipe(amountDAI);
}
function wipe(uint amountDAI) public auth active {
require((cdptab() > 0), "cdp debt already repaid");
if (amountDAI > cdptab()) {
amountDAI = cdptab();
}
mgr.wipe(amountDAI);
}
reserve.hardPayout(amountDAI);
dai.approve(address(mgr), amountDAI);
harvest();
function harvest() public active {
require((cdpink() > 0), "nothing profit to harvest");
uint dropPrice = assessor.calcSeniorTokenPrice();
uint lockedCollateralDAI = rmul(cdpink(), dropPrice);
uint profitDAI = safeSub(lockedCollateralDAI, calcOvercollAmount(cdptab()));
uint profitDROP = rdiv(profitDAI, dropPrice);
mgr.exit(address(this), profitDROP);
collateral.burn(address(this), profitDROP);
updateSeniorAsset(profitDAI, 0);
}
function sink(uint amountDAI) public auth active {
require(remainingCredit() >= amountDAI, "decrease amount too high");
uint overcollAmountDAI = calcOvercollAmount(amountDAI);
uint protectionDAI = safeSub(overcollAmountDAI, amountDAI);
require((validate(protectionDAI, 0, 0, overcollAmountDAI) == 0), "pool constraints violated");
creditline = safeSub(creditline, amountDAI);
assessor.changeBorrowAmountEpoch(safeSub(assessor.borrowAmountEpoch(), amountDAI));
}
function heal(uint amountDAI) public auth active {
uint collatDeficitDAI = collatDeficit();
require(collatDeficitDAI > 0, "no healing required");
if (collatDeficitDAI < amountDAI) {
amountDAI = collatDeficitDAI;
}
require((validate(0, amountDAI, 0, 0) == 0), "supply not possible, pool constraints violated");
uint collateralDROP = rdiv(amountDAI, priceDROP);
tranche.mint(address(this), collateralDROP);
collateral.approve(address(mgr), collateralDROP);
mgr.join(collateralDROP);
}
function heal(uint amountDAI) public auth active {
uint collatDeficitDAI = collatDeficit();
require(collatDeficitDAI > 0, "no healing required");
if (collatDeficitDAI < amountDAI) {
amountDAI = collatDeficitDAI;
}
require((validate(0, amountDAI, 0, 0) == 0), "supply not possible, pool constraints violated");
uint collateralDROP = rdiv(amountDAI, priceDROP);
tranche.mint(address(this), collateralDROP);
collateral.approve(address(mgr), collateralDROP);
mgr.join(collateralDROP);
}
uint priceDROP = assessor.calcSeniorTokenPrice();
updateSeniorAsset(0, amountDAI);
function heal() public auth active{
uint collatDeficitDAI = collatDeficit();
if (collatDeficitDAI > 0) {
heal(collatDeficitDAI);
}
}
function heal() public auth active{
uint collatDeficitDAI = collatDeficit();
if (collatDeficitDAI > 0) {
heal(collatDeficitDAI);
}
}
function validate(uint juniorSupplyDAI, uint juniorRedeemDAI, uint seniorSupplyDAI, uint seniorRedeemDAI) internal returns(int) {
uint newAssets = safeSub(safeSub(safeAdd(safeAdd(safeAdd(assessor.totalBalance(), assessor.getNAV()), seniorSupplyDAI),
juniorSupplyDAI), juniorRedeemDAI), seniorRedeemDAI);
uint expectedSeniorAsset = assessor.calcExpectedSeniorAsset(seniorRedeemDAI, seniorSupplyDAI,
assessor.seniorBalance(), assessor.seniorDebt());
return coordinator.validateRatioConstraints(newAssets, expectedSeniorAsset);
}
function updateSeniorAsset(uint decreaseDAI, uint increaseDAI) internal {
assessor.changeSeniorAsset(increaseDAI, decreaseDAI);
}
function cdptab() public view returns (uint) {
(, uint art) = vat.urns(mgr.ilk(), address(mgr));
return rmul(art, stabilityFee());
}
function cdpink() public view returns (uint) {
(uint ink, ) = vat.urns(mgr.ilk(), address(mgr));
return ink;
}
function mat() public view returns (uint) {
(, uint256 mat) = spotter.ilks(mgr.ilk());
}
function calcOvercollAmount(uint amountDAI) public returns (uint) {
return rmul(amountDAI, mat());
}
function returnDAI() public auth {
uint amountDAI = dai.balanceOf(address(this));
dai.approve(address(reserve), amountDAI);
reserve.hardDeposit(amountDAI);
}
function changeOwnerMgr(address usr) public auth {
mgr.setOwner(usr);
}
function debt() public view returns(uint) {
return cdptab();
}
function stabilityFee() public view returns(uint) {
(, uint rate, , ,) = vat.ilks(mgr.ilk());
return rate;
}
}
| 8,877,044 |
[
1,
1896,
3844,
434,
463,
18194,
716,
848,
506,
324,
1899,
82,
628,
490,
47,
54,
268,
267,
80,
911,
20092,
490,
47,
54,
20092,
1613,
358,
527,
603,
1760,
434,
4834,
358,
4543,
7976,
84,
4501,
26595,
367,
516,
805,
404,
9,
4516,
4186,
848,
1338,
506,
2695,
309,
326,
268,
267,
80,
911,
2845,
353,
4551,
486,
316,
7632,
7647,
19,
25675,
19,
16414,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
16351,
385,
749,
79,
353,
3123,
16,
2361,
288,
203,
203,
565,
2254,
1071,
12896,
1369,
31,
203,
203,
565,
10320,
4240,
8804,
67,
21,
24794,
31,
203,
565,
4725,
403,
280,
8804,
67,
21,
1551,
403,
280,
31,
203,
565,
1124,
6527,
8804,
67,
21,
20501,
31,
203,
565,
840,
304,
18706,
8804,
67,
21,
13637,
18706,
31,
203,
203,
565,
8558,
8804,
13333,
31,
203,
565,
25299,
8804,
17359,
31,
203,
565,
26523,
387,
8804,
16463,
387,
31,
203,
203,
565,
4232,
39,
3462,
8804,
67,
21,
5248,
77,
31,
203,
565,
4232,
39,
3462,
8804,
67,
21,
4508,
2045,
287,
31,
203,
203,
565,
2254,
4834,
1892,
273,
374,
18,
1611,
380,
1728,
636,
5324,
31,
203,
203,
203,
565,
9606,
2695,
1435,
288,
2583,
12,
18836,
9334,
315,
12015,
17,
19506,
8863,
389,
31,
289,
203,
565,
445,
14892,
1435,
1071,
1476,
1135,
12,
6430,
13,
288,
203,
3639,
327,
24794,
18,
12684,
5027,
1435,
422,
629,
597,
5028,
86,
3896,
5621,
203,
565,
289,
203,
203,
565,
445,
5028,
86,
3896,
1435,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
13333,
18,
4626,
1435,
597,
13333,
18,
7043,
361,
1435,
597,
13333,
18,
16472,
5621,
203,
565,
289,
203,
203,
565,
3885,
12,
2867,
5248,
77,
67,
16,
1758,
4508,
2045,
287,
67,
13,
1071,
288,
203,
3639,
341,
14727,
63,
3576,
18,
15330,
65,
273,
404,
31,
203,
3639,
5248,
77,
273,
225,
4232,
39,
3462,
8804,
67,
21,
12,
2414,
77,
67,
1769,
203,
3639,
2
] |
pragma solidity ^0.4.0;
import '../../../node_modules/zeppelin-solidity/contracts/math/SafeMath.sol';
import "../DAOLib.sol";
import "../../Token/TokenInterface.sol";
import "../CrowdsaleDAOFields.sol";
contract VotingDecisions is CrowdsaleDAOFields {
/*
* @dev Transfers withdrawal sum in ether or DXC tokens to the whitelisted address. Calls from Withdrawal proposal
* @param _address Whitelisted address
* @param _withdrawalSum Amount of ether/DXC to be sent
* @param _dxc Should withdrawal be in DXC tokens
*/
function withdrawal(address _address, uint _withdrawalSum, bool _dxc) notInRefundableState onlyVoting external {
lastWithdrawalTimestamp = block.timestamp;
_dxc ? DXC.transfer(_address, _withdrawalSum) : _address.transfer(_withdrawalSum);
}
/*
* @dev Change DAO's mode to `refundable`. Can be called by any tokenholder
*/
function makeRefundableByUser() external {
require(lastWithdrawalTimestamp == 0 && block.timestamp >= created_at + withdrawalPeriod
|| lastWithdrawalTimestamp != 0 && block.timestamp >= lastWithdrawalTimestamp + withdrawalPeriod);
makeRefundable();
}
/*
* @dev Change DAO's mode to `refundable`. Calls from Refund proposal
*/
function makeRefundableByVotingDecision() external onlyVoting {
makeRefundable();
}
/*
* @dev Change DAO's mode to `refundable`. Calls from this contract `makeRefundableByUser` or `makeRefundableByVotingDecision` functions
*/
function makeRefundable() notInRefundableState private {
refundable = true;
newEtherRate = SafeMath.mul(this.balance * etherRate, multiplier) / tokensMintedByEther;
newDXCRate = tokensMintedByDXC != 0 ? SafeMath.mul(DXC.balanceOf(this) * DXCRate, multiplier) / tokensMintedByDXC : 0;
}
/*
* @dev Make tokens of passed address non-transferable for passed period
* @param _address Address of tokenholder
* @param _duration Hold's duration in seconds
*/
function holdTokens(address _address, uint _duration) onlyVoting external {
token.hold(_address, _duration);
}
/*
* @dev Throws if called not by any voting contract
*/
modifier onlyVoting() {
require(votings[msg.sender]);
_;
}
/*
* @dev Throws if DAO is in refundable state
*/
modifier notInRefundableState {
require(!refundable && !refundableSoftCap);
_;
}
}
|
@dev Throws if called not by any voting contract/
|
modifier onlyVoting() {
require(votings[msg.sender]);
_;
}
| 14,043,329 |
[
1,
21845,
309,
2566,
486,
635,
1281,
331,
17128,
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,
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,
9606,
1338,
58,
17128,
1435,
288,
203,
3639,
2583,
12,
90,
352,
899,
63,
3576,
18,
15330,
19226,
203,
3639,
389,
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
] |
/// SPDX-License-Identifier: MIT
pragma solidity >=0.5.16 ^0.8.0;
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title Marketplace for second hand ticket resale
/// @author Jasmine Sabio
/// @notice Allows a user to sell a ticket or to buy a ticket
/// @dev Functional calls are implemented without side effects. This contract in herits Open Zeppelin's Pausable and Ownable.
contract Jaslist is Pausable, Ownable {
/// @dev Tracks total amount of items. itemCount is also used for item ID (sku).
uint public itemCount;
/// @dev Locks or unlocks account to pause account.
bool internal locked;
/// @dev Maps item number in item count to an item struct.
mapping (uint => Item) public items;
/// @dev Maps item number in item count to item owner.
mapping (uint => address) itemToOwner;
struct Item {
string name;
string description;
uint sku;
uint price;
address payable itemOwner;
bool purchased;
}
constructor() Pausable() Ownable() {
itemCount = 0;
}
/// @notice Event emitted when an item is added
/// @param _name Item name
/// @param _description Item description (location, date)
/// @param _sku Item ID (item count)
/// @param _price Item price in ETH
/// @param _itemOwner Item owner
/// @param _purchased Is item purchased?
event LogItemAdded(
string _name,
string _description,
uint _sku,
uint _price,
address payable _itemOwner,
bool _purchased
);
/// @notice Event emitted when an item is sold
/// @param _name Item name
/// @param _description Item description (location, date)
/// @param _sku Item ID (item count)
/// @param _price Item price in ETH
/// @param _itemOwner Item owner
/// @param _purchased Is item purchased?
event LogItemSold(
string _name,
string _description,
uint _sku,
uint _price,
address payable _itemOwner,
bool _purchased
);
/// @dev Protects function when ETH is transferred from reentrancy attacks
modifier noReentrant() {
require(!locked, "No re-entrancy");
locked = true;
_;
locked = false;
}
/// @dev Checks if buyer has enough ETH before executing the buying function
modifier paidEnough(uint _price) {
require(msg.value >= _price);
_;
}
/// @dev Refunds excess ETH if buyer paid too much
modifier checkValue(uint _sku) {
_;
uint _price = items[_sku].price;
uint amountToRefund = msg.value - _price;
address payable buyer = payable(msg.sender);
buyer.transfer(amountToRefund);
}
/// @notice Adds item to contract state
/// @param _name Item name
/// @param _description Item description
/// @param _price Item price in ETH
function addItem(string memory _name, string memory _description, uint _price) public whenNotPaused() returns (bool) {
itemCount += 1;
require(bytes(_name).length > 0);
require(_price > 0);
items[itemCount] = Item({
name: _name,
description: _description,
sku: itemCount,
price: _price,
itemOwner: payable(msg.sender),
purchased: false
});
emit LogItemAdded(_name, _description, items[itemCount].sku, _price, items[itemCount].itemOwner, items[itemCount].purchased);
return true;
}
/// @notice Buys item and ETH is transferred from the buyer to the seller
/// @param _sku Item ID (item count)
function buyItem(uint _sku) public payable paidEnough(items[_sku].price) checkValue(_sku) noReentrant() whenNotPaused() {
address payable _seller = items[_sku].itemOwner;
require(_sku >= 0 && _sku <= itemCount);
require(items[_sku].purchased == false);
require(_seller != msg.sender);
_seller.transfer(items[_sku].price);
items[_sku].itemOwner = payable(msg.sender);
items[_sku].purchased = true;
emit LogItemSold(items[_sku].name, items[_sku].description, items[_sku].sku, items[_sku].price, items[_sku].itemOwner, items[_sku].purchased);
}
/// @dev Pauses contract from further transaction; only executed by contract owner
function pauseTransactions() private onlyOwner() {
_pause();
}
/// @notice Ticket becomes unavaiable to be purchased
/// @param _sku Item ID (item count)
/// @dev Clears struct for item and ticket name is updated to "ticket unavailable"
function removeItem(uint _sku) public {
require(items[_sku].itemOwner == msg.sender);
delete items[_sku];
items[_sku].name = "ticket unavailable";
}
/// @notice Updates a seller's item price
/// @dev Only item owner can call this
function updateItemPrice() public {
// TODO: allows seller to update the price of their item
}
/// @notice Loads list of items the user owns
function getItemsByOwner() public {
// TODO: fetches list of items that the owner has
}
}
|
@dev Protects function when ETH is transferred from reentrancy attacks
|
modifier noReentrant() {
require(!locked, "No re-entrancy");
locked = true;
_;
locked = false;
}
| 5,514,976 |
[
1,
29599,
87,
445,
1347,
512,
2455,
353,
906,
4193,
628,
283,
8230,
12514,
28444,
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,
9606,
1158,
426,
8230,
970,
1435,
288,
203,
3639,
2583,
12,
5,
15091,
16,
315,
2279,
283,
17,
8230,
12514,
8863,
203,
3639,
8586,
273,
638,
31,
203,
3639,
389,
31,
203,
3639,
8586,
273,
629,
31,
203,
565,
289,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.7;
/// @author jpegmint.xyz
import "./IRoyaltiesERC2981.sol";
import "./IRoyaltiesManifold.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
abstract contract ERC721RoyaltiesUpgradeable is Initializable, ERC721Upgradeable, IRoyaltiesERC2981, IRoyaltiesManifold {
address private _royaltiesRecipient;
uint256 private _royaltiesBasisPoints;
function __ERC721Royalties_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Royalties_init_unchained();
}
function __ERC721Royalties_init_unchained() internal initializer {
}
/**
* @dev see {IERC165-supportsInterface}
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return
interfaceId == type(IRoyaltiesERC2981).interfaceId ||
interfaceId == type(IRoyaltiesManifold).interfaceId ||
super.supportsInterface(interfaceId)
;
}
/**
* @dev See {IRoyaltiesERC2981-royaltyInfo}.
*/
function royaltyInfo(uint256 tokenId, uint256 value) external view override returns (address, uint256) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyaltyInfo(tokenId, value);
}
/**
* @dev See {IRoyaltiesCreatorCore-getRoyalties}.
*/
function getRoyalties(uint256 tokenId) external view override returns (address payable[] memory, uint256[] memory) {
require(_exists(tokenId), "Nonexistent token");
return _getRoyalties(tokenId);
}
/**
* @dev Override with access control to set royalties.
*/
function setRoyalties(address recipient, uint256 basisPoints) external virtual;
/**
* @dev Set contract-wide royalties.
*/
function _setRoyalties(address recipient, uint256 basisPoints) internal {
require(basisPoints <= 10000, 'Royalties: Too high');
_royaltiesRecipient = recipient;
_royaltiesBasisPoints = basisPoints;
}
/**
* @dev Calculates royalties using contract-wide setting.
*/
function _getRoyaltyInfo(uint256, uint256 value) internal view returns (address, uint256) {
uint256 royaltyAmount = (value * _royaltiesBasisPoints) / 10000;
return (_royaltiesRecipient, royaltyAmount);
}
/**
* @dev Returns contract-wide royalties.
*/
function _getRoyalties(uint256) internal view returns (address payable[] memory, uint256[] memory) {
uint256[] memory royaltyBasisPoints = new uint[](1);
address payable[] memory royaltyReceivers = new address payable[](1);
royaltyBasisPoints[0] = _royaltiesBasisPoints;
royaltyReceivers[0] = payable(_royaltiesRecipient);
return (royaltyReceivers, royaltyBasisPoints);
}
}
|
* @dev Returns contract-wide royalties./
|
function _getRoyalties(uint256) internal view returns (address payable[] memory, uint256[] memory) {
uint256[] memory royaltyBasisPoints = new uint[](1);
address payable[] memory royaltyReceivers = new address payable[](1);
royaltyBasisPoints[0] = _royaltiesBasisPoints;
royaltyReceivers[0] = payable(_royaltiesRecipient);
return (royaltyReceivers, royaltyBasisPoints);
}
| 12,667,335 |
[
1,
1356,
6835,
17,
26767,
721,
93,
2390,
606,
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,
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,
389,
588,
54,
13372,
2390,
606,
12,
11890,
5034,
13,
2713,
1476,
1135,
261,
2867,
8843,
429,
8526,
3778,
16,
2254,
5034,
8526,
3778,
13,
288,
203,
203,
3639,
2254,
5034,
8526,
3778,
721,
93,
15006,
11494,
291,
5636,
273,
394,
2254,
8526,
12,
21,
1769,
203,
3639,
1758,
8843,
429,
8526,
3778,
721,
93,
15006,
4779,
6760,
273,
394,
1758,
8843,
429,
8526,
12,
21,
1769,
203,
203,
3639,
721,
93,
15006,
11494,
291,
5636,
63,
20,
65,
273,
389,
3800,
2390,
606,
11494,
291,
5636,
31,
203,
3639,
721,
93,
15006,
4779,
6760,
63,
20,
65,
273,
8843,
429,
24899,
3800,
2390,
606,
18241,
1769,
203,
203,
3639,
327,
261,
3800,
15006,
4779,
6760,
16,
721,
93,
15006,
11494,
291,
5636,
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
] |
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 {}
}
|
* 0x5b5e139f === bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('tokenURI(uint256)'))/* @dev Constructor function/ register the supported interfaces to conform to ERC721 via ERC165
|
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_registerInterface(InterfaceId_ERC721Metadata);
}
| 911,799 |
[
1,
20,
92,
25,
70,
25,
73,
24347,
74,
757,
377,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
529,
11866,
3719,
3602,
377,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
7175,
11866,
3719,
3602,
377,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
2316,
3098,
12,
11890,
5034,
2506,
3719,
19,
225,
11417,
445,
19,
1744,
326,
3260,
7349,
358,
20156,
358,
4232,
39,
27,
5340,
3970,
4232,
39,
28275,
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,
3885,
261,
1080,
3778,
508,
16,
533,
3778,
3273,
13,
1071,
288,
203,
3639,
389,
529,
273,
508,
31,
203,
3639,
389,
7175,
273,
3273,
31,
203,
203,
3639,
389,
4861,
1358,
12,
1358,
548,
67,
654,
39,
27,
5340,
2277,
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
] |
pragma solidity 0.6.12; // optimization runs: 200, evm version: istanbul
pragma experimental ABIEncoderV2;
interface DharmaTradeBotV1Interface {
event LimitOrderProcessed(
address indexed account,
address indexed suppliedAsset, // Ether = address(0)
address indexed receivedAsset, // Ether = address(0)
uint256 suppliedAmount,
uint256 receivedAmount,
bytes32 orderID
);
event LimitOrderCancelled(bytes32 orderID);
event RoleModified(Role indexed role, address account);
event RolePaused(Role indexed role);
event RoleUnpaused(Role indexed role);
enum Role {
BOT_COMMANDER,
CANCELLER,
PAUSER
}
struct RoleStatus {
address account;
bool paused;
}
struct LimitOrderArguments {
address account;
address assetToSupply; // Ether = address(0)
address assetToReceive; // Ether = address(0)
uint256 maximumAmountToSupply;
uint256 maximumPriceToAccept; // represented as a mantissa (n * 10^18)
uint256 expiration;
bytes32 salt;
}
struct LimitOrderExecutionArguments {
uint256 amountToSupply; // will be lower than maximum for partial fills
bytes signatures;
address tradeTarget;
bytes tradeData;
}
function processLimitOrder(
LimitOrderArguments calldata args,
LimitOrderExecutionArguments calldata executionArgs
) external returns (uint256 amountReceived);
function cancelLimitOrder(LimitOrderArguments calldata args) external;
function setRole(Role role, address account) external;
function removeRole(Role role) external;
function pause(Role role) external;
function unpause(Role role) external;
function isPaused(Role role) external view returns (bool paused);
function isRole(Role role) external view returns (bool hasRole);
function getOrderID(
LimitOrderArguments calldata args
) external view returns (bytes32 orderID, bool valid);
function getBotCommander() external view returns (address botCommander);
function getCanceller() external view returns (address canceller);
function getPauser() external view returns (address pauser);
}
interface SupportingContractInterface {
function setApproval(address token, uint256 amount) external;
}
interface ERC1271Interface {
function isValidSignature(
bytes calldata data, bytes calldata signatures
) external view returns (bytes4 magicValue);
}
interface ERC20Interface {
function transfer(address, uint256) external returns (bool);
function transferFrom(address, address, uint256) external returns (bool);
function approve(address, uint256) external returns (bool);
function balanceOf(address) external view returns (uint256);
function allowance(address, address) external view returns (uint256);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
}
/**
* @notice Contract module which provides a basic access control mechanism,
* where there is an account (an owner) that can be granted exclusive access
* to specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*
* In order to transfer ownership, a recipient must be specified, at which point
* the specified recipient can call `acceptOwnership` and take ownership.
*/
contract TwoStepOwnable {
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
address private _owner;
address private _newPotentialOwner;
/**
* @notice Initialize contract with transaction submitter as initial owner.
*/
constructor() internal {
_owner = tx.origin;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @notice Allows a new account (`newOwner`) to accept ownership.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) external onlyOwner {
require(
newOwner != address(0),
"TwoStepOwnable: new potential owner is the zero address."
);
_newPotentialOwner = newOwner;
}
/**
* @notice Cancel a transfer of ownership to a new account.
* Can only be called by the current owner.
*/
function cancelOwnershipTransfer() external onlyOwner {
delete _newPotentialOwner;
}
/**
* @notice Transfers ownership of the contract to the caller.
* Can only be called by a new potential owner set by the current owner.
*/
function acceptOwnership() external {
require(
msg.sender == _newPotentialOwner,
"TwoStepOwnable: current owner must set caller as new potential owner."
);
delete _newPotentialOwner;
emit OwnershipTransferred(_owner, msg.sender);
_owner = msg.sender;
}
/**
* @notice Returns the address of the current owner.
*/
function owner() external view returns (address) {
return _owner;
}
/**
* @notice Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @notice Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "TwoStepOwnable: caller is not the owner.");
_;
}
}
/**
* @title DharmaTradeBotV1Staging
* @author 0age
* @notice DharmaTradeBot is a contract for performing meta-transaction-enabled
* limit orders against external automated money markets or other sources of
* on-chain liquidity. Eth-to-Token trades require that `triggerEtherTransfer`
* is implemented on the account making the trade, and all trades require
* that the account implements `isValidSignature` as specified by ERC-1271,
* as well as a `setApproval` function, in order to enable meta-transactions.
* For Eth-to-token trades, the Eth amount is forwarded as part of the trade.
*/
contract DharmaTradeBotV1Staging is DharmaTradeBotV1Interface, TwoStepOwnable {
using SafeMath for uint256;
// Maintain a role status mapping with assigned accounts and paused states.
mapping(uint256 => RoleStatus) private _roles;
// Maintain a mapping of invalid meta-transaction order IDs.
mapping (bytes32 => bool) private _invalidMetaTxHashes;
ERC20Interface private constant _ETHERIZER = ERC20Interface(
0x723B51b72Ae89A3d0c2a2760f0458307a1Baa191
);
bool public constant staging = true;
receive() external payable {}
/**
* @notice Only callable by the bot commander or the owner. Enforces the
* expiration (or skips if it is set to zero) and trade size, validates
* the execution signatures using ERC-1271 against the account, sets
* approval to transfer the supplied token on behalf of that account,
* pulls in the necessary supplied tokens, sets an allowance for the
* provided trade target, calls the trade target with supplied data,
* ensures that the call was successful, calculates the required amount
* that must be received back based on the supplied amount and price,
* ensures that at least that amount was returned, sends it to the
* account, and emits an event. Use the null address to signify that
* the supplied or retained asset is Ether.
* @return amountReceived The amount received back from the trade.
*/
function processLimitOrder(
LimitOrderArguments calldata args,
LimitOrderExecutionArguments calldata executionArgs
) external override onlyOwnerOr(Role.BOT_COMMANDER) returns (
uint256 amountReceived
) {
_enforceExpiration(args.expiration);
require(
executionArgs.amountToSupply <= args.maximumAmountToSupply,
"Cannot supply more than the maximum authorized amount."
);
require(
args.assetToSupply != args.assetToReceive,
"Asset to supply and asset to receive cannot be identical."
);
if (executionArgs.tradeData.length >= 4) {
require(
abi.decode(
abi.encodePacked(executionArgs.tradeData[:4], bytes28(0)), (bytes4)
) != SupportingContractInterface.setApproval.selector,
"Trade data has a prohibited function selector."
);
}
// Construct order's "context" and use it to validate meta-transaction.
bytes memory context = _constructLimitOrderContext(args);
bytes32 orderID = _validateMetaTransaction(
args.account, context, executionArgs.signatures
);
// Determine asset supplied (use Etherizer for Ether) and ether value.
ERC20Interface assetToSupply;
uint256 etherValue;
if (args.assetToSupply == address(0)) {
assetToSupply = _ETHERIZER;
etherValue = executionArgs.amountToSupply;
} else {
assetToSupply = ERC20Interface(args.assetToSupply);
etherValue = 0;
// Ensure that target has allowance to transfer tokens.
_grantApprovalIfNecessary(
assetToSupply, executionArgs.tradeTarget, executionArgs.amountToSupply
);
}
// Call `setApproval` on the supplying account.
SupportingContractInterface(args.account).setApproval(
address(assetToSupply), executionArgs.amountToSupply
);
// Make the transfer in.
_transferInToken(
assetToSupply, args.account, executionArgs.amountToSupply
);
// Call into target, supplying data and value, and revert on failure.
_performCallToTradeTarget(
executionArgs.tradeTarget, executionArgs.tradeData, etherValue
);
// Determine amount expected back using supplied amount and price.
uint256 amountExpected = (
executionArgs.amountToSupply.mul(1e18)
).div(
args.maximumPriceToAccept
);
if (args.assetToReceive == address(0)) {
// Determine ether balance held by this contract.
amountReceived = address(this).balance;
// Ensure that enough Ether was received.
require(
amountReceived >= amountExpected,
"Trade did not result in the expected amount of Ether."
);
// Transfer the Ether out and revert on failure.
_transferEther(args.account, amountReceived);
} else {
ERC20Interface assetToReceive = ERC20Interface(args.assetToReceive);
// Determine balance of received tokens held by this contract.
amountReceived = assetToReceive.balanceOf(address(this));
// Ensure that enough tokens were received.
require(
amountReceived >= amountExpected,
"Trade did not result in the expected amount of tokens."
);
// Transfer the tokens and revert on failure.
_transferOutToken(assetToReceive, args.account, amountReceived);
}
emit LimitOrderProcessed(
args.account,
args.assetToSupply,
args.assetToReceive,
executionArgs.amountToSupply,
amountReceived,
orderID
);
}
/**
* @notice Cancels a potential limit order. Only the owner, the account
* in question, or the canceller role may call this function.
*/
function cancelLimitOrder(
LimitOrderArguments calldata args
) external override onlyOwnerOrAccountOr(Role.CANCELLER, args.account) {
_enforceExpiration(args.expiration);
// Construct the order ID using relevant "context" of the limit order.
bytes32 orderID = keccak256(_constructLimitOrderContext(args));
// Ensure the order ID has not been used or cancelled and invalidate it.
require(
!_invalidMetaTxHashes[orderID], "Meta-transaction already invalid."
);
_invalidMetaTxHashes[orderID] = true;
emit LimitOrderCancelled(orderID);
}
/**
* @notice Pause a currently unpaused role and emit a `RolePaused` event. Only
* the owner or the designated pauser may call this function. Also, bear in
* mind that only the owner may unpause a role once paused.
* @param role The role to pause.
*/
function pause(Role role) external override onlyOwnerOr(Role.PAUSER) {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(!storedRoleStatus.paused, "Role in question is already paused.");
storedRoleStatus.paused = true;
emit RolePaused(role);
}
/**
* @notice Unpause a currently paused role and emit a `RoleUnpaused` event.
* Only the owner may call this function.
* @param role The role to pause.
*/
function unpause(Role role) external override onlyOwner {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
require(storedRoleStatus.paused, "Role in question is already unpaused.");
storedRoleStatus.paused = false;
emit RoleUnpaused(role);
}
/**
* @notice Set a new account on a given role and emit a `RoleModified` event
* if the role holder has changed. Only the owner may call this function.
* @param role The role that the account will be set for.
* @param account The account to set as the designated role bearer.
*/
function setRole(Role role, address account) external override onlyOwner {
require(account != address(0), "Must supply an account.");
_setRole(role, account);
}
/**
* @notice Remove any current role bearer for a given role and emit a
* `RoleModified` event if a role holder was previously set. Only the owner
* may call this function.
* @param role The role that the account will be removed from.
*/
function removeRole(Role role) external override onlyOwner {
_setRole(role, address(0));
}
/**
* @notice View function to determine an order's meta-transaction message hash
* and to determine if it is still valid (i.e. it has not yet been used and is
* not expired). The returned order ID will need to be prefixed using EIP-191
* 0x45 and hashed again in order to generate a final digest for the required
* signature - in other words, the same procedure utilized by `eth_Sign`.
* @return orderID The ID corresponding to the limit order's meta-transaction.
*/
function getOrderID(
LimitOrderArguments calldata args
) external view override returns (bytes32 orderID, bool valid) {
// Construct the order ID based on relevant context.
orderID = keccak256(_constructLimitOrderContext(args));
// The meta-transaction is valid if it has not been used and is not expired.
valid = (
!_invalidMetaTxHashes[orderID] && (
args.expiration == 0 || block.timestamp <= args.expiration
)
);
}
/**
* @notice External view function to check whether or not the functionality
* associated with a given role is currently paused or not. The owner or the
* pauser may pause any given role (including the pauser itself), but only the
* owner may unpause functionality. Additionally, the owner may call paused
* functions directly.
* @param role The role to check the pause status on.
* @return paused A boolean to indicate if the functionality associated with
* the role in question is currently paused.
*/
function isPaused(Role role) external view override returns (bool paused) {
paused = _isPaused(role);
}
/**
* @notice External view function to check whether the caller is the current
* role holder.
* @param role The role to check for.
* @return hasRole A boolean indicating if the caller has the specified role.
*/
function isRole(Role role) external view override returns (bool hasRole) {
hasRole = _isRole(role);
}
/**
* @notice External view function to check the account currently holding the
* bot commander role. The bot commander can execute limit orders.
* @return botCommander The address of the current bot commander, or the null
* address if none is set.
*/
function getBotCommander() external view override returns (
address botCommander
) {
botCommander = _roles[uint256(Role.BOT_COMMANDER)].account;
}
/**
* @notice External view function to check the account currently holding the
* canceller role. The canceller can cancel limit orders.
* @return canceller The address of the current canceller, or the null
* address if none is set.
*/
function getCanceller() external view override returns (
address canceller
) {
canceller = _roles[uint256(Role.CANCELLER)].account;
}
/**
* @notice External view function to check the account currently holding the
* pauser role. The pauser can pause any role from taking its standard action,
* though the owner will still be able to call the associated function in the
* interim and is the only entity able to unpause the given role once paused.
* @return pauser The address of the current pauser, or the null address if
* none is set.
*/
function getPauser() external view override returns (address pauser) {
pauser = _roles[uint256(Role.PAUSER)].account;
}
/**
* @notice Private function to enforce that a given meta-transaction
* has not been used before and that the signature is valid according
* to the account in question (using ERC-1271).
* @param account address The account originating the meta-transaction.
* @param context bytes Information about the meta-transaction.
* @param signatures bytes Signature or signatures used to validate
* the meta-transaction.
*/
function _validateMetaTransaction(
address account, bytes memory context, bytes memory signatures
) private returns (bytes32 orderID) {
// Construct the order ID using the provided context.
orderID = keccak256(context);
// Ensure ID has not been used or cancelled and invalidate it.
require(
!_invalidMetaTxHashes[orderID], "Order is no longer valid."
);
_invalidMetaTxHashes[orderID] = true;
// Construct the digest to compare signatures against using EIP-191 0x45.
bytes32 digest = keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", orderID)
);
// Validate via ERC-1271 against the specified account.
bytes memory data = abi.encode(digest, context);
bytes4 magic = ERC1271Interface(account).isValidSignature(data, signatures);
require(magic == bytes4(0x20c13b0b), "Invalid signatures.");
}
/**
* @notice Private function to set a new account on a given role and emit a
* `RoleModified` event if the role holder has changed.
* @param role The role that the account will be set for.
* @param account The account to set as the designated role bearer.
*/
function _setRole(Role role, address account) private {
RoleStatus storage storedRoleStatus = _roles[uint256(role)];
if (account != storedRoleStatus.account) {
storedRoleStatus.account = account;
emit RoleModified(role, account);
}
}
/**
* @notice Private function to perform a call to a given trade target, supplying
* given data and value, and revert with reason on failure.
*/
function _performCallToTradeTarget(
address target, bytes memory data, uint256 etherValue
) private {
// Call into the provided target, supplying provided data.
(bool tradeTargetCallSuccess,) = target.call{value: etherValue}(data);
// Revert with reason if the call was not successful.
if (!tradeTargetCallSuccess) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
} else {
// Ensure that the target is a contract.
uint256 returnSize;
assembly { returnSize := returndatasize() }
if (returnSize == 0) {
uint256 size;
assembly { size := extcodesize(target) }
require(size > 0, "Specified target does not have contract code.");
}
}
}
/**
* @notice Private function to set approval for a given target to transfer tokens
* on behalf of this contract. It should generally be assumed that this contract
* is highly permissive when it comes to approvals.
*/
function _grantApprovalIfNecessary(
ERC20Interface token, address target, uint256 amount
) private {
if (token.allowance(address(this), target) < amount) {
// Try removing approval first as a workaround for unusual tokens.
(bool success, bytes memory returnData) = address(token).call(
abi.encodeWithSelector(
token.approve.selector, target, uint256(0)
)
);
// Grant approval to transfer tokens on behalf of this contract.
(success, returnData) = address(token).call(
abi.encodeWithSelector(
token.approve.selector, target, type(uint256).max
)
);
if (!success) {
// Some really janky tokens only allow setting approval up to current balance.
(success, returnData) = address(token).call(
abi.encodeWithSelector(
token.approve.selector, target, amount
)
);
}
require(
success && (returnData.length == 0 || abi.decode(returnData, (bool))),
"Token approval to trade against the target failed."
);
}
}
/**
* @notice Private function to transfer tokens out of this contract.
*/
function _transferOutToken(ERC20Interface token, address to, uint256 amount) private {
(bool success, bytes memory returnData) = address(token).call(
abi.encodeWithSelector(token.transfer.selector, to, amount)
);
if (!success) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
if (returnData.length == 0) {
uint256 size;
assembly { size := extcodesize(token) }
require(size > 0, "Token specified to transfer out does not have contract code.");
} else {
require(abi.decode(returnData, (bool)), 'Token transfer out failed.');
}
}
/**
* @notice Private function to transfer Ether out of this contract.
*/
function _transferEther(address recipient, uint256 etherAmount) private {
// Send Ether to recipient and revert with reason on failure.
(bool ok, ) = recipient.call{value: etherAmount}("");
if (!ok) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
}
/**
* @notice Private function to transfer tokens into this contract.
*/
function _transferInToken(ERC20Interface token, address from, uint256 amount) private {
(bool success, bytes memory returnData) = address(token).call(
abi.encodeWithSelector(token.transferFrom.selector, from, address(this), amount)
);
if (!success) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
if (returnData.length == 0) {
uint256 size;
assembly { size := extcodesize(token) }
require(size > 0, "Token specified to transfer in does not have contract code.");
} else {
require(abi.decode(returnData, (bool)), 'Token transfer in failed.');
}
}
/**
* @notice Private view function to check whether the caller is the current
* role holder.
* @param role The role to check for.
* @return hasRole A boolean indicating if the caller has the specified role.
*/
function _isRole(Role role) private view returns (bool hasRole) {
hasRole = msg.sender == _roles[uint256(role)].account;
}
/**
* @notice Private view function to check whether the given role is paused or
* not.
* @param role The role to check for.
* @return paused A boolean indicating if the specified role is paused or not.
*/
function _isPaused(Role role) private view returns (bool paused) {
paused = _roles[uint256(role)].paused;
}
/**
* @notice Private view function to construct the "context" or details that
* need to be included when generating the order ID.
* @return context bytes The context.
*/
function _constructLimitOrderContext(
LimitOrderArguments memory args
) private view returns (bytes memory context) {
context = abi.encode(
address(this),
args.account,
args.assetToSupply,
args.assetToReceive,
args.maximumAmountToSupply,
args.maximumPriceToAccept,
args.expiration,
args.salt
);
}
/**
* @notice Private view function to ensure that a given expiration has
* not elapsed, or is set to zero (signifying no expiration).
*/
function _enforceExpiration(uint256 expiration) private view {
require(
expiration == 0 || block.timestamp <= expiration,
"Order has expired."
);
}
/**
* @notice Modifier that throws if called by any account other than the owner
* or the supplied role, or if the caller is not the owner and the role in
* question is paused.
* @param role The role to require unless the caller is the owner. Permitted
* roles are bot commander (0), and canceller (1), and pauser (2).
*/
modifier onlyOwnerOr(Role role) {
if (!isOwner()) {
require(_isRole(role), "Caller does not have a required role.");
require(!_isPaused(role), "Role in question is currently paused.");
}
_;
}
/**
* @notice Modifier that throws if called by any account other than the owner,
* a specified account, or the supplied role, or if the caller is not the
* owner or the specified account and the role in question is paused.
* @param role The role to require unless the caller is the owner or the
* specified account. Permitted roles are bot commander (0), and canceller (1),
* and pauser (2).
*/
modifier onlyOwnerOrAccountOr(Role role, address account) {
if (!isOwner() && !(msg.sender == account)) {
require(_isRole(role), "Caller does not have a required role.");
require(!_isPaused(role), "Role in question is currently paused.");
}
_;
}
}
|
* @notice External view function to check the account currently holding the canceller role. The canceller can cancel limit orders. @return canceller The address of the current canceller, or the null address if none is set./
|
function getCanceller() external view override returns (
address canceller
) {
canceller = _roles[uint256(Role.CANCELLER)].account;
}
| 7,890,655 |
[
1,
6841,
1476,
445,
358,
866,
326,
2236,
4551,
19918,
326,
3755,
749,
2478,
18,
1021,
3755,
749,
848,
3755,
1800,
11077,
18,
327,
3755,
749,
1021,
1758,
434,
326,
783,
3755,
749,
16,
578,
326,
446,
1758,
309,
6555,
353,
444,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
225,
445,
12006,
2183,
749,
1435,
3903,
1476,
3849,
1135,
261,
203,
565,
1758,
3755,
749,
203,
225,
262,
288,
203,
565,
3755,
749,
273,
389,
7774,
63,
11890,
5034,
12,
2996,
18,
39,
4722,
4503,
654,
13,
8009,
4631,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/libs/Eidas.sol
pragma solidity 0.4.23;
library Eidas {
enum EidasLevel { Null, Reputational, Low, Substantial, High }
/*function onlyReputational(EidasLevel _eidasLevel) returns (bool) {
return (_eidasLevel == EidasLevel.Reputational);
}
function onlyLow(EidasLevel _eidasLevel) returns (bool) {
return (_eidasLevel == EidasLevel.Low);
}
function onlySubstantial(EidasLevel _eidasLevel) returns (bool) {
return (_eidasLevel == EidasLevel.Substantial);
}
function onlyHigh(EidasLevel _eidasLevel) returns (bool) {
return (_eidasLevel == EidasLevel.High);
}*/
function atLeastLow(EidasLevel _eidasLevel) public pure returns (bool) {
return atLeast(_eidasLevel, EidasLevel.Low);
}
/*function alLeastSubstantial(EidasLevel _eidasLevel) returns (bool) {
return atLeast(_eidasLevel, EidasLevel.Substantial);
}
function alLeastHigh(EidasLevel _eidasLevel) returns (bool) {
return atLeast(_eidasLevel, EidasLevel.High);
}*/
function atLeast(EidasLevel _eidasLevel, EidasLevel _level) public pure returns (bool) {
return (uint(_eidasLevel) >= uint(_level));
}
/*function notNull(EidasLevel _eidasLevel) returns (bool) {
return _eidasLevel != EidasLevel.Null;
}
function toEidasLevel(uint _level) returns (EidasLevel) {
return EidasLevel(_level);
}*/
}
// File: contracts/identityManager/AlastriaIdentityServiceProvider.sol
pragma solidity 0.4.23;
contract AlastriaIdentityServiceProvider {
using Eidas for Eidas.EidasLevel;
mapping(address => bool) internal providers;
modifier onlyIdentityServiceProvider(address _identityServiceProvider) {
require (isIdentityServiceProvider(_identityServiceProvider));
_;
}
modifier notIdentityServiceProvider(address _identityServiceProvider) {
require (!isIdentityServiceProvider(_identityServiceProvider));
_;
}
constructor () public {
providers[msg.sender] = true;
}
function addIdentityServiceProvider(address _identityServiceProvider) public onlyIdentityServiceProvider(msg.sender) notIdentityServiceProvider(_identityServiceProvider) {
providers[_identityServiceProvider] = true;
}
function deleteIdentityServiceProvider(address _identityServiceProvider) public onlyIdentityServiceProvider(_identityServiceProvider) onlyIdentityServiceProvider(msg.sender) {
providers[_identityServiceProvider] = false;
}
function isIdentityServiceProvider(address _identityServiceProvider) public constant returns (bool) {
return providers[_identityServiceProvider];
}
}
// File: contracts/identityManager/AlastriaIdentityIssuer.sol
pragma solidity 0.4.23;
contract AlastriaIdentityIssuer {
using Eidas for Eidas.EidasLevel;
struct IdentityIssuer {
Eidas.EidasLevel level;
bool active;
}
mapping(address => IdentityIssuer) internal issuers;
modifier onlyIdentityIssuer(address _identityIssuer) {
require (issuers[_identityIssuer].active);
_;
}
modifier notIdentityIssuer(address _identityIssuer) {
require (!issuers[_identityIssuer].active);
_;
}
modifier alLeastLow(Eidas.EidasLevel _level) {
require (_level.atLeastLow());
_;
}
constructor () public {
IdentityIssuer storage identityIssuer;
identityIssuer.level = Eidas.EidasLevel.High;
identityIssuer.active = true;
issuers[msg.sender] = identityIssuer;
}
function addIdentityIssuer(address _identityIssuer, Eidas.EidasLevel _level) public alLeastLow(_level) notIdentityIssuer(_identityIssuer) onlyIdentityIssuer(msg.sender) {
IdentityIssuer storage identityIssuer = issuers[_identityIssuer];
identityIssuer.level = _level;
identityIssuer.active = true;
}
function updateIdentityIssuerEidasLevel(address _identityIssuer, Eidas.EidasLevel _level) public alLeastLow(_level) onlyIdentityIssuer(_identityIssuer) {
IdentityIssuer storage identityIssuer = issuers[_identityIssuer];
identityIssuer.level = _level;
}
function deleteIdentityIssuer(address _identityIssuer) public onlyIdentityIssuer(_identityIssuer) {
IdentityIssuer storage identityIssuer = issuers[_identityIssuer];
identityIssuer.level = Eidas.EidasLevel.Null;
identityIssuer.active = false;
}
function getEidasLevel(address _identityIssuer) public constant onlyIdentityIssuer(_identityIssuer) returns (Eidas.EidasLevel) {
return issuers[_identityIssuer].level;
}
function isIdentityIssuer(address _identityIssuer) public constant returns (bool) {
return issuers[_identityIssuer].active;
}
}
// File: contracts/libs/Owned.sol
pragma solidity 0.4.23;
contract Owned {
address public owner;
modifier onlyOwner() {
require(isOwner(msg.sender));
_;
}
constructor () public {
owner = msg.sender;
}
function isOwner(address addr) public view returns(bool) {
return addr == owner;
}
function transfer(address newOwner) public onlyOwner {
if (newOwner != address(this)) {
owner = newOwner;
}
}
}
// File: contracts/identityManager/AlastriaProxy.sol
pragma solidity 0.4.23;
contract AlastriaProxy is Owned {
address public owner;
event Forwarded (address indexed destination, uint value, bytes data);
//TODO: upgradeable owner for version in Identity Manager
constructor () public {
owner = msg.sender;
}
function () payable public{
revert();
}
function forward(address destination, uint value, bytes data) public onlyOwner {
require(destination.call.value(value)(data));
emit Forwarded(destination, value, data);
}
}
// File: contracts/identityManager/AlastriaIdentityEntity.sol
pragma solidity 0.4.23;
contract AlastriaIdentityEntity {
using Eidas for Eidas.EidasLevel;
struct IdentityEntity {
string name;
string cif;
string url_logo;
string url_createAID;
string url_AOA;
bool active;
}
mapping(address => IdentityEntity) internal entities;
address[] listEntities;
modifier onlyIdentityEntity(address _identityEntity) {
require (entities[_identityEntity].active == true);
_;
}
modifier notIdentityEntity(address _identityEntity) {
require (!entities[_identityEntity].active);
_;
}
constructor () public {
IdentityEntity storage identityEntity;
identityEntity.active = true;
entities[msg.sender] = identityEntity;
}
function addEntity(address _addressEntity, string _name, string _cif, string _url_logo, string _url_createAID, string _url_AOA, bool _active) public notIdentityEntity(_addressEntity) onlyIdentityEntity(msg.sender) {
IdentityEntity storage identityEntity = entities[_addressEntity];
listEntities.push(_addressEntity);
entities[_addressEntity].name = _name;
entities[_addressEntity].cif = _cif;
entities[_addressEntity].url_logo = _url_logo;
entities[_addressEntity].url_createAID = _url_createAID;
entities[_addressEntity].url_AOA = _url_AOA;
entities[_addressEntity].active = _active;
}
function setNameEntity(address _addressEntity, string _name) public onlyIdentityEntity(_addressEntity) {
entities[_addressEntity].name = _name;
}
function setCifEntity(address _addressEntity, string _cif) public onlyIdentityEntity(_addressEntity) {
entities[_addressEntity].cif = _cif;
}
function setUrlLogo(address _addressEntity, string _url_logo) public onlyIdentityEntity(_addressEntity) {
entities[_addressEntity].url_logo = _url_logo;
}
function setUrlCreateAID(address _addressEntity, string _url_createAID) public onlyIdentityEntity(_addressEntity) {
entities[_addressEntity].url_createAID = _url_createAID;
}
function setUrlAOA(address _addressEntity, string _url_AOA) public onlyIdentityEntity(_addressEntity) {
entities[_addressEntity].url_AOA = _url_AOA;
}
function getEntity(address _addressEntity) public view returns(string _name, string _cif, string _url_logo, string _url_createAID, string _url_AOA, bool _active){
_name = entities[_addressEntity].name;
_cif = entities[_addressEntity].cif;
_url_logo = entities[_addressEntity].url_logo;
_url_createAID = entities[_addressEntity].url_createAID;
_url_AOA = entities[_addressEntity].url_AOA;
_active = entities[_addressEntity].active;
}
function entitiesList() public view returns(address[]){
return listEntities;
}
}
// File: contracts/registry/AlastriaCredentialRegistry.sol
pragma solidity 0.4.23;
contract AlastriaCredentialRegistry {
// SubjectCredential are registered under Hash(Credential) in a (subject, hash) mapping
// IssuerCredentials are registered under Hash (Credentials + SubjectCredentialSignature) in a (issuer, hash) mapping
// A List of Subject credential hashes is gathered in a (subject) mapping
// To Think About: Make a unique Credential struct and just one mapping subjectCredentialRegistry instead one for subjects and one for issuers
// To Do: Return credential URI. Should only be available to Subject. Mainly as a backup or main index when there are more than one device.
// Could be done from credential mapping in another get function only for subject
// or in getSubjectCredentialList (changing URI from one mapping to the other)
// To Do: make AlastriaCredentialRegistry similar to AlastriaClaimRegistry.
// Variables
int public version;
address public previousPublishedVersion;
// SubjectCredential: Initially Valid: Only DeletedBySubject
// IssuerCredentials: Initially Valid: Only AskIssuer or Revoked, no backwards transitions.
enum Status {Valid, AskIssuer, Revoked, DeletedBySubject}
Status constant STATUS_FIRST = Status.Valid;
Status constant STATUS_LAST = Status.DeletedBySubject;
struct SubjectCredential {
bool exists;
Status status;
string URI;
}
// Mapping subject, hash (JSON credential)
mapping(address => mapping(bytes32 => SubjectCredential)) public subjectCredentialRegistry;
mapping(address => bytes32[]) public subjectCredentialList;
struct IssuerCredential {
bool exists;
Status status;
}
// Mapping issuer, hash (JSON credential + CredentialSignature)
mapping(address => mapping(bytes32 => IssuerCredential)) private issuerCredentialRegistry;
mapping(address => bytes32[]) public issuerCredentialList;
// Events. Just for changes, not for initial set
event SubjectCredentialDeleted (bytes32 subjectCredentialHash);
event IssuerCredentialRevoked (bytes32 issuerCredentialHash, Status status);
//Modifiers
modifier validAddress(address addr) {//protects against some weird attacks
require(addr != address(0));
_;
}
modifier validStatus (Status status) { // solidity currently check on use not at function call
require (status >= STATUS_FIRST && status <= STATUS_LAST);
_;
}
// Functions
constructor (address _previousPublishedVersion) public {
version = 3;
previousPublishedVersion = _previousPublishedVersion;
}
function addSubjectCredential(bytes32 subjectCredentialHash, string URI) public {
require(!subjectCredentialRegistry[msg.sender][subjectCredentialHash].exists);
subjectCredentialRegistry[msg.sender][subjectCredentialHash] = SubjectCredential(true, Status.Valid, URI);
subjectCredentialList[msg.sender].push(subjectCredentialHash);
}
function addIssuerCredential(bytes32 issuerCredentialHash) public {
require(!issuerCredentialRegistry[msg.sender][issuerCredentialHash].exists);
issuerCredentialRegistry[msg.sender][issuerCredentialHash] = IssuerCredential(true, Status.Valid);
issuerCredentialList[msg.sender].push(issuerCredentialHash);
}
function deleteSubjectCredential(bytes32 subjectCredentialHash) public {
SubjectCredential storage value = subjectCredentialRegistry[msg.sender][subjectCredentialHash];
// only existent
if (value.exists && value.status != Status.DeletedBySubject) {
value.status = Status.DeletedBySubject;
emit SubjectCredentialDeleted(subjectCredentialHash);
}
}
// If the credential does not exists the return is a void credential
// If we want a log, should we add an event?
function getSubjectCredentialStatus(address subject, bytes32 subjectCredentialHash) view public validAddress(subject) returns (bool exists, Status status) {
SubjectCredential storage value = subjectCredentialRegistry[subject][subjectCredentialHash];
return (value.exists, value.status);
}
function getSubjectCredentialList(address subject) public view returns (uint, bytes32[]) {
return (subjectCredentialList[subject].length, subjectCredentialList[subject]);
}
function updateCredentialStatus(bytes32 issuerCredentialHash, Status status) validStatus (status) public {
IssuerCredential storage value = issuerCredentialRegistry[msg.sender][issuerCredentialHash];
// No backward transition, only AskIssuer or Revoked
if (status > value.status) {
if (status == Status.AskIssuer || status == Status.Revoked) {
value.exists = true;
value.status = status;
emit IssuerCredentialRevoked(issuerCredentialHash, status);
}
}
}
// If the credential does not exists the return is a void credential
// If we want a log, should we add an event?
function getIssuerCredentialStatus(address issuer, bytes32 issuerCredentialHash) view public validAddress(issuer) returns (bool exists, Status status) {
IssuerCredential storage value = issuerCredentialRegistry[issuer][issuerCredentialHash];
return (value.exists, value.status);
}
// Utility function
// Defining three status functions avoid linking the subject to the issuer or the corresponding hashes
function getCredentialStatus(Status subjectStatus, Status issuerStatus) pure public validStatus(subjectStatus) validStatus(issuerStatus) returns (Status){
if (subjectStatus >= issuerStatus) {
return subjectStatus;
} else {
return issuerStatus;
}
}
}
// File: contracts/registry/AlastriaPresentationRegistry.sol
pragma solidity 0.4.23;
contract AlastriaPresentationRegistry {
// Subject Presentation actions are registered under subjectPresentationHash = hash(Presentation)
// in a (subject, subjectPresentationHash) mapping
// Receiver (ussually a Service Provider) Presentation Actions are registered
// under receiverPresentationHash = hash(Presentations + PresentationSignature) in a (receiver, receiverPresentationHash) mapping
// A List of Subject Presentation Hashes is gathered in a (subject) mapping
// To Review: Subject Presentations could be iterated instead of returned as an array
// Variables
int public version;
address public previousPublishedVersion;
// Status definition, should be moved to a Library.
enum Status {Valid, Received, AskDeletion, DeletionConfirmation}
Status constant STATUS_FIRST = Status.Valid;
Status constant STATUS_LAST = Status.DeletionConfirmation;
int constant STATUS_SIZE = 4;
bool[STATUS_SIZE] subjectAllowed = [
true,
false,
true,
false
];
bool[STATUS_SIZE] receiverAllowed = [
false,
true,
false,
true
];
bool backTransitionsAllowed = false;
// Presentation: Initially set to Valid
// Updates as allowed in *allow arrays
struct SubjectPresentation {
bool exists;
Status status;
string URI;
}
// Mapping subject, subjectPresentationHash (Complete JSON Presentation)
mapping(address => mapping(bytes32 => SubjectPresentation)) public subjectPresentationRegistry;
mapping(address => bytes32[]) public subjectPresentationListRegistry;
struct ReceiverPresentation {
bool exists;
Status status;
}
// Mapping receiver, receiverPresentationHash (Complete JSON Presentation + PresentationSignature)
mapping(address => mapping(bytes32 => ReceiverPresentation)) private receiverPresentationRegistry;
// Events. Just for changes, not for initial set
event PresentationUpdated (bytes32 hash, Status status);
//Modifiers
modifier validAddress(address addr) {//protects against some weird attacks
require(addr != address(0));
_;
}
modifier validStatus (Status status) { // solidity currently check on use not at function call
require (status >= STATUS_FIRST && status <= STATUS_LAST);
_;
}
// Functions
constructor (address _previousPublishedVersion) public {
version = 3;
previousPublishedVersion = _previousPublishedVersion;
}
//
//Subject functions
function addSubjectPresentation(bytes32 subjectPresentationHash, string URI) public {
require(!subjectPresentationRegistry[msg.sender][subjectPresentationHash].exists);
subjectPresentationRegistry[msg.sender][subjectPresentationHash] = SubjectPresentation(true, Status.Valid, URI);
subjectPresentationListRegistry[msg.sender].push(subjectPresentationHash);
}
function updateSubjectPresentation(bytes32 subjectPresentationHash, Status status) public validStatus(status) {
SubjectPresentation storage value = subjectPresentationRegistry[msg.sender][subjectPresentationHash];
// Check existence and backtransitions, should be requires?
if (!value.exists) {
return;
}
if (!backTransitionsAllowed && status <= value.status) {
return;
}
if (subjectAllowed[uint(status)]) {
value.status = status;
emit PresentationUpdated(subjectPresentationHash, status);
}
}
// If the Presentation does not exists the return is a void Presentation
// If we want a log, should we add an event?
function getSubjectPresentationStatus(address subject, bytes32 subjectPresentationHash) view public validAddress(subject) returns (bool exists, Status status) {
SubjectPresentation storage value = subjectPresentationRegistry[subject][subjectPresentationHash];
return (value.exists, value.status);
}
function getSubjectPresentationList(address subject) public view returns (uint, bytes32[]) {
return (subjectPresentationListRegistry[subject].length, subjectPresentationListRegistry[subject]);
}
//
//Receiver functions
function updateReceiverPresentation(bytes32 receiverPresentationHash, Status status) public validStatus(status) {
ReceiverPresentation storage value = receiverPresentationRegistry[msg.sender][receiverPresentationHash];
// No previous existence required. Check backward transition
if (!backTransitionsAllowed && status <= value.status) {
return;
}
if (receiverAllowed[uint(status)]) {
value.exists = true;
value.status = status;
emit PresentationUpdated(receiverPresentationHash, status);
}
}
// If the Presentation does not exists the return is a void Presentation
// If we want a log, should we add an event?
function getReceiverPresentationStatus(address receiver, bytes32 receiverPresentationHash) view public validAddress(receiver) returns (bool exists, Status status) {
ReceiverPresentation storage value = receiverPresentationRegistry[receiver][receiverPresentationHash];
return (value.exists, value.status);
}
// Utility function
// Defining three status functions avoids linking the Subject to the Receiver or the corresponding hashes
function getPresentationStatus(Status subjectStatus, Status receiverStatus) pure public validStatus(subjectStatus) validStatus(receiverStatus) returns (Status){
if (subjectStatus >= receiverStatus) {
return subjectStatus;
} else {
return receiverStatus;
}
}
}
// File: contracts/registry/AlastriaPublicKeyRegistry.sol
pragma solidity 0.4.23;
contract AlastriaPublicKeyRegistry {
// This contracts registers and makes publicly avalaible the AlastriaID Public Keys hash and status, current and past.
//To Do: Should we add RevokedBySubject Status?
//Variables
int public version;
address public previousPublishedVersion;
// Initially Valid: could only be changed to DeletedBySubject for the time being.
enum Status {Valid, DeletedBySubject}
struct PublicKey {
bool exists;
Status status; // Deleted keys shouldnt be used, not even to check previous signatures.
uint startDate;
uint endDate;
}
// Mapping (subject, publickey)
mapping(address => mapping(bytes32 => PublicKey)) private publicKeyRegistry;
// mapping subject => publickey
mapping(address => string[]) public publicKeyList;
//Events, just for revocation and deletion
event PublicKeyDeleted (string publicKey);
event PublicKeyRevoked (string publicKey);
//Modifiers
modifier validAddress(address addr) {//protects against some weird attacks
require(addr != address(0));
_;
}
//Functions
constructor (address _previousPublishedVersion) public {
version = 3;
previousPublishedVersion = _previousPublishedVersion;
}
// Sets new key and revokes previous
function addKey(string memory publicKey) public {
require(!publicKeyRegistry[msg.sender][getKeyHash(publicKey)].exists);
uint changeDate = now;
revokePublicKey(getCurrentPublicKey(msg.sender));
publicKeyRegistry[msg.sender][getKeyHash(publicKey)] = PublicKey(
true,
Status.Valid,
changeDate,
0
);
publicKeyList[msg.sender].push(publicKey);
}
function revokePublicKey(string memory publicKey) public {
PublicKey storage value = publicKeyRegistry[msg.sender][getKeyHash(publicKey)];
// only existent no backtransition
if (value.exists && value.status != Status.DeletedBySubject) {
value.endDate = now;
emit PublicKeyRevoked(publicKey);
}
}
function deletePublicKey(string memory publicKey) public {
PublicKey storage value = publicKeyRegistry[msg.sender][getKeyHash(publicKey)];
// only existent
if (value.exists) {
value.status = Status.DeletedBySubject;
value.endDate = now;
emit PublicKeyDeleted(publicKey);
}
}
function getCurrentPublicKey(address subject) view public validAddress(subject) returns (string) {
if (publicKeyList[subject].length > 0) {
return publicKeyList[subject][publicKeyList[subject].length - 1];
} else {
return "";
}
}
function getPublicKeyStatus(address subject, bytes32 publicKey) view public validAddress(subject)
returns (bool exists, Status status, uint startDate, uint endDate){
PublicKey storage value = publicKeyRegistry[subject][publicKey];
return (value.exists, value.status, value.startDate, value.endDate);
}
function getKeyHash(string memory inputKey) internal pure returns(bytes32){
return keccak256(inputKey);
}
}
// File: contracts/identityManager/AlastriaIdentityManager.sol
pragma solidity 0.4.23;
contract AlastriaIdentityManager is AlastriaIdentityServiceProvider, AlastriaIdentityIssuer, AlastriaIdentityEntity, Owned {
//Variables
uint256 public version;
uint internal timeToLive = 10000;
AlastriaCredentialRegistry public alastriaCredentialRegistry;
AlastriaPresentationRegistry public alastriaPresentationRegistry;
AlastriaPublicKeyRegistry public alastriaPublicKeyRegistry;
mapping(address => address) public identityKeys; //change to alastriaID created check bool
mapping(address => uint) public pendingIDs;
//Events
event PreparedAlastriaID(address indexed signAddress);
event OperationWasNotSupported(string indexed method);
event IdentityCreated(address indexed identity, address indexed creator, address owner);
event IdentityRecovered(address indexed oldAccount, address newAccount, address indexed serviceProvider);
//Modifiers
modifier isPendingAndOnTime(address _signAddress) {
require(pendingIDs[_signAddress] > 0 && pendingIDs[_signAddress] > now);
_;
}
modifier validAddress(address addr) { //protects against some weird attacks
require(addr != address(0));
_;
}
//Constructor
constructor (uint256 _version) public{
//TODO require(_version > getPreviousVersion(_previousVersion));
version = _version;
alastriaCredentialRegistry = new AlastriaCredentialRegistry(address(0));
alastriaPresentationRegistry = new AlastriaPresentationRegistry(address(0));
alastriaPublicKeyRegistry = new AlastriaPublicKeyRegistry(address(0));
}
//Methods
function prepareAlastriaID(address _signAddress) public onlyIdentityIssuer(msg.sender) {
pendingIDs[_signAddress] = now + timeToLive;
emit PreparedAlastriaID(_signAddress);
}
/// @dev Creates a new AlastriaProxy contract for an owner and recovery and allows an initial forward call which would be to set the registry in our case
/// @param addPublicKeyCallData of the call to addKey function in AlastriaPublicKeyRegistry from the new deployed AlastriaProxy contract
function createAlastriaIdentity(bytes addPublicKeyCallData) public validAddress(msg.sender) isPendingAndOnTime(msg.sender) {
AlastriaProxy identity = new AlastriaProxy();
identityKeys[msg.sender] = identity;
pendingIDs[msg.sender] = 0;
identity.forward(address(alastriaPublicKeyRegistry), 0, addPublicKeyCallData);//must be alastria registry call
}
/// @dev This method send a transaction trough the proxy of the sender
function delegateCall(address _destination, uint256 _value, bytes _data) public {
require(identityKeys[msg.sender]!=address(0));
AlastriaProxy identity = AlastriaProxy(address(identityKeys[msg.sender]));
identity.forward(_destination,_value,_data);
}
function recoverAccount(address accountLost, address newAccount) public onlyIdentityIssuer(msg.sender) {
identityKeys[newAccount] = identityKeys[accountLost];
identityKeys[accountLost] = address(0);
IdentityRecovered(accountLost,newAccount,msg.sender);
}
//Internals TODO: warning recommending change visibility to pure
//Checks that address a is the first input in msg.data.
//Has very minimal gas overhead.
function checkMessageData(address a) internal pure returns (bool t) {
if (msg.data.length < 36) return false;
assembly {
let mask := 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
t := eq(a, and(mask, calldataload(4)))
}
}
}
|
If the credential does not exists the return is a void credential If we want a log, should we add an event?
|
function getIssuerCredentialStatus(address issuer, bytes32 issuerCredentialHash) view public validAddress(issuer) returns (bool exists, Status status) {
IssuerCredential storage value = issuerCredentialRegistry[issuer][issuerCredentialHash];
return (value.exists, value.status);
}
| 2,563,325 |
[
1,
2047,
326,
8447,
1552,
486,
1704,
326,
327,
353,
279,
918,
8447,
971,
732,
2545,
279,
613,
16,
1410,
732,
527,
392,
871,
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,
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,
336,
16667,
8605,
1482,
12,
2867,
9715,
16,
1731,
1578,
9715,
8605,
2310,
13,
1476,
1071,
923,
1887,
12,
17567,
13,
1135,
261,
6430,
1704,
16,
2685,
1267,
13,
288,
203,
3639,
23959,
8605,
2502,
460,
273,
9715,
8605,
4243,
63,
17567,
6362,
17567,
8605,
2310,
15533,
203,
3639,
327,
261,
1132,
18,
1808,
16,
460,
18,
2327,
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,
-100,
-100,
-100,
-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/0x1D0977e86c70EAbb5c8fD98DB1B08C6d60caa0C1/sources/contracts/engine/GenArt721CoreV2_ENGINE_FLEX.sol
|
* @notice Updates artist name for project `_projectId` to be `_projectArtistName`./
|
function updateProjectArtistName(
uint256 _projectId,
string memory _projectArtistName
) public onlyUnlocked(_projectId) onlyArtistOrWhitelisted(_projectId) {
projects[_projectId].artist = _projectArtistName;
}
| 9,648,732 |
[
1,
5121,
15469,
508,
364,
1984,
1375,
67,
4406,
548,
68,
358,
506,
1375,
67,
4406,
4411,
376,
461,
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,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
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,
1089,
4109,
4411,
376,
461,
12,
203,
3639,
2254,
5034,
389,
4406,
548,
16,
203,
3639,
533,
3778,
389,
4406,
4411,
376,
461,
203,
565,
262,
1071,
1338,
7087,
329,
24899,
4406,
548,
13,
1338,
4411,
376,
1162,
18927,
329,
24899,
4406,
548,
13,
288,
203,
3639,
10137,
63,
67,
4406,
548,
8009,
25737,
273,
389,
4406,
4411,
376,
461,
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
] |
./partial_match/1/0x373ae78a14577682591E088F2E78EF1417612c68/sources/contracts/oracle/BaseKP3ROracle.sol
|
overflow is desired
|
uint32 timeElapsed = currTime - lastTime;
| 4,169,165 |
[
1,
11512,
353,
6049,
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,
0
] |
[
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,
0
] |
[
1,
1377,
2254,
1578,
813,
28827,
273,
4306,
950,
300,
31323,
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,
-100
] |
pragma solidity ^0.8.10;
import "./ERC721.sol";
import "./Ownable.sol";
import "./Strings.sol";
/// @notice Thrown when completing the transaction results in overallocation of Pixelmon.
error MintedOut();
/// @notice Thrown when the dutch auction phase has not yet started, or has already ended.
error AuctionNotStarted();
/// @notice Thrown when the user has already minted two Pixelmon in the dutch auction.
error MintingTooMany();
/// @notice Thrown when the value of the transaction is not enough for the current dutch auction or mintlist price.
error ValueTooLow();
/// @notice Thrown when the user is not on the mintlist.
error NotMintlisted();
/// @notice Thrown when the caller is not the EvolutionSerum contract, and is trying to evolve a Pixelmon.
error UnauthorizedEvolution();
/// @notice Thrown when an invalid evolution is given by the EvolutionSerum contract.
error UnknownEvolution();
// ______ __ __ __ ______ __ __ __ ______ __ __
// /\ == \ /\ \ /\_\_\_\ /\ ___\ /\ \ /\ "-./ \ /\ __ \ /\ "-.\ \
// \ \ _-/ \ \ \ \/_/\_\/_ \ \ __\ \ \ \____ \ \ \-./\ \ \ \ \/\ \ \ \ \-. \
// \ \_\ \ \_\ /\_\/\_\ \ \_____\ \ \_____\ \ \_\ \ \_\ \ \_____\ \ \_\\"\_\
// \/_/ \/_/ \/_/\/_/ \/_____/ \/_____/ \/_/ \/_/ \/_____/ \/_/ \/_/
//
/// @title Generation 1 Pixelmon NFTs
/// @author delta devs (https://www.twitter.com/deltadevelopers)
contract Pixelmon is ERC721, Ownable {
using Strings for uint256;
/*///////////////////////////////////////////////////////////////
CONSTANTS
//////////////////////////////////////////////////////////////*/
/// @dev Determines the order of the species for each tokenId, mechanism for choosing starting index explained post mint, explanation hash: acb427e920bde46de95103f14b8e57798a603abcf87ff9d4163e5f61c6a56881.
uint constant public provenanceHash = 0x9912e067bd3802c3b007ce40b6c125160d2ccb5352d199e20c092fdc17af8057;
/// @dev Sole receiver of collected contract funds, and receiver of 330 Pixelmon in the constructor.
address constant gnosisSafeAddress = 0xF6BD9Fc094F7aB74a846E5d82a822540EE6c6971;
/// @dev 7750, plus 330 for the Pixelmon Gnosis Safe
uint constant auctionSupply = 7750 + 330;
/// @dev The offsets are the tokenIds that the corresponding evolution stage will begin minting at.
uint constant secondEvolutionOffset = 10005;
uint constant thirdEvolutionOffset = secondEvolutionOffset + 4013;
uint constant fourthEvolutionOffset = thirdEvolutionOffset + 1206;
/*///////////////////////////////////////////////////////////////
EVOLUTIONARY STORAGE
//////////////////////////////////////////////////////////////*/
/// @dev The next tokenID to be minted for each of the evolution stages
uint secondEvolutionSupply = 0;
uint thirdEvolutionSupply = 0;
uint fourthEvolutionSupply = 0;
/// @notice The address of the contract permitted to mint evolved Pixelmon.
address public serumContract;
/// @notice Returns true if the user is on the mintlist, if they have not already minted.
mapping(address => bool) public mintlisted;
/*///////////////////////////////////////////////////////////////
AUCTION STORAGE
//////////////////////////////////////////////////////////////*/
/// @notice Starting price of the auction.
uint256 constant public auctionStartPrice = 3 ether;
/// @notice Unix Timestamp of the start of the auction.
/// @dev Monday, February 7th 2022, 13:00:00 converted to 1644256800 (GMT -5)
uint256 constant public auctionStartTime = 1644256800;
/// @notice Current mintlist price, which will be updated after the end of the auction phase.
/// @dev We started with signatures, then merkle tree, but landed on mapping to reduce USER gas fees.
uint256 public mintlistPrice = 0.75 ether;
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public baseURI;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/// @notice Deploys the contract, minting 330 Pixelmon to the Gnosis Safe and setting the initial metadata URI.
constructor(string memory _baseURI) ERC721("Pixelmon", "PXLMN") {
baseURI = _baseURI;
unchecked {
balanceOf[gnosisSafeAddress] += 330;
totalSupply += 330;
for (uint256 i = 0; i < 330; i++) {
ownerOf[i] = gnosisSafeAddress;
emit Transfer(address(0), gnosisSafeAddress, i);
}
}
}
/*///////////////////////////////////////////////////////////////
METADATA LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Allows the contract deployer to set the metadata URI.
/// @param _baseURI The new metadata URI.
function setBaseURI(string memory _baseURI) public onlyOwner {
baseURI = _baseURI;
}
function tokenURI(uint256 id) public view override returns (string memory) {
return string(abi.encodePacked(baseURI, id.toString()));
}
/*///////////////////////////////////////////////////////////////
DUTCH AUCTION LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Calculates the auction price with the accumulated rate deduction since the auction's begin
/// @return The auction price at the current time, or 0 if the deductions are greater than the auction's start price.
function validCalculatedTokenPrice() private view returns (uint) {
uint priceReduction = ((block.timestamp - auctionStartTime) / 10 minutes) * 0.1 ether;
return auctionStartPrice >= priceReduction ? (auctionStartPrice - priceReduction) : 0;
}
/// @notice Calculates the current dutch auction price, given accumulated rate deductions and a minimum price.
/// @return The current dutch auction price
function getCurrentTokenPrice() public view returns (uint256) {
return max(validCalculatedTokenPrice(), 0.2 ether);
}
/// @notice Purchases a Pixelmon NFT in the dutch auction
/// @param mintingTwo True if the user is minting two Pixelmon, otherwise false.
/// @dev balanceOf is fine, team is aware and accepts that transferring out and repurchasing can be done, even by contracts.
function auction(bool mintingTwo) public payable {
if(block.timestamp < auctionStartTime || block.timestamp > auctionStartTime + 1 days) revert AuctionNotStarted();
uint count = mintingTwo ? 2 : 1;
uint price = getCurrentTokenPrice();
if(totalSupply + count > auctionSupply) revert MintedOut();
if(balanceOf[msg.sender] + count > 2) revert MintingTooMany();
if(msg.value < price * count) revert ValueTooLow();
mintingTwo ? _mintTwo(msg.sender) : _mint(msg.sender, totalSupply);
}
/// @notice Mints two Pixelmons to an address
/// @param to Receiver of the two newly minted NFTs
/// @dev errors taken from super._mint
function _mintTwo(address to) internal {
require(to != address(0), "INVALID_RECIPIENT");
require(ownerOf[totalSupply] == address(0), "ALREADY_MINTED");
uint currentId = totalSupply;
/// @dev unchecked because no arithmetic can overflow
unchecked {
totalSupply += 2;
balanceOf[to] += 2;
ownerOf[currentId] = to;
ownerOf[currentId + 1] = to;
emit Transfer(address(0), to, currentId);
emit Transfer(address(0), to, currentId + 1);
}
}
/*///////////////////////////////////////////////////////////////
MINTLIST MINT LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Allows the contract deployer to set the price of the mintlist. To be called before uploading the mintlist.
/// @param price The price in wei of a Pixelmon NFT to be purchased from the mintlist supply.
function setMintlistPrice(uint256 price) public onlyOwner {
mintlistPrice = price;
}
/// @notice Allows the contract deployer to add a single address to the mintlist.
/// @param user Address to be added to the mintlist.
function mintlistUser(address user) public onlyOwner {
mintlisted[user] = true;
}
/// @notice Allows the contract deployer to add a list of addresses to the mintlist.
/// @param users Addresses to be added to the mintlist.
function mintlistUsers(address[] calldata users) public onlyOwner {
for (uint256 i = 0; i < users.length; i++) {
mintlisted[users[i]] = true;
}
}
/// @notice Purchases a Pixelmon NFT from the mintlist supply
/// @dev We do not check if auction is over because the mintlist will be uploaded after the auction.
function mintlistMint() public payable {
if(totalSupply >= secondEvolutionOffset) revert MintedOut();
if(!mintlisted[msg.sender]) revert NotMintlisted();
if(msg.value < mintlistPrice) revert ValueTooLow();
mintlisted[msg.sender] = false;
_mint(msg.sender, totalSupply);
}
/// @notice Withdraws collected funds to the Gnosis Safe address
function withdraw() public onlyOwner {
(bool success, ) = gnosisSafeAddress.call{value: address(this).balance}("");
require(success);
}
/*///////////////////////////////////////////////////////////////
ROLL OVER LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Allows the contract deployer to airdrop Pixelmon to a list of addresses, in case the auction doesn't mint out
/// @param addresses Array of addresses to receive Pixelmon
function rollOverPixelmons(address[] calldata addresses) public onlyOwner {
if(totalSupply + addresses.length > secondEvolutionOffset) revert MintedOut();
for (uint256 i = 0; i < addresses.length; i++) {
_mint(msg.sender, totalSupply);
}
}
/*///////////////////////////////////////////////////////////////
EVOLUTIONARY LOGIC
//////////////////////////////////////////////////////////////*/
/// @notice Sets the address of the contract permitted to call mintEvolvedPixelmon
/// @param _serumContract The address of the EvolutionSerum contract
function setSerumContract(address _serumContract) public onlyOwner {
serumContract = _serumContract;
}
/// @notice Mints an evolved Pixelmon
/// @param receiver Receiver of the evolved Pixelmon
/// @param evolutionStage The evolution (2-4) that the Pixelmon is undergoing
function mintEvolvedPixelmon(address receiver, uint evolutionStage) public payable {
if(msg.sender != serumContract) revert UnauthorizedEvolution();
if (evolutionStage == 2) {
if(secondEvolutionSupply >= 4013) revert MintedOut();
_mint(receiver, secondEvolutionOffset + secondEvolutionSupply);
unchecked {
secondEvolutionSupply++;
}
} else if (evolutionStage == 3) {
if(thirdEvolutionSupply >= 1206) revert MintedOut();
_mint(receiver, thirdEvolutionOffset + thirdEvolutionSupply);
unchecked {
thirdEvolutionSupply++;
}
} else if (evolutionStage == 4) {
if(fourthEvolutionSupply >= 33) revert MintedOut();
_mint(receiver, fourthEvolutionOffset + fourthEvolutionSupply);
unchecked {
fourthEvolutionSupply++;
}
} else {
revert UnknownEvolution();
}
}
/*///////////////////////////////////////////////////////////////
UTILS
//////////////////////////////////////////////////////////////*/
/// @notice Returns the greater of two numbers.
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
}
|
@notice Purchases a Pixelmon NFT in the dutch auction @param mintingTwo True if the user is minting two Pixelmon, otherwise false. @dev balanceOf is fine, team is aware and accepts that transferring out and repurchasing can be done, even by contracts.
|
function auction(bool mintingTwo) public payable {
if(block.timestamp < auctionStartTime || block.timestamp > auctionStartTime + 1 days) revert AuctionNotStarted();
uint count = mintingTwo ? 2 : 1;
uint price = getCurrentTokenPrice();
if(totalSupply + count > auctionSupply) revert MintedOut();
if(balanceOf[msg.sender] + count > 2) revert MintingTooMany();
if(msg.value < price * count) revert ValueTooLow();
mintingTwo ? _mintTwo(msg.sender) : _mint(msg.sender, totalSupply);
}
| 12,826,992 |
[
1,
10262,
343,
3304,
279,
26070,
2586,
423,
4464,
316,
326,
302,
322,
343,
279,
4062,
225,
312,
474,
310,
11710,
1053,
309,
326,
729,
353,
312,
474,
310,
2795,
26070,
2586,
16,
3541,
629,
18,
225,
11013,
951,
353,
11079,
16,
5927,
353,
18999,
471,
8104,
716,
906,
74,
20245,
596,
471,
2071,
295,
343,
11730,
848,
506,
2731,
16,
5456,
635,
20092,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
279,
4062,
12,
6430,
312,
474,
310,
11710,
13,
1071,
8843,
429,
288,
203,
3639,
309,
12,
2629,
18,
5508,
411,
279,
4062,
13649,
747,
1203,
18,
5508,
405,
279,
4062,
13649,
397,
404,
4681,
13,
15226,
432,
4062,
1248,
9217,
5621,
203,
203,
3639,
2254,
1056,
273,
312,
474,
310,
11710,
692,
576,
294,
404,
31,
203,
3639,
2254,
6205,
273,
5175,
1345,
5147,
5621,
203,
203,
3639,
309,
12,
4963,
3088,
1283,
397,
1056,
405,
279,
4062,
3088,
1283,
13,
15226,
490,
474,
329,
1182,
5621,
203,
3639,
309,
12,
12296,
951,
63,
3576,
18,
15330,
65,
397,
1056,
405,
576,
13,
15226,
490,
474,
310,
10703,
5594,
5621,
203,
3639,
309,
12,
3576,
18,
1132,
411,
6205,
380,
1056,
13,
15226,
1445,
10703,
10520,
5621,
203,
203,
3639,
312,
474,
310,
11710,
692,
389,
81,
474,
11710,
12,
3576,
18,
15330,
13,
294,
389,
81,
474,
12,
3576,
18,
15330,
16,
2078,
3088,
1283,
1769,
203,
565,
289,
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,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-02-07
*/
// SPDX-License-Identifier: AGPL-3.0-or-later
// File: interfaces/ISinsAuthority.sol
pragma solidity >=0.7.5;
interface ISinsAuthority {
/* ========== EVENTS ========== */
event GovernorPushed(address indexed from, address indexed to, bool _effectiveImmediately);
event GuardianPushed(address indexed from, address indexed to, bool _effectiveImmediately);
event PolicyPushed(address indexed from, address indexed to, bool _effectiveImmediately);
event VaultPushed(address indexed from, address indexed to, bool _effectiveImmediately);
event GovernorPulled(address indexed from, address indexed to);
event GuardianPulled(address indexed from, address indexed to);
event PolicyPulled(address indexed from, address indexed to);
event VaultPulled(address indexed from, address indexed to);
/* ========== VIEW ========== */
function governor() external view returns (address);
function guardian() external view returns (address);
function policy() external view returns (address);
function vault() external view returns (address);
}
// File: types/SinsAccessControlled.sol
pragma solidity >=0.7.5;
abstract contract SinsAccessControlled {
/* ========== EVENTS ========== */
event AuthorityUpdated(ISinsAuthority indexed authority);
string UNAUTHORIZED = "UNAUTHORIZED"; // save gas
/* ========== STATE VARIABLES ========== */
ISinsAuthority public authority;
/* ========== Constructor ========== */
constructor(ISinsAuthority _authority) {
authority = _authority;
emit AuthorityUpdated(_authority);
}
/* ========== MODIFIERS ========== */
modifier onlyGovernor() {
require(msg.sender == authority.governor(), UNAUTHORIZED);
_;
}
modifier onlyGuardian() {
require(msg.sender == authority.guardian(), UNAUTHORIZED);
_;
}
modifier onlyPolicy() {
require(msg.sender == authority.policy(), UNAUTHORIZED);
_;
}
modifier onlyVault() {
require(msg.sender == authority.vault(), UNAUTHORIZED);
_;
}
/* ========== GOV ONLY ========== */
function setAuthority(ISinsAuthority _newAuthority) external onlyGovernor {
authority = _newAuthority;
emit AuthorityUpdated(_newAuthority);
}
}
pragma solidity >=0.7.5;
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
uint256 chainID;
assembly {
chainID := chainid()
}
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = chainID;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
uint256 chainID;
assembly {
chainID := chainid()
}
if (chainID == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 nameHash,
bytes32 versionHash
) private view returns (bytes32) {
uint256 chainID;
assembly {
chainID := chainid()
}
return keccak256(abi.encode(typeHash, nameHash, versionHash, chainID, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// File: interfaces/IERC20Permit.sol
pragma solidity >=0.7.5;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as th xe allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// File: interfaces/IERC20.sol
pragma solidity >=0.7.5;
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: interfaces/ISIN.sol
pragma solidity >=0.7.5;
interface ISIN is IERC20 {
function mint(address account_, uint256 amount_) external;
function burn(uint256 amount) external;
function burnFrom(address account_, uint256 amount_) external;
}
pragma solidity >=0.7.5;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// File: libraries/SafeMath.sol
pragma solidity >=0.7.5;
// TODO(zx): Replace all instances of SafeMath with OZ implementation
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by 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;
}
// Only used in the BondingCalculator.sol
function sqrrt(uint256 a) internal pure returns (uint c) {
if (a > 3) {
c = a;
uint b = add( div( a, 2), 1 );
while (b < c) {
c = b;
b = div( add( div( a, b ), b), 2 );
}
} else if (a != 0) {
c = 1;
}
}
}
// File: libraries/Counters.sol
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;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
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 ITaxDistributor {
function distribute(address urv2, address dai, address marketingWallet, uint256 daiForBuyback, address buybackWallet, uint256 liquidityTokens, uint256 daiForLiquidity, address liquidityTo) external;
}
pragma solidity >=0.7.5;
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// File: types/ERC20.sol
pragma solidity >=0.7.5;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
abstract contract ERC20 is Context, IERC20{
using SafeMath for uint256;
// TODO comment actual hash value.
bytes32 constant private ERC20TOKEN_ERC1820_INTERFACE_ID = keccak256( "ERC20Token" );
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowances;
uint256 internal _totalSupply;
string internal _name;
string internal _symbol;
uint8 internal immutable _decimals;
constructor (string memory name_, string memory symbol_, uint8 decimals_) {
_name = name_;
_symbol = symbol_;
_decimals = decimals_;
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view virtual returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(msg.sender, spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
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);
}
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);
}
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);
}
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);
}
function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal virtual { }
}
// File: types/ERC20Permit.sol
pragma solidity >=0.7.5;
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
// File: SinsERC20.sol
pragma solidity >=0.7.5;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
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;
}
contract SinsERC20Token is ERC20Permit, ISIN, SinsAccessControlled {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
address public constant deadAddress = address(0xdead);
address public marketingWallet;
address public buybackWallet;
bool public tradingActive = false;
bool public swapEnabled = false;
bool private swapping;
uint256 public buyTotalFees;
uint256 public buyMarketingFee;
uint256 public buyLiquidityFee;
uint256 public buyBurnFee;
uint256 public buyBuybackFee;
uint256 public sellTotalFees;
uint256 public sellMarketingFee;
uint256 public sellLiquidityFee;
uint256 public sellBurnFee;
uint256 public sellBuybackFee;
address public taxDistributor;
uint256 public tokensForMarketing;
uint256 public tokensForLiquidity;
uint256 public tokensForBurn;
uint256 public tokensForBuyback;
bool public limitsInEffect = true;
// Anti-bot and anti-whale mappings and variables
mapping(address => uint256) private _holderLastTransferTimestamp; // to hold last Transfers temporarily during launch
bool public transferDelayEnabled = true;
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) public _isExcludedMaxTransactionAmount;
uint256 public maxTransactionAmount;
uint256 public maxWallet;
uint256 public initialSupply;
address public dai;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet);
event buybackWalletUpdated(address indexed newWallet, address indexed oldWallet);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiquidity
);
constructor(address _authority, address _marketingWallet, address _buybackWallet, address _dai)
ERC20("Sins", "SIN", 9)
ERC20Permit("Sins")
SinsAccessControlled(ISinsAuthority(_authority)) {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
uniswapV2Router = _uniswapV2Router;
dai = _dai;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _dai);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
initialSupply = 50000*1e9;
maxTransactionAmount = initialSupply * 5 / 1000; // 0.5% maxTransactionAmountTxn
maxWallet = initialSupply * 10 / 1000; // 1% maxWallet
_mint(authority.governor(), initialSupply);
uint256 _buyMarketingFee = 2;
uint256 _buyLiquidityFee = 3;
uint256 _buyBurnFee = 1;
uint256 _buyBuybackFee = 0;
uint256 _sellMarketingFee = 9;
uint256 _sellLiquidityFee = 3;
uint256 _sellBurnFee = 1;
uint256 _sellBuybackFee = 2;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyBurnFee = _buyBurnFee;
buyBuybackFee = _buyBuybackFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBurnFee + buyBuybackFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellBurnFee = _sellBurnFee;
sellBuybackFee = _sellBuybackFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBurnFee + sellBuybackFee;
marketingWallet = address(_marketingWallet);
buybackWallet = address(_buybackWallet);
// exclude from paying fees or having max transaction amount
excludeFromFees(authority.governor(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
}
receive() external payable {
}
// remove limits after token is stable
function removeLimits() external onlyGovernor returns (bool){
limitsInEffect = false;
sellMarketingFee = 4;
sellLiquidityFee = 3;
sellBurnFee = 1;
sellBuybackFee = 0;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBurnFee + sellBuybackFee;
return true;
}
function updateTaxDistributor(address _taxDistributor) external onlyGovernor {
taxDistributor = _taxDistributor;
}
function updateMaxTxnAmount(uint256 newNum) external onlyGovernor {
require(newNum >= (totalSupply() * 1 / 1000)/1e9, "Cannot set maxTransactionAmount lower than 0.1%");
maxTransactionAmount = newNum * (10**9);
}
function updateMaxWalletAmount(uint256 newNum) external onlyGovernor {
require(newNum >= (totalSupply() * 5 / 1000)/1e9, "Cannot set maxWallet lower than 0.5%");
maxWallet = newNum * (10**9);
}
function excludeFromMaxTransaction(address updAds, bool isEx) public onlyGovernor {
_isExcludedMaxTransactionAmount[updAds] = isEx;
}
// disable Transfer delay - cannot be reenabled
function disableTransferDelay() external onlyGovernor returns (bool){
transferDelayEnabled = false;
return true;
}
// once enabled, can never be turned off
function enableTrading() external onlyGovernor {
tradingActive = true;
swapEnabled = true;
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyGovernor {
require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function excludeFromFees(address account, bool excluded) public onlyGovernor {
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
// only use to disable contract sales if absolutely necessary (emergency use only)
function updateSwapEnabled(bool enabled) external onlyGovernor{
swapEnabled = enabled;
}
function updateBuyFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _burnFee, uint256 _buybackFee) external onlyGovernor {
buyMarketingFee = _marketingFee;
buyLiquidityFee = _liquidityFee;
buyBurnFee = _burnFee;
buyBuybackFee = _buybackFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyBurnFee + buyBuybackFee;
require(buyTotalFees <= 15, "Must keep fees at 15% or less");
}
function updateSellFees(uint256 _marketingFee, uint256 _liquidityFee, uint256 _burnFee, uint256 _buybackFee) external onlyGovernor {
sellMarketingFee = _marketingFee;
sellLiquidityFee = _liquidityFee;
sellBurnFee = _burnFee;
sellBuybackFee = _buybackFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellBurnFee + sellBuybackFee;
require(sellTotalFees <= 15, "Must keep fees at 15% or less");
}
function updateMarketingWallet(address newMarketingWallet) external onlyGovernor {
emit marketingWalletUpdated(newMarketingWallet, marketingWallet);
marketingWallet = newMarketingWallet;
}
function updateBuybackWallet(address newBuybackWallet) external onlyGovernor {
emit buybackWalletUpdated(newBuybackWallet, buybackWallet);
buybackWallet = newBuybackWallet;
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function mint(address account_, uint256 amount_) external override onlyVault {
_mint(account_, amount_);
}
function burn(uint256 amount) external override {
_burn(msg.sender, amount);
}
function burnFrom(address account_, uint256 amount_) external override {
_burnFrom(account_, amount_);
}
function _burnFrom(address account_, uint256 amount_) internal {
uint256 decreasedAllowance_ = allowance(account_, msg.sender).sub(amount_, "ERC20: burn amount exceeds allowance");
_approve(account_, msg.sender, decreasedAllowance_);
_burn(account_, amount_);
}
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != authority.governor() &&
to != authority.governor() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
// at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.
if (transferDelayEnabled){
if (to != authority.governor() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
//when buy
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
//when sell
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
if(
swapEnabled &&
!swapping &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to] &&
!automatedMarketMakerPairs[from]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
tokensForBurn = 0;
// only take fees on buys/sells, do not take on wallet transfers
if(takeFee){
// on sell
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForBurn = fees * sellBurnFee / sellTotalFees;
tokensForBuyback += fees * sellBuybackFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
// on buy
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForBurn = fees * buyBurnFee / buyTotalFees;
tokensForBuyback += fees * buyBuybackFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees-tokensForBurn > 0){
super._transfer(from, address(this), fees.sub(tokensForBurn));
}
if (tokensForBurn > 0){
super._transfer(from, deadAddress, tokensForBurn);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
function swapTokensForDai(uint256 tokenAmount) public {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = dai;
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
taxDistributor,
block.timestamp
);
}
function swapBack() public {
uint256 contractBalance = balanceOf(address(this));
uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForBuyback;
if(contractBalance == 0 || totalTokensToSwap == 0) {return;}
if(contractBalance > totalSupply() * 5 / 10000 * 20){
contractBalance = totalSupply() * 5 / 10000 * 20;
}
// Halve the amount of liquidity tokens
uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2;
uint256 amountToSwapForDai = contractBalance.sub(liquidityTokens);
uint256 initialDaiBalance = IERC20(dai).balanceOf(taxDistributor);
swapTokensForDai(amountToSwapForDai);
uint256 daiBalance = IERC20(dai).balanceOf(taxDistributor).sub(initialDaiBalance);
uint256 daiForMarketing = daiBalance.mul(tokensForMarketing).div(totalTokensToSwap);
uint256 daiForBuyback = daiBalance.mul(tokensForBuyback).div(totalTokensToSwap);
uint256 daiForLiquidity = daiBalance - daiForMarketing - daiForBuyback;
super._transfer(address(this), taxDistributor, liquidityTokens);
ITaxDistributor(taxDistributor).distribute(address(uniswapV2Router), dai, marketingWallet, daiForBuyback, buybackWallet, liquidityTokens, daiForLiquidity, authority.governor());
tokensForLiquidity = 0;
tokensForMarketing = 0;
tokensForBuyback = 0;
}
}
|
at launch if the transfer delay is enabled, ensure the block timestamps for purchasers is set -- during launch.when buywhen sell if any account belongs to _isExcludedFromFee account then remove the fee only take fees on buys/sells, do not take on wallet transfers on sell on buy
|
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(limitsInEffect){
if (
from != authority.governor() &&
to != authority.governor() &&
to != address(0) &&
to != address(0xdead) &&
!swapping
){
if(!tradingActive){
require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active.");
}
if (transferDelayEnabled){
if (to != authority.governor() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){
require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed.");
_holderLastTransferTimestamp[tx.origin] = block.number;
}
}
if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) {
require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount.");
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) {
require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount.");
}
else if(!_isExcludedMaxTransactionAmount[to]){
require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded");
}
}
}
if(
swapEnabled &&
!swapping &&
!_isExcludedFromFees[from] &&
!_isExcludedFromFees[to] &&
!automatedMarketMakerPairs[from]
) {
swapping = true;
swapBack();
swapping = false;
}
bool takeFee = !swapping;
if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
uint256 fees = 0;
tokensForBurn = 0;
if(takeFee){
if (automatedMarketMakerPairs[to] && sellTotalFees > 0){
fees = amount.mul(sellTotalFees).div(100);
tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees;
tokensForBurn = fees * sellBurnFee / sellTotalFees;
tokensForBuyback += fees * sellBuybackFee / sellTotalFees;
tokensForMarketing += fees * sellMarketingFee / sellTotalFees;
}
else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) {
fees = amount.mul(buyTotalFees).div(100);
tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees;
tokensForBurn = fees * buyBurnFee / buyTotalFees;
tokensForBuyback += fees * buyBuybackFee / buyTotalFees;
tokensForMarketing += fees * buyMarketingFee / buyTotalFees;
}
if(fees-tokensForBurn > 0){
super._transfer(from, address(this), fees.sub(tokensForBurn));
}
if (tokensForBurn > 0){
super._transfer(from, deadAddress, tokensForBurn);
}
amount -= fees;
}
super._transfer(from, to, amount);
}
| 6,817,926 |
[
1,
270,
8037,
309,
326,
7412,
4624,
353,
3696,
16,
3387,
326,
1203,
11267,
364,
5405,
343,
345,
414,
353,
444,
1493,
4982,
8037,
18,
13723,
30143,
13723,
357,
80,
309,
1281,
2236,
11081,
358,
389,
291,
16461,
1265,
14667,
2236,
1508,
1206,
326,
14036,
1338,
4862,
1656,
281,
603,
25666,
1900,
19,
87,
1165,
87,
16,
741,
486,
4862,
603,
9230,
29375,
603,
357,
80,
603,
30143,
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,
389,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
3849,
288,
203,
3639,
2583,
12,
2080,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
869,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
540,
203,
540,
309,
12,
8949,
422,
374,
13,
288,
203,
5411,
2240,
6315,
13866,
12,
2080,
16,
358,
16,
374,
1769,
203,
5411,
327,
31,
203,
3639,
289,
203,
203,
3639,
309,
12,
14270,
382,
12477,
15329,
203,
5411,
309,
261,
203,
7734,
628,
480,
11675,
18,
75,
1643,
29561,
1435,
597,
203,
7734,
358,
480,
11675,
18,
75,
1643,
29561,
1435,
597,
203,
7734,
358,
480,
1758,
12,
20,
13,
597,
203,
7734,
358,
480,
1758,
12,
20,
92,
22097,
13,
597,
203,
7734,
401,
22270,
1382,
203,
5411,
262,
95,
203,
7734,
309,
12,
5,
313,
14968,
3896,
15329,
203,
10792,
2583,
24899,
291,
16461,
1265,
2954,
281,
63,
2080,
65,
747,
389,
291,
16461,
1265,
2954,
281,
63,
869,
6487,
315,
1609,
7459,
353,
486,
2695,
1199,
1769,
203,
7734,
289,
203,
203,
7734,
309,
261,
13866,
6763,
1526,
15329,
203,
10792,
309,
261,
869,
480,
11675,
18,
75,
1643,
29561,
1435,
597,
358,
480,
1758,
12,
318,
291,
91,
438,
58,
22,
8259,
13,
597,
358,
480,
1758,
12,
318,
291,
91,
438,
58,
22,
4154,
3719,
95,
203,
13491,
2
] |
./full_match/1/0x146657fd93AA4869934383c9c899891078E6b94C/sources/lib/lssvm/src/LSSVMPairETH.sol
|
@inheritdoc LSSVMPair
|
function withdrawERC20(ERC20 a, uint256 amount)
external
override
onlyOwner
{
a.safeTransfer(msg.sender, amount);
}
for the owner to top up the pair's token reserves.
| 2,983,677 |
[
1,
36,
10093,
511,
1260,
7397,
4154,
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,
598,
9446,
654,
39,
3462,
12,
654,
39,
3462,
279,
16,
2254,
5034,
3844,
13,
203,
3639,
3903,
203,
3639,
3849,
203,
3639,
1338,
5541,
203,
565,
288,
203,
3639,
279,
18,
4626,
5912,
12,
3576,
18,
15330,
16,
3844,
1769,
203,
565,
289,
203,
203,
3639,
364,
326,
3410,
358,
1760,
731,
326,
3082,
1807,
1147,
400,
264,
3324,
18,
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
] |
./partial_match/8453/0x794a166CB034d2ac581DAf3CC3d435abfE1aFD3a/sources/BC.sol
|
* @title ERC20Decimals @dev Implementation of the ERC20Decimals. Extension of {ERC20} that adds decimals storage slot./
|
contract BC is ERC20 {
uint8 immutable private _decimals = 18;
uint256 private _totalSupply = 1000000000* 10 ** 18;
constructor () ERC20('BC', 'BC') {
_mint(_msgSender(), _totalSupply);
}
function decimals() public view virtual override returns (uint8) {
return _decimals;
}
}
| 16,776,410 |
[
1,
654,
39,
3462,
31809,
225,
25379,
434,
326,
4232,
39,
3462,
31809,
18,
10021,
434,
288,
654,
39,
3462,
97,
716,
4831,
15105,
2502,
4694,
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
] |
[
1,
1,
1,
1,
1,
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,
16351,
21225,
353,
4232,
39,
3462,
288,
203,
565,
2254,
28,
11732,
3238,
389,
31734,
273,
6549,
31,
203,
565,
2254,
5034,
3238,
389,
4963,
3088,
1283,
273,
15088,
3784,
14,
1728,
2826,
6549,
31,
203,
203,
203,
565,
3885,
1832,
4232,
39,
3462,
2668,
16283,
2187,
296,
16283,
6134,
288,
203,
3639,
389,
81,
474,
24899,
3576,
12021,
9334,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
565,
445,
15105,
1435,
1071,
1476,
5024,
3849,
1135,
261,
11890,
28,
13,
288,
203,
3639,
327,
389,
31734,
31,
203,
565,
289,
203,
97,
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
] |
pragma solidity ^0.4.20;
import "./lib/ECVerify.sol";
/*
* Interfaces
*/
/// @dev The contract as receiver must implement these functions
contract ReceiverContract {
/// @notice Called to get owner of the Contract
/// @return Address of the owner
function getOwner() public returns (address);
}
/// @title Transfer Channels Contract.
contract TransferChannels {
/*
* Data structures
*/
// Contract semantic version
string public constant version = '1.0.0';
// Number of blocks to wait from an uncooperativeClose initiated by the sender
// in order to give the receiver a chance to respond with a balance proof in case the sender cheats.
// After the challenge period, the sender can settle and delete the channel.
uint32 public constant challengePeriod = 5000;
// We temporarily limit total deposits in a channel to 10000 ATN with 18 decimals.
uint256 public constant channel_deposit_bugbounty_limit = 10 ** 18 * 10000;
mapping (bytes32 => Channel) public channels;
mapping (bytes32 => ClosingRequest) public closing_requests;
mapping (bytes32 => uint256) public withdrawn_balances;
struct Channel {
// uint256 is the maximum uint size needed for deposit based on 2.1 * 10^8 * 10^18 totalSupply.
uint256 deposit;
// Block number at which the channel was opened.
uint32 open_block_number;
}
struct ClosingRequest {
// Balance owed by the sender when closing the channel.
uint256 closing_balance;
// Block number at which the challenge period ends, in case it has been initiated.
uint32 settle_block_number;
}
/*
* Events
*/
event ChannelCreated(
address indexed _sender_address,
address indexed _receiver_address,
uint256 _deposit);
event ChannelToppedUp (
address indexed _sender_address,
address indexed _receiver_address,
uint32 indexed _open_block_number,
uint256 _added_deposit);
event ChannelCloseRequested(
address indexed _sender_address,
address indexed _receiver_address,
uint32 indexed _open_block_number,
uint256 _balance);
event ChannelSettled(
address indexed _sender_address,
address indexed _receiver_address,
uint32 indexed _open_block_number,
uint256 _balance,
uint256 _receiver_remaining_balance);
event ChannelWithdraw(
address indexed _sender_address,
address indexed _receiver_address,
uint32 indexed _open_block_number,
uint256 _withdrawn_balance);
/*
* External functions
*/
/// @notice Create a channel between `msg.sender` and `_receiver_address` and transfer `msg.value` to this contract as deposit in the channel.
/// @param _receiver_address The address of the receiver.
function createChannel(address _receiver_address) external payable {
createChannelPrivate(msg.sender, _receiver_address, msg.value);
}
/// @notice Increase the channel deposit with `msg.value`.
/// @param _receiver_address The address of the receiver.
/// @param _open_block_number The block number at which the channel was created.
function topUp(
address _receiver_address,
uint32 _open_block_number)
payable
external
{
updateInternalBalanceStructs(
msg.sender,
_receiver_address,
_open_block_number,
msg.value
);
}
/// @notice Allows channel receiver to withdraw balance.
/// @param _open_block_number The block number at which the channel was created.
/// @param _balance Partial or total amount of balance owed by the sender to the receiver.
/// Has to be smaller or equal to the channel deposit. Has to match the balance value from `_balance_msg_sig`
/// @param _balance_msg_sig The balance message signed by the sender.
/// @return withdrawed balance
function withdraw(
uint32 _open_block_number,
uint256 _balance,
bytes _balance_msg_sig)
external
returns (uint256)
{
require(_balance > 0);
// Derive sender address from signed balance proof
address sender_address = extractBalanceProofSignature(
msg.sender,
_open_block_number,
_balance,
_balance_msg_sig
);
bytes32 key = getKey(sender_address, msg.sender, _open_block_number);
// Make sure the channel exists
require(channels[key].open_block_number > 0);
// Make sure the channel is not in the challenge period
require(closing_requests[key].settle_block_number == 0);
require(_balance <= channels[key].deposit);
require(withdrawn_balances[key] < _balance);
uint256 remaining_balance = _balance - withdrawn_balances[key];
withdrawn_balances[key] = _balance;
// Send the remaining balance to the receiver
msg.sender.transfer(remaining_balance);
emit ChannelWithdraw(sender_address, msg.sender, channels[key].open_block_number, remaining_balance);
return remaining_balance;
}
/// @notice Called by the sender or receiver with all the needed signatures to close and settle the channel immediately.
/// @param _receiver_address The address of the receiver.
/// @param _open_block_number The block number at which the channel was created.
/// @param _balance The amount of balance owed by the sender to the receiver.
/// @param _balance_msg_sig The balance message signed by the sender.
/// @param _closing_sig The receiver's signed balance message, containing the sender's address.
/// If the receiver is a contract, it should be signed by the constract's owner
function cooperativeClose(
address _receiver_address,
uint32 _open_block_number,
uint256 _balance,
bytes _balance_msg_sig,
bytes _closing_sig)
external
{
// Derive sender address from signed balance proof
address sender = extractBalanceProofSignature(
_receiver_address,
_open_block_number,
_balance,
_balance_msg_sig
);
// Derive receiver address from closing signature
address signer = extractClosingSignature(
sender,
_open_block_number,
_balance,
_closing_sig
);
// If the receiver is a contract, the `_closing_sig` should be signed by it's owner
if (isContract(_receiver_address)) {
require(signer == ReceiverContract(_receiver_address).getOwner());
} else {
require(signer == _receiver_address);
}
// Both signatures have been verified and the channel can be settled immediately.
settleChannel(sender, _receiver_address, _open_block_number, _balance);
}
/// @notice Sender requests the closing of the channel and starts the challenge period.
/// This can only happen once.
/// @param _receiver_address The address of the receiver.
/// @param _open_block_number The block number at which the channel was created.
/// @param _balance The amount of blance owed by the sender to the receiver.
function uncooperativeClose(
address _receiver_address,
uint32 _open_block_number,
uint256 _balance)
external
{
bytes32 key = getKey(msg.sender, _receiver_address, _open_block_number);
require(channels[key].open_block_number > 0);
require(closing_requests[key].settle_block_number == 0);
require(_balance <= channels[key].deposit);
// Mark channel as closed
closing_requests[key].settle_block_number = uint32(block.number) + challengePeriod;
require(closing_requests[key].settle_block_number > block.number);
closing_requests[key].closing_balance = _balance;
emit ChannelCloseRequested(msg.sender, _receiver_address, channels[key].open_block_number, _balance);
}
/// @notice Function called by the sender after the challenge period has ended, in order to
/// settle and delete the channel, in case the receiver has not closed the channel himself.
/// @param _receiver_address The address of the receiver.
/// @param _open_block_number The block number at which the channel was created.
function settle(address _receiver_address, uint32 _open_block_number) external {
bytes32 key = getKey(msg.sender, _receiver_address, _open_block_number);
// Make sure an uncooperativeClose has been initiated
require(closing_requests[key].settle_block_number > 0);
// Make sure the challengePeriod has ended
require(block.number > closing_requests[key].settle_block_number);
settleChannel(msg.sender, _receiver_address, _open_block_number, closing_requests[key].closing_balance
);
}
/// @notice Retrieving information about a channel.
/// @param _sender_address The address of the sender.
/// @param _receiver_address The address of the receiver.
/// @param _open_block_number The block number at which the channel was created.
/// @return Channel information: key, deposit, open_block_number, settle_block_number, closing_balance, withdrawn balance).
function getChannelInfo(
address _sender_address,
address _receiver_address,
uint32 _open_block_number)
external
view
returns (bytes32, uint256, uint32, uint256, uint256)
{
bytes32 key = getKey(_sender_address, _receiver_address, _open_block_number);
require(channels[key].open_block_number > 0);
return (
key,
channels[key].deposit,
// channels[key].open_block_number,
closing_requests[key].settle_block_number,
closing_requests[key].closing_balance,
withdrawn_balances[key]
);
}
/*
* Public functions
*/
/// @notice Returns the sender address extracted from the balance proof.
/// work with eth_signTypedData https://github.com/ethereum/EIPs/pull/712.
/// @param _receiver_address The address of the receiver.
/// @param _open_block_number The block number at which the channel was created.
/// @param _balance The amount of balance.
/// @param _balance_msg_sig The balance message signed by the sender.
/// @return Address of the balance proof signer.
function extractBalanceProofSignature(
address _receiver_address,
uint32 _open_block_number,
uint256 _balance,
bytes _balance_msg_sig)
public
view
returns (address)
{
// The variable names from below will be shown to the sender when signing the balance proof.
// The hashed strings should be kept in sync with this function's parameters (variable names and types).
// ! Note that EIP712 might change how hashing is done, triggering a new contract deployment with updated code.
bytes32 message_hash = keccak256(
keccak256(
'string message_id',
'address receiver',
// 'uint32 block_created',
'uint256 balance',
'address contract'
),
keccak256(
'Sender balance proof signature',
_receiver_address,
// _open_block_number,
_balance,
address(this)
)
);
// Derive address from signature
address signer = ECVerify.ecverify(message_hash, _balance_msg_sig);
return signer;
}
/// @dev Returns the receiver address extracted from the closing signature.
/// Works with eth_signTypedData https://github.com/ethereum/EIPs/pull/712.
/// @param _sender_address The address of the sender.
/// @param _open_block_number The block number at which the channel was created.
/// @param _balance The amount of balance.
/// @param _closing_sig The receiver's signed balance message, containing the sender's address.
/// @return Address of the closing signature signer.
function extractClosingSignature(
address _sender_address,
uint32 _open_block_number,
uint256 _balance,
bytes _closing_sig)
public
view
returns (address)
{
// The variable names from below will be shown to the sender when signing the balance proof.
// The hashed strings should be kept in sync with this function's parameters (variable names and types).
// ! Note that EIP712 might change how hashing is done, triggering a
// new contract deployment with updated code.
bytes32 message_hash = keccak256(
keccak256(
'string message_id',
'address sender',
// 'uint32 block_created',
'uint256 balance',
'address contract'
),
keccak256(
'Receiver closing signature',
_sender_address,
// _open_block_number,
_balance,
address(this)
)
);
// Derive address from signature
address signer = ECVerify.ecverify(message_hash, _closing_sig);
return signer;
}
/// @notice Returns the unique channel identifier used in the contract.
/// @param _sender_address The address of the sender.
/// @param _receiver_address The address of the receiver.
/// @param _open_block_number The block number at which the channel was created.
/// @return Unique channel identifier.
function getKey(
address _sender_address,
address _receiver_address,
uint32 _open_block_number)
public
pure
returns (bytes32 data)
{
// TMP: ignore _open_block_number as channel identifier, so that only one channel allowed
return keccak256(_sender_address, _receiver_address);
}
/*
* Private functions
*/
/// @dev Creates a new channel between a sender and a receiver.
/// @param _sender_address The address of the sender.
/// @param _receiver_address The address of the receiver.
function createChannelPrivate(
address _sender_address,
address _receiver_address,
uint256 _deposit)
private
{
require(_deposit <= channel_deposit_bugbounty_limit);
uint32 open_block_number = uint32(block.number);
// Create unique identifier from sender, receiver and current block number
bytes32 key = getKey(_sender_address, _receiver_address, open_block_number);
require(channels[key].deposit == 0);
require(channels[key].open_block_number == 0);
require(closing_requests[key].settle_block_number == 0);
// Store channel information
channels[key] = Channel({deposit: _deposit, open_block_number: open_block_number});
emit ChannelCreated(_sender_address, _receiver_address, _deposit);
}
/// @dev Updates internal balance Structures when the sender adds tokens to the channel.
/// @param _sender_address The address of the sender.
/// @param _receiver_address The address of the receiver.
/// @param _open_block_number The block number at which the channel was created.
/// @param _added_deposit The added token deposit with which the current deposit is increased.
function updateInternalBalanceStructs(
address _sender_address,
address _receiver_address,
uint32 _open_block_number,
uint256 _added_deposit)
private
{
require(_added_deposit > 0);
require(_open_block_number > 0);
bytes32 key = getKey(_sender_address, _receiver_address, _open_block_number);
require(channels[key].open_block_number > 0);
require(closing_requests[key].settle_block_number == 0);
require(channels[key].deposit + _added_deposit <= channel_deposit_bugbounty_limit);
channels[key].deposit += _added_deposit;
assert(channels[key].deposit >= _added_deposit);
emit ChannelToppedUp(_sender_address, _receiver_address, channels[key].open_block_number, _added_deposit);
}
/// @dev Deletes the channel and settles by transfering the balance to the receiver
/// and the rest of the deposit back to the sender.
/// @param _sender_address The address of the sender.
/// @param _receiver_address The address of the receiver.
/// @param _open_block_number The block number at which the channel was created.
/// @param _balance The amount of tokens owed by the sender to the receiver.
function settleChannel(
address _sender_address,
address _receiver_address,
uint32 _open_block_number,
uint256 _balance)
private
{
bytes32 key = getKey(_sender_address, _receiver_address, _open_block_number);
Channel memory channel = channels[key];
require(channel.open_block_number > 0);
require(_balance <= channel.deposit);
require(withdrawn_balances[key] <= _balance);
// Remove closed channel structures
// Change state before transfer call
delete channels[key];
delete closing_requests[key];
// Send the unwithdrawn _balance to the receiver
uint256 _receiver_remaining_balance = _balance - withdrawn_balances[key];
_receiver_address.transfer(_receiver_remaining_balance);
// Send deposit - balance back to sender
_sender_address.transfer(channel.deposit - _balance);
emit ChannelSettled(
_sender_address,
_receiver_address,
channel.open_block_number,
_balance,
_receiver_remaining_balance
);
}
/*
* Internal functions
*/
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) internal view returns (bool) {
uint size;
if (_addr == 0) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
}
|
@dev Returns the receiver address extracted from the closing signature. Works with eth_signTypedData https://github.com/ethereum/EIPs/pull/712. @param _sender_address The address of the sender. @param _open_block_number The block number at which the channel was created. @param _balance The amount of balance. @param _closing_sig The receiver's signed balance message, containing the sender's address. @return Address of the closing signature signer. The variable names from below will be shown to the sender when signing the balance proof. The hashed strings should be kept in sync with this function's parameters (variable names and types). ! Note that EIP712 might change how hashing is done, triggering a new contract deployment with updated code. 'uint32 block_created', _open_block_number, Derive address from signature
|
function extractClosingSignature(
address _sender_address,
uint32 _open_block_number,
uint256 _balance,
bytes _closing_sig)
public
view
returns (address)
{
bytes32 message_hash = keccak256(
keccak256(
'string message_id',
'address sender',
'uint256 balance',
'address contract'
),
keccak256(
'Receiver closing signature',
_sender_address,
_balance,
address(this)
)
);
address signer = ECVerify.ecverify(message_hash, _closing_sig);
return signer;
}
| 12,693,242 |
[
1,
1356,
326,
5971,
1758,
9438,
628,
326,
7647,
3372,
18,
4147,
87,
598,
13750,
67,
2977,
11985,
751,
2333,
2207,
6662,
18,
832,
19,
546,
822,
379,
19,
41,
18246,
19,
13469,
19,
27,
2138,
18,
225,
389,
15330,
67,
2867,
1021,
1758,
434,
326,
5793,
18,
225,
389,
3190,
67,
2629,
67,
2696,
1021,
1203,
1300,
622,
1492,
326,
1904,
1703,
2522,
18,
225,
389,
12296,
1021,
3844,
434,
11013,
18,
225,
389,
19506,
67,
7340,
1021,
5971,
1807,
6726,
11013,
883,
16,
4191,
326,
5793,
1807,
1758,
18,
327,
5267,
434,
326,
7647,
3372,
10363,
18,
1021,
2190,
1257,
628,
5712,
903,
506,
12188,
358,
326,
5793,
1347,
10611,
326,
11013,
14601,
18,
1021,
14242,
2064,
1410,
506,
16555,
316,
3792,
598,
333,
445,
1807,
1472,
261,
6105,
1257,
471,
1953,
2934,
401,
3609,
716,
512,
2579,
27,
2138,
4825,
2549,
3661,
24641,
353,
2731,
16,
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,
2608,
15745,
5374,
12,
203,
3639,
1758,
389,
15330,
67,
2867,
16,
203,
3639,
2254,
1578,
389,
3190,
67,
2629,
67,
2696,
16,
203,
3639,
2254,
5034,
389,
12296,
16,
203,
3639,
1731,
389,
19506,
67,
7340,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
2867,
13,
203,
565,
288,
203,
3639,
1731,
1578,
883,
67,
2816,
273,
417,
24410,
581,
5034,
12,
203,
5411,
417,
24410,
581,
5034,
12,
203,
7734,
296,
1080,
883,
67,
350,
2187,
203,
7734,
296,
2867,
5793,
2187,
203,
7734,
296,
11890,
5034,
11013,
2187,
203,
7734,
296,
2867,
6835,
11,
203,
5411,
262,
16,
203,
5411,
417,
24410,
581,
5034,
12,
203,
7734,
296,
12952,
7647,
3372,
2187,
203,
7734,
389,
15330,
67,
2867,
16,
203,
7734,
389,
12296,
16,
203,
7734,
1758,
12,
2211,
13,
203,
5411,
262,
203,
3639,
11272,
203,
203,
3639,
1758,
10363,
273,
7773,
8097,
18,
557,
8705,
12,
2150,
67,
2816,
16,
389,
19506,
67,
7340,
1769,
203,
3639,
327,
10363,
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
] |
pragma solidity ^0.4.11;
/*
Initially from : https://github.com/vitiko/solidity-test-example/blob/master/contracts/Congress.sol
Changed by : Jimmy Paris
Changed to be accessible only for a liste of the members
Members can propose new members who will be accepted or not by votations.
Note that in this version the creator can add the first members in a inital period.
*/
import './MomentalyOwned.sol';
contract CongressOwned is MomentalyOwned {
/* constants, variables and events */
uint256 public constant minimumQuorum = 3; // Minimum acceptation + rejection
uint256 public constant debatingPeriod = 7 days; //minimal delay to close a votation
uint256 public constant majorityMinPourcent = 67;
uint256 public constant periodEnterProposal = 7 days; //minimal delay enter 2 proposals from the same sender
Proposal[] public proposals;
uint256 public numProposals;
mapping (address => uint256) public timeLastProposal;
mapping (address => uint256) public memberId;
Member[] public members;
event ProposalAdded(uint256 proposalID, address candidate, string candidateName);
event Voted(uint256 proposalID, bool position, address voter, string justification);
event ProposalTallied(uint256 proposalID, uint256 result, uint256 quorum, bool active);
event MembershipChanged(address member, bool isMember);
struct Proposal {
uint256 id;
address candidateAddress;
string candidateName; //name of the candidate
uint256 votingDeadline;
bool executed;
bool proposalPassed;
uint256 numberOfVotes;
uint256 currentResult;
Vote[] votes;
mapping (address => bool) voted;
}
struct Member {
address member;
string name;
uint256 memberSince;
}
struct Vote {
bool inSupport;
address voter;
string justification;
}
/* Modifier that allows only members */
modifier onlyMembers(address addr) {
require(memberId[addr] != 0);
_;
}
/* Modifier that allows only not members */
modifier onlyNotMembers(address addr) {
require(memberId[addr] == 0);
_;
}
/* First time setup */
function CongressOwned() {
// It’s necessary to add an empty first member (as a sentinel)
addMember(0, '');
// and let's add the founder, to save a step later
addMember(owner, 'founder');
}
function getMembersCount() constant returns (uint256){
return members.length -1;
}
/*make a new member*/
function addElectedMember(address targetMember, string memberName) onlyAfterQ1 onlyNotMembers(targetMember) private {
uint256 id;
memberId[targetMember] = members.length;
id = members.length++;
members[id] = Member({member: targetMember, memberSince: now, name: memberName});
MembershipChanged(targetMember, true);
}
/*make a new "early" member*/
function addMember(address targetMember, string memberName) onlyOwner onlyNotMembers(targetMember) onlyInQ1 {
uint256 id;
memberId[targetMember] = members.length;
id = members.length++;
members[id] = Member({member: targetMember, memberSince: now, name: memberName});
MembershipChanged(targetMember, true);
}
function removeMember(address targetMember) onlyOwner onlyInQ1 onlyMembers(targetMember) returns (bool){
for (uint256 i = memberId[targetMember]; i<members.length-1; i++){
members[i] = members[i+1];
}
memberId[targetMember] = 0;
balances[targetMember] = 0;
delete members[members.length-1];
members.length--;
MembershipChanged(targetMember, false);
}
function getTime() constant returns (uint256){
return now;
}
/* Function to create a new proposal */
function newProposal( address candidateAddress,string candidateName) onlyAfterQ1 onlyMembers(msg.sender) onlyNotMembers(candidateAddress) returns (uint256 proposalID) {
require(now >= timeLastProposal[msg.sender] + periodEnterProposal); //Sender did not make a proposal for a while
timeLastProposal[msg.sender] = now; //Update the time of the last proposal from the sender
//Create a new proposal
proposalID = proposals.length++; //Set the id of the new proposal and (after) increase the proposals array
Proposal storage p = proposals[proposalID]; //Set the pointer
p.id = proposalID; //Set the id of this proposal
p.candidateAddress = candidateAddress; //Set the ETH address of the candidate
p.candidateName = candidateName; //Set the candidate firm identifier
p.votingDeadline = now + debatingPeriod; //Set the deadline of this proposal
p.executed = false; //Set the proposal to unexecuted
p.proposalPassed = false; //Set the result of the proposal to false (unused if not executed)
//Vote for my own proposal
Vote storage v = p.votes[p.votes.length++]; //Get a new vote structure
v.voter = msg.sender; //Set the voter
v.inSupport = true; //Set the stat of his vote (accepted or rejected)
v.justification = "Creator's vote"; //Set the justification
p.voted[msg.sender] = true; // Sender has voted for this proposal
p.numberOfVotes = 1; //Set the count of votes
p.currentResult = 1; //Set the count of acceptations
numProposals = proposalID +1; //Update the number of proposals
ProposalAdded(proposalID, candidateAddress, candidateName);
return proposalID;
}
function vote(uint256 proposalID,bool supportsProposal,string justificationText) onlyAfterQ1 onlyMembers(msg.sender) returns (uint256 voteID) {
Proposal storage p = proposals[proposalID]; // Get the proposal
require(p.voted[msg.sender] == false); // If has already voted, cancel
Vote storage v = p.votes[p.votes.length++]; //Get a new vote structure
v.voter = msg.sender; //Set the voter
v.inSupport = supportsProposal; //Set the stat of his vote (accepted or rejected)
v.justification = justificationText; // Set the justification
p.voted[msg.sender] = true; // Set this voter as having voted
p.numberOfVotes++; // Increase the number of votes
if (supportsProposal) { // If they support the proposal
p.currentResult++; // Increase score
}
// Create a log of this event
Voted(proposalID, supportsProposal, msg.sender, justificationText);
return p.numberOfVotes;
}
function executeProposal(uint256 proposalID) onlyAfterQ1 {
Proposal storage p = proposals[proposalID];
require(now >= p.votingDeadline); // Has the voting deadline arrived?
require(!p.executed); // Has it been already executed or is it being executed?
require(p.numberOfVotes >= minimumQuorum); //Has a minimum quorum?
/* If difference between support and opposition is larger than margin */
if ( p.currentResult * 100 / p.numberOfVotes >= majorityMinPourcent) {
// Add the member
addElectedMember(p.candidateAddress,p.candidateName);
p.proposalPassed = true;
} else {
p.proposalPassed = false;
}
p.executed = true; //Note the proposal as executed
ProposalTallied(proposalID, p.currentResult, p.numberOfVotes, p.proposalPassed); //Fire event
}
function getVoteFromProposal(uint256 idProposal, uint256 idVote) constant returns (address, bool, string) {
Proposal memory p = proposals[idProposal];
Vote memory v = p.votes[idVote];
return (v.voter, v.inSupport, v.justification);
}
}
|
Update the time of the last proposal from the sender
|
timeLastProposal[msg.sender] = now;
| 14,079,406 |
[
1,
1891,
326,
813,
434,
326,
1142,
14708,
628,
326,
5793,
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,
202,
21114,
202,
957,
3024,
14592,
63,
3576,
18,
15330,
65,
273,
2037,
31,
202,
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
] |
./partial_match/1/0xbfB9fFEB6019b5a5E5354a5eB907D4A216111061/sources/ETF.sol
|
once enabled, can never be turned off
|
function enableTrading() external onlyOwner {
tradingActive = true;
lastLpBurnTime = block.timestamp;
}
| 16,092,104 |
[
1,
8243,
3696,
16,
848,
5903,
506,
21826,
3397,
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,
4237,
1609,
7459,
1435,
3903,
1338,
5541,
288,
203,
3639,
1284,
7459,
3896,
273,
638,
31,
203,
3639,
1142,
48,
84,
38,
321,
950,
273,
1203,
18,
5508,
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
] |
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../standard-pool/StandardPoolConverter.sol";
/**
* @dev This contract is a specialized version of the converter, which implements
* a constant conversion-rate (configurable by the owner of the converter).
*/
contract FixedRatePoolConverter is StandardPoolConverter {
mapping(IReserveToken => uint256) private _rate;
/**
* @dev initializes a new FixedRatePoolConverter instance
*
* @param _anchor anchor governed by the converter
* @param _registry address of a contract registry contract
* @param _maxConversionFee maximum conversion fee, represented in ppm
*/
constructor(
IConverterAnchor _anchor,
IContractRegistry _registry,
uint32 _maxConversionFee
) public StandardPoolConverter(_anchor, _registry, _maxConversionFee) {}
/**
* @dev returns the converter type
*
* @return see the converter types in the the main contract doc
*/
function converterType() public pure override returns (uint16) {
return 4;
}
/**
* @dev returns the worth of the 1st reserve token in units of the 2nd reserve token
*
* @return the numerator of the rate between the 1st reserve token and the 2nd reserve token
* @return the denominator of the rate between the 1st reserve token and the 2nd reserve token
*/
function rate() public view returns (uint256, uint256) {
IReserveToken[] memory _reserveTokens = reserveTokens();
return (_rate[_reserveTokens[0]], _rate[_reserveTokens[1]]);
}
/**
* @dev sets the worth of the 1st reserve token in units of the 2nd reserve token
* can be executed only by the owner of the converter
*
* @param rateN the numerator of the rate between the 1st reserve token and the 2nd reserve token
* @param rateD the denominator of the rate between the 1st reserve token and the 2nd reserve token
*/
function setRate(uint256 rateN, uint256 rateD) public ownerOnly {
require(rateN > 0 && rateD > 0, "ERR_INVALID_RATE");
IReserveToken[] memory _reserveTokens = reserveTokens();
_rate[_reserveTokens[0]] = rateN;
_rate[_reserveTokens[1]] = rateD;
}
/**
* @dev returns the expected amount and expected fee for converting one reserve to another
*
* @param _sourceToken address of the source reserve token contract
* @param _targetToken address of the target reserve token contract
* @param _amount amount of source reserve tokens converted
*
* @return expected amount in units of the target reserve token
* @return expected fee in units of the target reserve token
*/
function targetAmountAndFee(
IReserveToken _sourceToken,
IReserveToken _targetToken,
uint256 _amount
) public view override active returns (uint256, uint256) {
return targetAmountAndFee(_sourceToken, _targetToken, 0, 0, _amount);
}
/**
* @dev returns the expected amount and expected fee for converting one reserve to another
*
* @param _sourceToken address of the source reserve token contract
* @param _targetToken address of the target reserve token contract
* @param _amount amount of source reserve tokens converted
*
* @return expected amount in units of the target reserve token
* @return expected fee in units of the target reserve token
*/
function targetAmountAndFee(
IReserveToken _sourceToken,
IReserveToken _targetToken,
uint256, /* _sourceBalance */
uint256, /* _targetBalance */
uint256 _amount
) internal view override returns (uint256, uint256) {
IReserveToken[] memory _reserveTokens = reserveTokens();
require(
(_sourceToken == _reserveTokens[0] && _targetToken == _reserveTokens[1]) ||
(_sourceToken == _reserveTokens[1] && _targetToken == _reserveTokens[0]),
"ERR_INVALID_RESERVES"
);
uint256 rateN = _rate[_sourceToken];
uint256 rateD = _rate[_targetToken];
uint256 amount = _amount.mul(rateN).div(rateD);
uint256 fee = calculateFee(amount);
return (amount - fee, fee);
}
/**
* @dev returns the required amount and expected fee for converting one reserve to another
*
* @param _sourceToken address of the source reserve token contract
* @param _targetToken address of the target reserve token contract
* @param _amount amount of target reserve tokens desired
*
* @return required amount in units of the source reserve token
* @return expected fee in units of the target reserve token
*/
function sourceAmountAndFee(
IReserveToken _sourceToken,
IReserveToken _targetToken,
uint256 _amount
) public view override active returns (uint256, uint256) {
uint256 rateN = _rate[_sourceToken];
uint256 rateD = _rate[_targetToken];
uint256 fee = calculateFeeInv(_amount);
uint256 amount = _amount.add(fee).mul(rateD).div(rateN);
return (amount, fee);
}
/**
* @dev get the amount of pool tokens to mint for the caller
* and the amount of reserve tokens to transfer from the caller
*
* @param _reserveTokens address of each reserve token
* @param _reserveAmounts amount of each reserve token
* @param _reserveBalances balance of each reserve token
* @param _totalSupply total supply of pool tokens
*
* @return amount of pool tokens to mint for the caller
* @return amount of reserve tokens to transfer from the caller
*/
function addLiquidityAmounts(
IReserveToken[] memory _reserveTokens,
uint256[] memory _reserveAmounts,
uint256[2] memory _reserveBalances,
uint256 _totalSupply
) internal view override returns (uint256, uint256[2] memory) {
uint256 rateN = _rate[_reserveTokens[0]];
uint256 rateD = _rate[_reserveTokens[1]];
uint256 n = _reserveAmounts[0].mul(rateN).add(_reserveAmounts[1]).mul(rateD);
uint256 d = _reserveBalances[0].mul(rateN).add(_reserveBalances[1]).mul(rateD);
return (_totalSupply.mul(n).div(d), [_reserveAmounts[0], _reserveAmounts[1]]);
}
/**
* @dev checks whether or not at least one reserve amount is larger than zero
*
* @param _reserveAmounts array of reserve amounts
*
* @return true if at least one of the reserve amounts is larger than zero; false otherwise
*/
function validReserveAmounts(uint256[] memory _reserveAmounts) internal pure override returns (bool) {
return _reserveAmounts[0] > 0 || _reserveAmounts[1] > 0;
}
}
|
* @dev returns the worth of the 1st reserve token in units of the 2nd reserve token @return the numerator of the rate between the 1st reserve token and the 2nd reserve token @return the denominator of the rate between the 1st reserve token and the 2nd reserve token/
|
function rate() public view returns (uint256, uint256) {
IReserveToken[] memory _reserveTokens = reserveTokens();
return (_rate[_reserveTokens[0]], _rate[_reserveTokens[1]]);
}
| 7,286,016 |
[
1,
6154,
326,
26247,
434,
326,
404,
334,
20501,
1147,
316,
4971,
434,
326,
576,
4880,
20501,
1147,
327,
326,
16730,
434,
326,
4993,
3086,
326,
404,
334,
20501,
1147,
471,
326,
576,
4880,
20501,
1147,
327,
326,
15030,
434,
326,
4993,
3086,
326,
404,
334,
20501,
1147,
471,
326,
576,
4880,
20501,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
565,
445,
4993,
1435,
1071,
1476,
1135,
261,
11890,
5034,
16,
2254,
5034,
13,
288,
203,
3639,
467,
607,
6527,
1345,
8526,
3778,
389,
455,
6527,
5157,
273,
20501,
5157,
5621,
203,
3639,
327,
261,
67,
5141,
63,
67,
455,
6527,
5157,
63,
20,
65,
6487,
389,
5141,
63,
67,
455,
6527,
5157,
63,
21,
13563,
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
] |
./partial_match/97/0xccA3EAC7477d6f551256425A4787532534E47d24/sources/MyToken.sol
|
TBA testing: MyToken , production: BinanceBTCToken
|
contract MyToken is ERC20, Ownable {
| 11,374,208 |
[
1,
56,
12536,
225,
7769,
30,
8005,
1345,
269,
12449,
30,
16827,
1359,
38,
56,
1268,
969,
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,
16351,
8005,
1345,
353,
4232,
39,
3462,
16,
14223,
6914,
288,
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,
-100
] |
./partial_match/1/0x904d7c6e649992417D920a93267A0C492B75F77F/sources/MatteNft.sol
|
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.
|
function isContract(address account) public onlyOwner view returns (bool) {
uint size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
| 2,834,453 |
[
1,
2503,
707,
14719,
281,
603,
1110,
7000,
554,
16,
1492,
1135,
374,
364,
20092,
316,
16171,
16,
3241,
326,
981,
353,
1338,
4041,
622,
326,
679,
434,
326,
3885,
4588,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
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,
353,
8924,
12,
2867,
2236,
13,
1071,
1338,
5541,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
2254,
963,
31,
203,
3639,
19931,
288,
203,
5411,
963,
519,
1110,
7000,
554,
12,
4631,
13,
203,
3639,
289,
203,
3639,
327,
963,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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/42220/0xdc58D242E79bfc2C3dc1742b2c0F31B994E32e28/sources/contracts/ERC20.sol
|
* @dev Throws if called by any account other than the minter./
|
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
function _afterTokenTransfer(
address from,
address to,
uint256 amount
}
modifier onlyMinter() {
require(msg.sender == minter, "Caller is not the minter");
_;
}
| 3,496,119 |
[
1,
21845,
309,
2566,
635,
1281,
2236,
1308,
2353,
326,
1131,
387,
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,
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,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
203,
565,
445,
389,
5205,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
97,
203,
203,
203,
565,
9606,
1338,
49,
2761,
1435,
288,
203,
3639,
2583,
12,
3576,
18,
15330,
422,
1131,
387,
16,
315,
11095,
353,
486,
326,
1131,
387,
8863,
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,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-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.6.6 https://hardhat.org
// File hardhat/[email protected]
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected]
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;
}
}
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
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;
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
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 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;
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
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);
}
}
// File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected]
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);
}
// File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected]
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 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;
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/utils/structs/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// File @openzeppelin/contracts-upgradeable/access/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
function __AccessControlEnumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
}
function __AccessControlEnumerable_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControlUpgradeable) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/utils/math/[email protected]
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 SafeMathUpgradeable {
/**
* @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-upgradeable/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @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;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/[email protected]
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 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);
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
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);
}
}
}
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected]
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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable {
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
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 = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[44] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/[email protected]
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 IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/[email protected]
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 ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable {
function __ERC721Enumerable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Enumerable_init_unchained();
}
function __ERC721Enumerable_init_unchained() internal initializer {
}
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) {
return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Upgradeable.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721EnumerableUpgradeable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721Upgradeable.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
uint256[46] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721BurnableUpgradeable is Initializable, ContextUpgradeable, ERC721Upgradeable {
function __ERC721Burnable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721Burnable_init_unchained();
}
function __ERC721Burnable_init_unchained() internal initializer {
}
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/security/[email protected]
pragma solidity ^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 PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev ERC721 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC721PausableUpgradeable is Initializable, ERC721Upgradeable, PausableUpgradeable {
function __ERC721Pausable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
}
function __ERC721Pausable_init_unchained() internal initializer {
}
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/utils/[email protected]
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library CountersUpgradeable {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// File @openzeppelin/contracts-upgradeable/token/ERC721/presets/[email protected]
pragma solidity ^0.8.0;
/**
* @dev {ERC721} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
* - token ID and URI autogeneration
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC721PresetMinterPauserAutoIdUpgradeable is
Initializable, ContextUpgradeable,
AccessControlEnumerableUpgradeable,
ERC721EnumerableUpgradeable,
ERC721BurnableUpgradeable,
ERC721PausableUpgradeable
{
function initialize(
string memory name,
string memory symbol,
string memory baseTokenURI
) public virtual initializer {
__ERC721PresetMinterPauserAutoId_init(name, symbol, baseTokenURI);
}
using CountersUpgradeable for CountersUpgradeable.Counter;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
CountersUpgradeable.Counter private _tokenIdTracker;
string private _baseTokenURI;
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* Token URIs will be autogenerated based on `baseURI` and their token IDs.
* See {ERC721-tokenURI}.
*/
function __ERC721PresetMinterPauserAutoId_init(
string memory name,
string memory symbol,
string memory baseTokenURI
) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
__ERC721_init_unchained(name, symbol);
__ERC721Enumerable_init_unchained();
__ERC721Burnable_init_unchained();
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
__ERC721PresetMinterPauserAutoId_init_unchained(name, symbol, baseTokenURI);
}
function __ERC721PresetMinterPauserAutoId_init_unchained(
string memory name,
string memory symbol,
string memory baseTokenURI
) internal initializer {
_baseTokenURI = baseTokenURI;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
/**
* @dev Creates a new token for `to`. Its token ID will be automatically
* assigned (and available on the emitted {IERC721-Transfer} event), and the token
* URI autogenerated based on the base URI passed at construction.
*
* See {ERC721-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have minter role to mint");
// We cannot just use balanceOf to create the new tokenId because tokens
// can be burned (destroyed), so we need a separate counter.
_mint(to, _tokenIdTracker.current());
_tokenIdTracker.increment();
}
/**
* @dev Pauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable, ERC721PausableUpgradeable) {
super._beforeTokenTransfer(from, to, tokenId);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerableUpgradeable, ERC721Upgradeable, ERC721EnumerableUpgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
uint256[48] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC1155/[email protected]
pragma solidity ^0.8.0;
/**
* @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;
}
// File @openzeppelin/contracts-upgradeable/token/ERC1155/[email protected]
pragma solidity ^0.8.0;
/**
* @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);
}
// File @openzeppelin/contracts-upgradeable/token/ERC1155/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @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);
}
// File @openzeppelin/contracts-upgradeable/token/ERC1155/[email protected]
pragma solidity ^0.8.0;
/**
* @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;
}
// File @openzeppelin/contracts-upgradeable/token/ERC1155/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Extension of {ERC1155} that allows token holders to destroy both their
* own tokens and those that they have been approved to use.
*
* _Available since v3.1._
*/
abstract contract ERC1155BurnableUpgradeable is Initializable, ERC1155Upgradeable {
function __ERC1155Burnable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC1155Burnable_init_unchained();
}
function __ERC1155Burnable_init_unchained() internal initializer {
}
function burn(
address account,
uint256 id,
uint256 value
) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burn(account, id, value);
}
function burnBatch(
address account,
uint256[] memory ids,
uint256[] memory values
) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burnBatch(account, ids, values);
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC1155/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev ERC1155 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*
* _Available since v3.1._
*/
abstract contract ERC1155PausableUpgradeable is Initializable, ERC1155Upgradeable, PausableUpgradeable {
function __ERC1155Pausable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__Pausable_init_unchained();
__ERC1155Pausable_init_unchained();
}
function __ERC1155Pausable_init_unchained() internal initializer {
}
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
require(!paused(), "ERC1155Pausable: token transfer while paused");
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC1155/presets/[email protected]
pragma solidity ^0.8.0;
/**
* @dev {ERC1155} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC1155PresetMinterPauserUpgradeable is Initializable, ContextUpgradeable, AccessControlEnumerableUpgradeable, ERC1155BurnableUpgradeable, ERC1155PausableUpgradeable {
function initialize(string memory uri) public virtual initializer {
__ERC1155PresetMinterPauser_init(uri);
}
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, and `PAUSER_ROLE` to the account that
* deploys the contract.
*/
function __ERC1155PresetMinterPauser_init(string memory uri) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
__ERC1155_init_unchained(uri);
__ERC1155Burnable_init_unchained();
__Pausable_init_unchained();
__ERC1155Pausable_init_unchained();
__ERC1155PresetMinterPauser_init_unchained(uri);
}
function __ERC1155PresetMinterPauser_init_unchained(string memory uri) internal initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`, of token type `id`.
*
* See {ERC1155-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint");
_mint(to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}.
*/
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint");
_mintBatch(to, ids, amounts, data);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerableUpgradeable, ERC1155Upgradeable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override(ERC1155Upgradeable, ERC1155PausableUpgradeable) {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[45] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/extensions/[email protected]
pragma solidity ^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 ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable {
function __ERC20Burnable_init() internal initializer {
__Context_init_unchained();
__ERC20Burnable_init_unchained();
}
function __ERC20Burnable_init_unchained() internal initializer {
}
/**
* @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 currentAllowance = allowance(account, _msgSender());
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
unchecked {
_approve(account, _msgSender(), currentAllowance - amount);
}
_burn(account, amount);
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @dev ERC20 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable {
function __ERC20Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
}
function __ERC20Pausable_init_unchained() internal initializer {
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
require(!paused(), "ERC20Pausable: token transfer while paused");
}
uint256[50] private __gap;
}
// File @openzeppelin/contracts-upgradeable/token/ERC20/presets/[email protected]
pragma solidity ^0.8.0;
/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC20PresetMinterPauserUpgradeable is Initializable, ContextUpgradeable, AccessControlEnumerableUpgradeable, ERC20BurnableUpgradeable, ERC20PausableUpgradeable {
function initialize(string memory name, string memory symbol) public virtual initializer {
__ERC20PresetMinterPauser_init(name, symbol);
}
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` and `PAUSER_ROLE` to the
* account that deploys the contract.
*
* See {ERC20-constructor}.
*/
function __ERC20PresetMinterPauser_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
__AccessControlEnumerable_init_unchained();
__ERC20_init_unchained(name, symbol);
__ERC20Burnable_init_unchained();
__Pausable_init_unchained();
__ERC20Pausable_init_unchained();
__ERC20PresetMinterPauser_init_unchained(name, symbol);
}
function __ERC20PresetMinterPauser_init_unchained(string memory name, string memory symbol) internal initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have minter role to mint");
_mint(to, amount);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC20Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC20PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) {
super._beforeTokenTransfer(from, to, amount);
}
uint256[50] private __gap;
}
// File contracts/EIP712Base.sol
pragma solidity ^0.8.0;
contract EIP712Base is Initializable {
struct EIP712Domain {
string name;
string version;
address verifyingContract;
bytes32 salt;
}
string constant public ERC712_VERSION = "1";
bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256(
bytes(
"EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)"
)
);
bytes32 internal domainSeperator;
// supposed to be called once while initializing.
// one of the contractsa that inherits this contract follows proxy pattern
// so it is not possible to do this in a constructor
function _initializeEIP712(
string memory name
)
internal
initializer
{
_setDomainSeperator(name);
}
function _setDomainSeperator(string memory name) internal {
domainSeperator = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(name)),
keccak256(bytes(ERC712_VERSION)),
address(this),
bytes32(getChainId())
)
);
}
function getDomainSeperator() public view returns (bytes32) {
return domainSeperator;
}
function getChainId() public view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* Accept message hash and returns hash message in EIP712 compatible form
* So that it can be used to recover signer from signature signed using EIP712 formatted data
* https://eips.ethereum.org/EIPS/eip-712
* "\\x19" makes the encoding deterministic
* "\\x01" is the version byte to make it compatible to EIP-191
*/
function toTypedMessageHash(bytes32 messageHash)
internal
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash)
);
}
}
// File contracts/NativeMetaTransaction.sol
pragma solidity ^0.8.0;
contract NativeMetaTransaction is EIP712Base {
using SafeMathUpgradeable for uint256;
bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256(
bytes(
"MetaTransaction(uint256 nonce,address from,bytes functionSignature)"
)
);
event MetaTransactionExecuted(
address userAddress,
address payable relayerAddress,
bytes functionSignature
);
mapping(address => uint256) nonces;
/*
* Meta transaction structure.
* No point of including value field here as if user is doing value transfer then he has the funds to pay for gas
* He should call the desired function directly in that case.
*/
struct MetaTransaction {
uint256 nonce;
address from;
bytes functionSignature;
}
function executeMetaTransaction(
address userAddress,
bytes memory functionSignature,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) public payable returns (bytes memory) {
MetaTransaction memory metaTx = MetaTransaction({
nonce: nonces[userAddress],
from: userAddress,
functionSignature: functionSignature
});
require(
verify(userAddress, metaTx, sigR, sigS, sigV),
"Signer and signature do not match"
);
// increase nonce for user (to avoid re-use)
nonces[userAddress] = nonces[userAddress].add(1);
emit MetaTransactionExecuted(
userAddress,
payable(msg.sender),
functionSignature
);
// Append userAddress and relayer address at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call(
abi.encodePacked(functionSignature, userAddress)
);
require(success, "Function call not successful");
return returnData;
}
function hashMetaTransaction(MetaTransaction memory metaTx)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
META_TRANSACTION_TYPEHASH,
metaTx.nonce,
metaTx.from,
keccak256(metaTx.functionSignature)
)
);
}
function getNonce(address user) public view returns (uint256 nonce) {
nonce = nonces[user];
}
function verify(
address signer,
MetaTransaction memory metaTx,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) internal view returns (bool) {
require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER");
return
signer ==
ecrecover(
toTypedMessageHash(hashMetaTransaction(metaTx)),
sigV,
sigR,
sigS
);
}
}
// File contracts/ContextMixin.sol
pragma solidity ^0.8.0;
abstract contract ContextMixin {
function msgSender()
internal
view
returns (address payable sender)
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = payable(msg.sender);
}
return sender;
}
}
// File contracts/CompiMinter.sol
pragma solidity ^0.8.0;
//import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
contract CompiMinter is
Initializable,
AccessControlEnumerableUpgradeable,
NativeMetaTransaction,
ContextMixin
{
using SafeMathUpgradeable for uint256;
ERC721PresetMinterPauserAutoIdUpgradeable private _tokenERC721;
IERC20Upgradeable private _tokenERC20;
// Mapping from address to boolean -> true if refund was used
mapping (address => bool) private _accountDiscountUsed;
// Mapping from address to amount of mints
mapping (address => uint8) private _accountMintCount;
address[] private _discountTokens;
bool[] private _discountTokensIsERC1155;
uint8 private _maxMintByAccount;
uint256 private _startTime;
uint256 private _endTime;
uint256 private _multPrice;
uint32 private _totalTokenAmount;
uint256 private _tokenCount;
function initialize(string memory domainSeparator) public initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_initializeEIP712(domainSeparator);
setTimeWindow(block.timestamp, block.timestamp.add(2592000));
setPrice(5000000000000000000);
_maxMintByAccount = 100;
_totalTokenAmount = 10010-14;
}
function setMaxSupply(uint32 maxSupply) public {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "CompiMinter: must have admin role to set max supply");
_totalTokenAmount = maxSupply;
emit MaxSupplySet(maxSupply);
}
/**
* @dev Max supply, minted count
*/
function getSupply() public view returns(uint32 maxSupply, uint256 currentSupply) {
return (_totalTokenAmount, _tokenCount);
}
function setDiscountTokens(address[] memory discountTokens, bool[] memory discountTokensIsERC1155) public {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "CompiMinter: must have admin role to set price");
require(discountTokens.length == discountTokensIsERC1155.length, "CompiMinter: array lengths must match");
_discountTokens = discountTokens;
_discountTokensIsERC1155 = discountTokensIsERC1155;
emit DiscountTokensSet(discountTokens, discountTokensIsERC1155);
}
function setPrice(uint256 multPrice) public {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "CompiMinter: must have admin role to set price");
_multPrice = multPrice;
emit PriceSet(multPrice);
}
function setTimeWindow(uint256 startTime, uint256 endTime) public {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "CompiMinter: must have admin role to change end time");
_startTime = startTime;
_endTime = endTime;
emit TimeWindowSet(startTime, endTime);
}
/**
* @dev Get time window
*/
function getTimeWindow() public view returns(uint256 startTime, uint256 endTime) {
return (_startTime, _endTime);
}
function setERC20(IERC20Upgradeable tokenERC20) external {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "CompiMinter: must have admin role to set token");
_tokenERC20 = tokenERC20;
emit ERC20Set(tokenERC20);
}
function setERC721(ERC721PresetMinterPauserAutoIdUpgradeable tokenERC721) external {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "CompiMinter: must have admin role to set PFP contract");
_tokenERC721 = tokenERC721;
emit ERC721Set(_tokenERC721);
}
function getPrice(address for_account) public view returns(uint256 _price, bool use_discount) {
//
bool willUseDiscount = false;
uint256 tmpPrice = _multPrice;
if (!_accountDiscountUsed[for_account]) {
for(uint i = 0; i < _discountTokens.length; i++) {
if (_discountTokensIsERC1155[i]) {
ERC1155PresetMinterPauserUpgradeable _contract = ERC1155PresetMinterPauserUpgradeable(_discountTokens[i]);
if (_contract.balanceOf(for_account, 0)>0) {
willUseDiscount = true;
break;
}
} else {
ERC721PresetMinterPauserAutoIdUpgradeable _contract = ERC721PresetMinterPauserAutoIdUpgradeable(_discountTokens[i]);
if (_contract.balanceOf(for_account)>0) {
willUseDiscount = true;
break;
}
}
}
}
if (!willUseDiscount) {
// Price not cut in half
tmpPrice = tmpPrice.mul(2);
}
//
return (tmpPrice, willUseDiscount);
}
/**
* @dev Get price, setting the discount as used.
*/
function _getPrice() private returns(uint256 _price) {
(uint256 tmpPrice, bool willUseDiscount) = getPrice(_msgSender());
// Mark discount as used
if (willUseDiscount) {
_accountDiscountUsed[_msgSender()] = true;
}
return tmpPrice;
}
/**
* @dev Is time window open?
*/
function isWindowOpen() public view returns(bool use_discount) {
if (block.timestamp > _startTime && block.timestamp < _endTime){
return true;
} else {
return false;
}
}
/**
* @dev Mints a new Compi from an id.
*/
function mintCompi(uint256 maxPrice)
external
price(_getPrice(), maxPrice)
{
require(!_tokenERC721.paused(), "CompiMinter: token mint while paused");
require(block.timestamp > _startTime, "CompiMinter: minting event not started");
require(block.timestamp < _endTime, "CompiMinter: minting event ended");
require(_tokenCount < _totalTokenAmount, "CompiMinter: contract mint limit reached");
require(_accountMintCount[_msgSender()] < _maxMintByAccount, "CompiMinter: max mints reached");
_tokenCount = _tokenCount.add(1);
_accountMintCount[_msgSender()] += 1;
_tokenERC721.mint(_msgSender());
}
/*
* @dev Remove all Ether from the contract, and transfer it to account of owner
*/
function withdrawBalance() external {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "CompiMinter: must have admin role to withdraw");
uint256 balance = _tokenERC20.balanceOf(address(this));
_tokenERC20.transfer(_msgSender(), balance);
emit Withdraw(balance);
}
// Modifiers
/**
* @dev modifier Associete fee with a function call. If the caller sent too much, then is discounted, but only after the function body.
* This was dangerous before Solidity version 0.4.0, where it was possible to skip the part after `_;`.
* @param _amount - ether needed to call the function
*/
modifier price(uint256 _amount, uint256 maxPrice) {
require(maxPrice >= _amount, "CompiMinter: price exceedes maxPrice");
require(_tokenERC20.balanceOf(_msgSender()) >= _amount, "CompiMinter: Not enough ERC20 tokens.");
require(_tokenERC20.allowance(_msgSender(), address(this)) >= _amount, "CompiMinter: Not enough ERC20 token allowance.");
_;
_tokenERC20.transferFrom(_msgSender(), address(this), _amount);
}
// This is to support Native meta transactions
// never use msg.sender directly, use _msgSender() instead
function _msgSender()
internal
override
view
returns (address sender) // Eibriel removed "payable"
{
return ContextMixin.msgSender();
}
/* Events */
/**
* @dev Emits when owner take ETH out of contract
* @param balance - amount of ETh sent out from contract
*/
event Withdraw(uint256 balance);
/**
* @dev Emits when discount tokens are set
* @param discountTokens - array of ERC721 or ERC1155 address
* @param discountTokensIsERC1155 - array of boolean. True if token is ERC1155
*/
event DiscountTokensSet(address[] discountTokens, bool[] discountTokensIsERC1155);
/**
* @dev Emits when a new price is set
* @param multPrice - a multiplier for the price
*/
event PriceSet(uint256 multPrice);
/**
* @dev Emits when a new max supply is set
* @param maxSupply - max amount of tokens to mint
*/
event MaxSupplySet(uint256 maxSupply);
/**
* @dev Emits when the contract URI is set
* @param contractURI - an URL to the metadata
*/
event ContractURISet(string contractURI);
/**
* @dev Emits when the start and end time are set
* @param startTime - the event start time
* @param endTime - the event end time
*/
event TimeWindowSet(uint256 startTime, uint256 endTime);
/**
* @dev Emits when the minting ERC721 contract address is set
* @param tokenERC721 - an address to the minting ERC721 contract
*/
event ERC721Set(IERC721Upgradeable tokenERC721);
/**
* @dev Emits when the payment ERC20 contract address is set
* @param tokenERC20 - an address to the payment ERC20 contract
*/
event ERC20Set(IERC20Upgradeable tokenERC20);
}
|
* @dev Implementation of the basic standard multi-token. _Available since v3.1._/ Mapping from token ID to account balances Mapping from account to operator approvals Used as the URI for all token types by relying on ID substitution, e.g. https:token-cdn-domain/{id}.json
|
contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable {
using AddressUpgradeable for address;
mapping(uint256 => mapping(address => uint256)) private _balances;
mapping(address => mapping(address => bool)) private _operatorApprovals;
string private _uri;
}
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_);
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC1155Upgradeable).interfaceId ||
interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
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];
}
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;
}
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;
}
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);
}
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
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);
}
) internal virtual {}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
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");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
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");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
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");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
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");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
} catch Error(string memory reason) {
} catch {
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");
}
revert(reason);
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");
}
revert(reason);
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");
}
revert(reason);
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");
}
revert(reason);
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
} catch Error(string memory reason) {
} catch {
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
uint256[47] private __gap;
}
| 12,569,548 |
[
1,
13621,
434,
326,
5337,
4529,
3309,
17,
2316,
18,
389,
5268,
3241,
331,
23,
18,
21,
6315,
19,
9408,
628,
1147,
1599,
358,
2236,
324,
26488,
9408,
628,
2236,
358,
3726,
6617,
4524,
10286,
487,
326,
3699,
364,
777,
1147,
1953,
635,
283,
6291,
603,
1599,
12785,
16,
425,
18,
75,
18,
2333,
30,
2316,
17,
20902,
17,
4308,
4938,
350,
5496,
1977,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
16351,
4232,
39,
2499,
2539,
10784,
429,
353,
10188,
6934,
16,
1772,
10784,
429,
16,
4232,
39,
28275,
10784,
429,
16,
467,
654,
39,
2499,
2539,
10784,
429,
16,
467,
654,
39,
2499,
2539,
2277,
3098,
10784,
429,
288,
203,
565,
1450,
5267,
10784,
429,
364,
1758,
31,
203,
203,
565,
2874,
12,
11890,
5034,
516,
2874,
12,
2867,
516,
2254,
5034,
3719,
3238,
389,
70,
26488,
31,
203,
203,
565,
2874,
12,
2867,
516,
2874,
12,
2867,
516,
1426,
3719,
3238,
389,
9497,
12053,
4524,
31,
203,
203,
565,
533,
3238,
389,
1650,
31,
203,
203,
97,
203,
203,
565,
445,
1001,
654,
39,
2499,
2539,
67,
2738,
12,
1080,
3778,
2003,
67,
13,
2713,
12562,
288,
203,
3639,
1001,
1042,
67,
2738,
67,
4384,
8707,
5621,
203,
3639,
1001,
654,
39,
28275,
67,
2738,
67,
4384,
8707,
5621,
203,
3639,
1001,
654,
39,
2499,
2539,
67,
2738,
67,
4384,
8707,
12,
1650,
67,
1769,
203,
565,
289,
203,
203,
565,
445,
1001,
654,
39,
2499,
2539,
67,
2738,
67,
4384,
8707,
12,
1080,
3778,
2003,
67,
13,
2713,
12562,
288,
203,
3639,
389,
542,
3098,
12,
1650,
67,
1769,
203,
565,
289,
203,
203,
565,
445,
6146,
1358,
12,
3890,
24,
1560,
548,
13,
1071,
1476,
5024,
3849,
12,
654,
39,
28275,
10784,
429,
16,
467,
654,
39,
28275,
10784,
429,
13,
1135,
261,
6430,
13,
288,
203,
3639,
327,
203,
5411,
1560,
548,
422,
618,
12,
45,
654,
39,
2499,
2539,
10784,
429,
2934,
5831,
548,
747,
203,
5411,
1560,
548,
2
] |
./full_match/1/0x9bC228711706db212ED2BC12d9dC1643cf304EEA/sources/lib/openzeppelin-contracts-upgradeable/contracts/token/ERC20/utils/SafeERC20Upgradeable.sol
|
* @title SafeERC20 @dev Wrappers around ERC20 operations that throw on failure (when the token contract returns false). Tokens that return no value (and instead revert or throw on failure) are also supported, non-reverting calls are assumed to be successful. To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, which allows you to call the safe operations as `token.safeTransfer(...)`, etc./
|
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
error SafeERC20FailedOperation(address token);
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
function forceApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
function forceApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
function safePermit(
IERC20PermitUpgradeable token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
if (nonceAfter != nonceBefore + 1) {
revert SafeERC20FailedOperation(address(token));
}
}
function safePermit(
IERC20PermitUpgradeable token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
if (nonceAfter != nonceBefore + 1) {
revert SafeERC20FailedOperation(address(token));
}
}
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
function _callOptionalReturnBool(IERC20Upgradeable token, bytes memory data) private returns (bool) {
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
| 8,424,055 |
[
1,
9890,
654,
39,
3462,
225,
4266,
10422,
6740,
4232,
39,
3462,
5295,
716,
604,
603,
5166,
261,
13723,
326,
1147,
6835,
1135,
629,
2934,
13899,
716,
327,
1158,
460,
261,
464,
3560,
15226,
578,
604,
603,
5166,
13,
854,
2546,
3260,
16,
1661,
17,
266,
1097,
310,
4097,
854,
12034,
358,
506,
6873,
18,
2974,
999,
333,
5313,
1846,
848,
527,
279,
1375,
9940,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
68,
3021,
358,
3433,
6835,
16,
1492,
5360,
1846,
358,
745,
326,
4183,
5295,
487,
1375,
2316,
18,
4626,
5912,
5825,
13,
9191,
5527,
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
] |
[
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
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
] |
[
1,
12083,
14060,
654,
39,
3462,
10784,
429,
288,
203,
565,
1450,
5267,
10784,
429,
364,
1758,
31,
203,
203,
565,
555,
14060,
654,
39,
3462,
2925,
2988,
12,
2867,
1147,
1769,
203,
203,
565,
555,
14060,
654,
39,
3462,
2925,
23326,
448,
7009,
1359,
12,
2867,
17571,
264,
16,
2254,
5034,
783,
7009,
1359,
16,
2254,
5034,
3764,
23326,
448,
1769,
203,
203,
203,
565,
445,
4183,
5912,
12,
45,
654,
39,
3462,
10784,
429,
1147,
16,
1758,
358,
16,
2254,
5034,
460,
13,
2713,
288,
203,
3639,
389,
1991,
6542,
990,
12,
2316,
16,
24126,
18,
3015,
1477,
12,
2316,
18,
13866,
16,
261,
869,
16,
460,
3719,
1769,
203,
565,
289,
203,
203,
565,
445,
4183,
5912,
1265,
12,
45,
654,
39,
3462,
10784,
429,
1147,
16,
1758,
628,
16,
1758,
358,
16,
2254,
5034,
460,
13,
2713,
288,
203,
3639,
389,
1991,
6542,
990,
12,
2316,
16,
24126,
18,
3015,
1477,
12,
2316,
18,
13866,
1265,
16,
261,
2080,
16,
358,
16,
460,
3719,
1769,
203,
565,
289,
203,
203,
565,
445,
4183,
382,
11908,
7009,
1359,
12,
45,
654,
39,
3462,
10784,
429,
1147,
16,
1758,
17571,
264,
16,
2254,
5034,
460,
13,
2713,
288,
203,
3639,
2254,
5034,
1592,
7009,
1359,
273,
1147,
18,
5965,
1359,
12,
2867,
12,
2211,
3631,
17571,
264,
1769,
203,
3639,
2944,
12053,
537,
12,
2316,
16,
17571,
264,
16,
1592,
7009,
1359,
397,
460,
1769,
203,
565,
289,
203,
203,
565,
445,
4183,
23326,
448,
7009,
1359,
12,
45,
654,
39,
3462,
10784,
2
] |
pragma solidity ^0.5.7;
pragma experimental ABIEncoderV2;
import "./SafeMath.sol";
import "./LibGlobals.sol";
import "./IToken.sol";
import "./MatryxSystem.sol";
import "./MatryxCommit.sol";
import "./MatryxTournament.sol";
library LibPlatform {
using SafeMath for uint256;
event TournamentCreated(address indexed tournament, address indexed creator);
event TournamentBountyAdded(address indexed tournament, address indexed donor, uint256 amount);
function _canUseMatryx(
MatryxPlatform.Info storage info,
MatryxPlatform.Data storage data,
address user
)
internal
returns (bool)
{
if (data.blacklist[user]) return false;
if (data.whitelist[user]) return true;
if (IToken(info.token).balanceOf(user) > 0) {
data.whitelist[user] = true;
return true;
}
return false;
}
/// @dev Gets information about the Platform
/// @param info Platform info struct
/// @return Info Struct that contains system, token, and owner
function getInfo(
address,
address,
MatryxPlatform.Info storage info
)
public
view
returns (MatryxPlatform.Info memory)
{
return info;
}
/// @dev Return if a Tournament exists
/// @param data Platform data struct
/// @param tAddress Tournament address
/// @return true if Tournament exists
function isTournament(
address,
address,
MatryxPlatform.Data storage data,
address tAddress
)
public
view
returns (bool)
{
return data.tournaments[tAddress].info.owner != address(0);
}
/// @dev Return if a Commit exists
/// @param data Platform data struct
/// @param cHash Commit hash
/// @return true if Commit exists
function isCommit(
address,
address,
MatryxPlatform.Data storage data,
bytes32 cHash
)
public
view
returns (bool)
{
return data.commits[cHash].owner != address(0);
}
/// @dev Return if a Submission exists
/// @param data Platform data struct
/// @param sHash Submission hash
/// @return true if Submission exists
function isSubmission(
address,
address,
MatryxPlatform.Data storage data,
bytes32 sHash
)
public
view
returns (bool)
{
return data.submissions[sHash].tournament != address(0);
}
/// @dev Return total allocated MTX in Platform
/// @param data Platform data struct
/// @return Total allocated MTX in Platform
function getTotalBalance(
address,
address,
MatryxPlatform.Data storage data
)
public
view
returns (uint256)
{
return data.totalBalance;
}
/// @dev Return total number of Tournaments
/// @param data Platform data struct
/// @return Number of Tournaments on Platform
function getTournamentCount(
address,
address,
MatryxPlatform.Data storage data
)
public
view
returns (uint256)
{
return data.allTournaments.length;
}
/// @dev Return all Tournaments addresses
/// @param data Platform data struct
/// @return Array of Tournament addresses
function getTournaments(
address,
address,
MatryxPlatform.Data storage data
)
public
view
returns (address[] memory)
{
return data.allTournaments;
}
/// @dev Returns a Submission by its hash
/// @param data Platform data struct
/// @param submissionHash Submission hash
/// @return The submission details
function getSubmission(
address,
address,
MatryxPlatform.Data storage data,
bytes32 submissionHash
)
external
view
returns (LibTournament.SubmissionData memory)
{
return data.submissions[submissionHash];
}
/// @dev Blacklists or unblacklists a user address
/// @param info Platform info struct
/// @param data Platform data struct
/// @param user User address
/// @param isBlacklisted true to blacklist, false to unblacklist
function setUserBlacklisted(
address,
address sender,
MatryxPlatform.Info storage info,
MatryxPlatform.Data storage data,
address user,
bool isBlacklisted
)
public
{
require(sender == info.owner, "Must be Platform owner");
data.blacklist[user] = isBlacklisted;
}
/// @dev Creates a Tournament
/// @param sender msg.sender to Platform
/// @param info Platform info struct
/// @param data Platform data struct
/// @param tDetails Tournament details (content, bounty, entryFee)
/// @param rDetails Round details (start, end, review, bounty)
/// @return Address of the created Tournament
function createTournament(
address,
address sender,
MatryxPlatform.Info storage info,
MatryxPlatform.Data storage data,
LibTournament.TournamentDetails memory tDetails,
LibTournament.RoundDetails memory rDetails
)
public
returns (address)
{
require(_canUseMatryx(info, data, sender), "Must be allowed to use Matryx");
require(tDetails.bounty > 0, "Tournament bounty must be greater than 0");
require(rDetails.bounty <= tDetails.bounty, "Round bounty cannot exceed Tournament bounty");
uint256 version = IMatryxSystem(info.system).getVersion();
address tAddress = address(new MatryxTournament(version, info.system));
IMatryxSystem(info.system).setContractType(tAddress, uint256(LibSystem.ContractType.Tournament));
data.allTournaments.push(tAddress);
LibTournament.TournamentData storage tournament = data.tournaments[tAddress];
tournament.info.version = version;
tournament.info.owner = sender;
tournament.details = tDetails;
data.totalBalance = data.totalBalance.add(tDetails.bounty);
data.tournamentBalance[tAddress] = tDetails.bounty;
require(IToken(info.token).transferFrom(sender, address(this), tDetails.bounty), "Transfer failed");
LibTournament.createRound(tAddress, address(this), info, data, rDetails);
emit TournamentCreated(tAddress, sender);
emit TournamentBountyAdded(tAddress, sender, tDetails.bounty);
return tAddress;
}
}
|
@dev Creates a Tournament @param sender msg.sender to Platform @param info Platform info struct @param data Platform data struct @param tDetails Tournament details (content, bounty, entryFee) @param rDetails Round details (start, end, review, bounty) @return Address of the created Tournament
|
function createTournament(
address,
address sender,
MatryxPlatform.Info storage info,
MatryxPlatform.Data storage data,
LibTournament.TournamentDetails memory tDetails,
LibTournament.RoundDetails memory rDetails
)
public
returns (address)
{
require(_canUseMatryx(info, data, sender), "Must be allowed to use Matryx");
require(tDetails.bounty > 0, "Tournament bounty must be greater than 0");
require(rDetails.bounty <= tDetails.bounty, "Round bounty cannot exceed Tournament bounty");
uint256 version = IMatryxSystem(info.system).getVersion();
address tAddress = address(new MatryxTournament(version, info.system));
IMatryxSystem(info.system).setContractType(tAddress, uint256(LibSystem.ContractType.Tournament));
data.allTournaments.push(tAddress);
LibTournament.TournamentData storage tournament = data.tournaments[tAddress];
tournament.info.version = version;
tournament.info.owner = sender;
tournament.details = tDetails;
data.totalBalance = data.totalBalance.add(tDetails.bounty);
data.tournamentBalance[tAddress] = tDetails.bounty;
require(IToken(info.token).transferFrom(sender, address(this), tDetails.bounty), "Transfer failed");
LibTournament.createRound(tAddress, address(this), info, data, rDetails);
emit TournamentCreated(tAddress, sender);
emit TournamentBountyAdded(tAddress, sender, tDetails.bounty);
return tAddress;
}
| 12,869,163 |
[
1,
2729,
279,
2974,
30751,
225,
5793,
565,
1234,
18,
15330,
358,
11810,
225,
1123,
1377,
11810,
1123,
1958,
225,
501,
1377,
11810,
501,
1958,
225,
268,
3790,
225,
2974,
30751,
3189,
261,
1745,
16,
324,
592,
93,
16,
1241,
14667,
13,
225,
436,
3790,
225,
11370,
3189,
261,
1937,
16,
679,
16,
10725,
16,
324,
592,
93,
13,
327,
1850,
5267,
434,
326,
2522,
2974,
30751,
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,
752,
774,
30751,
12,
203,
3639,
1758,
16,
203,
3639,
1758,
5793,
16,
203,
3639,
14493,
1176,
92,
8201,
18,
966,
2502,
1123,
16,
203,
3639,
14493,
1176,
92,
8201,
18,
751,
2502,
501,
16,
203,
3639,
10560,
774,
30751,
18,
774,
30751,
3790,
3778,
268,
3790,
16,
203,
3639,
10560,
774,
30751,
18,
11066,
3790,
3778,
436,
3790,
203,
565,
262,
203,
3639,
1071,
203,
3639,
1135,
261,
2867,
13,
203,
565,
288,
203,
3639,
2583,
24899,
4169,
3727,
15947,
1176,
92,
12,
1376,
16,
501,
16,
5793,
3631,
315,
10136,
506,
2935,
358,
999,
14493,
1176,
92,
8863,
203,
203,
3639,
2583,
12,
88,
3790,
18,
70,
592,
93,
405,
374,
16,
315,
774,
30751,
324,
592,
93,
1297,
506,
6802,
2353,
374,
8863,
203,
3639,
2583,
12,
86,
3790,
18,
70,
592,
93,
1648,
268,
3790,
18,
70,
592,
93,
16,
315,
11066,
324,
592,
93,
2780,
9943,
2974,
30751,
324,
592,
93,
8863,
203,
203,
3639,
2254,
5034,
1177,
273,
6246,
270,
1176,
92,
3163,
12,
1376,
18,
4299,
2934,
588,
1444,
5621,
203,
3639,
1758,
268,
1887,
273,
1758,
12,
2704,
14493,
1176,
92,
774,
30751,
12,
1589,
16,
1123,
18,
4299,
10019,
203,
203,
3639,
6246,
270,
1176,
92,
3163,
12,
1376,
18,
4299,
2934,
542,
8924,
559,
12,
88,
1887,
16,
2254,
5034,
12,
5664,
3163,
18,
8924,
559,
18,
774,
30751,
10019,
203,
3639,
501,
18,
454,
774,
321,
301,
4877,
18,
6206,
12,
88,
1887,
1769,
203,
203,
3639,
10560,
774,
30751,
18,
2
] |
pragma solidity ^0.4.21;
/*
* @author Ivan Borisov(Github.com/pillardevelopment)
*/
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);
uint256 c = a / b;
assert(a == b * c + a % b);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
function Ownable() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
}
contract TokenERC20 is Ownable {
using SafeMath for uint;
string public name = "Your Open Direct Sales Ecosystem";
string public symbol = "YODSE";
uint256 public decimals = 18;
uint256 DEC = 10 ** uint256(decimals);
address public owner;
uint256 public totalSupply = 100000000*DEC;
uint256 public avaliableSupply;
mapping (address => uint256) public balanceOf;
event Transfer(address indexed from, address indexed to, uint256 value);
event Burn(address indexed from, uint256 value);
function TokenERC20() public
{
balanceOf[msg.sender] = totalSupply;
avaliableSupply = balanceOf[msg.sender];
owner = msg.sender;
}
function _transfer(address _from, address _to, uint256 _value) internal {
require(_to != 0x0);
require(balanceOf[_from] >= _value);
require(balanceOf[_to] + _value > balanceOf[_to]);
uint previousBalances = balanceOf[_from] + balanceOf[_to];
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
emit Transfer(_from, _to, _value);
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balanceOf[_who]);
balanceOf[_who] = balanceOf[_who].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
|
@author Ivan Borisov(Github.com/pillardevelopment)/
|
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 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);
uint256 c = a / b;
assert(a == b * 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;
}
}
| 1,805,154 |
[
1,
45,
90,
304,
605,
280,
291,
1527,
12,
31522,
18,
832,
19,
17726,
26630,
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,
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,
12083,
14060,
10477,
288,
203,
203,
565,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
69,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
3639,
1815,
12,
71,
342,
279,
422,
324,
1769,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
14064,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
261,
69,
422,
374,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
3639,
2254,
5034,
276,
273,
279,
380,
324,
31,
203,
3639,
1815,
12,
71,
342,
279,
422,
324,
1769,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
3739,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
1815,
12,
70,
405,
374,
1769,
203,
3639,
2254,
5034,
276,
273,
279,
342,
324,
31,
203,
3639,
1815,
12,
69,
422,
324,
380,
276,
397,
279,
738,
324,
1769,
203,
3639,
327,
276,
31,
203,
565,
289,
203,
203,
565,
445,
720,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2713,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
1815,
12,
70,
1648,
279,
1769,
203,
3639,
327,
279,
300,
324,
31,
203,
565,
289,
203,
203,
565,
445,
527,
12,
11890,
5034,
279,
16,
2254,
5034,
324,
13,
2
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.